Skip to main content

script/dom/security/
csp.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6
7/// Used to determine which inline check to run
8pub use content_security_policy::InlineCheckType;
9/// Used to report CSP violations in Fetch handlers
10pub use content_security_policy::Violation;
11use content_security_policy::{
12    CheckResult, CspList, Destination, Element as CspElement, Initiator, NavigationCheckType,
13    Origin, ParserMetadata, PolicyDisposition, PolicySource, Request, Response as CspResponse,
14    ViolationResource,
15};
16use http::header::{HeaderMap, HeaderValue, ValueIter};
17use hyper_serde::Serde;
18use js::context::JSContext;
19use js::realm::CurrentRealm;
20use js::rust::describe_scripted_caller;
21use log::warn;
22use servo_constellation_traits::{LoadData, LoadOrigin};
23use url::Url;
24
25use super::csppolicyviolationreport::CSPViolationReportBuilder;
26use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
27use crate::dom::bindings::codegen::UnionTypes::TrustedScriptOrString;
28use crate::dom::bindings::inheritance::Castable;
29use crate::dom::bindings::refcounted::Trusted;
30use crate::dom::bindings::root::DomRoot;
31use crate::dom::element::Element;
32use crate::dom::globalscope::GlobalScope;
33use crate::dom::node::{Node, NodeTraits};
34use crate::dom::reporting::reportingobserver::ReportingObserver;
35use crate::dom::security::cspviolationreporttask::CSPViolationReportTask;
36use crate::dom::trustedtypes::trustedscript::TrustedScript;
37use crate::dom::window::Window;
38use crate::tasks::task::TaskOnce;
39
40pub(crate) trait CspReporting {
41    fn is_js_evaluation_allowed(
42        &self,
43        cx: &mut JSContext,
44        global: &GlobalScope,
45        source: &str,
46    ) -> bool;
47    fn is_wasm_evaluation_allowed(&self, cx: &mut JSContext, global: &GlobalScope) -> bool;
48    fn should_navigation_request_be_blocked(
49        &self,
50        cx: &mut JSContext,
51        global: &GlobalScope,
52        load_data: &mut LoadData,
53        element: Option<&Element>,
54    ) -> bool;
55    fn should_navigation_response_to_navigation_request_be_blocked(
56        &self,
57        cx: &mut JSContext,
58        window: &Window,
59        url: Url,
60        self_origin: &url::Origin,
61    ) -> bool;
62    fn should_elements_inline_type_behavior_be_blocked(
63        &self,
64        cx: &mut JSContext,
65        global: &GlobalScope,
66        el: &Element,
67        type_: InlineCheckType,
68        source: &str,
69        current_line: u32,
70    ) -> bool;
71    fn is_trusted_type_policy_creation_allowed(
72        &self,
73        cx: &mut JSContext,
74        global: &GlobalScope,
75        policy_name: &str,
76        created_policy_names: &[&str],
77    ) -> bool;
78    fn does_sink_type_require_trusted_types(
79        &self,
80        sink_group: &str,
81        include_report_only_policies: bool,
82    ) -> bool;
83    fn should_sink_type_mismatch_violation_be_blocked_by_csp(
84        &self,
85        cx: &mut JSContext,
86        global: &GlobalScope,
87        sink: &str,
88        sink_group: &str,
89        source: &str,
90    ) -> bool;
91    fn is_base_allowed_for_document(
92        &self,
93        cx: &mut JSContext,
94        global: &GlobalScope,
95        base: &url::Url,
96        self_origin: &url::Origin,
97    ) -> bool;
98    fn concatenate(self, new_csp_list: Option<CspList>) -> Option<CspList>;
99}
100
101impl CspReporting for Option<CspList> {
102    /// <https://www.w3.org/TR/CSP/#can-compile-strings>
103    fn is_js_evaluation_allowed(
104        &self,
105        cx: &mut JSContext,
106        global: &GlobalScope,
107        source: &str,
108    ) -> bool {
109        let Some(csp_list) = self else {
110            return true;
111        };
112
113        let (is_js_evaluation_allowed, violations) = csp_list.is_js_evaluation_allowed(source);
114
115        global.report_csp_violations(cx, violations, None, None);
116
117        is_js_evaluation_allowed == CheckResult::Allowed
118    }
119
120    /// <https://www.w3.org/TR/CSP/#can-compile-wasm-bytes>
121    fn is_wasm_evaluation_allowed(&self, cx: &mut JSContext, global: &GlobalScope) -> bool {
122        let Some(csp_list) = self else {
123            return true;
124        };
125
126        let (is_wasm_evaluation_allowed, violations) = csp_list.is_wasm_evaluation_allowed();
127
128        global.report_csp_violations(cx, violations, None, None);
129
130        is_wasm_evaluation_allowed == CheckResult::Allowed
131    }
132
133    /// <https://www.w3.org/TR/CSP/#should-block-navigation-request>
134    fn should_navigation_request_be_blocked(
135        &self,
136        cx: &mut JSContext,
137        global: &GlobalScope,
138        load_data: &mut LoadData,
139        element: Option<&Element>,
140    ) -> bool {
141        let Some(csp_list) = self else {
142            return false;
143        };
144        let mut request = Request {
145            url: load_data.url.clone().into_url(),
146            // TODO: Figure out how to propagate redirect data from LoadData into here
147            current_url: load_data.url.clone().into_url(),
148            origin: match &load_data.load_origin {
149                LoadOrigin::Script(origin) => origin.immutable().clone().into_url_origin(),
150                _ => Origin::new_opaque(),
151            },
152            // TODO: populate this field correctly
153            redirect_count: 0,
154            destination: Destination::None,
155            initiator: Initiator::None,
156            nonce: "".to_owned(),
157            integrity_metadata: "".to_owned(),
158            parser_metadata: ParserMetadata::None,
159        };
160        // TODO: set correct navigation check type for form submission if applicable
161        let (result, violations) = csp_list.should_navigation_request_be_blocked(
162            &mut request,
163            NavigationCheckType::Other,
164            |script_source| {
165                // Step 4. Let convertedScriptSource be the result of executing
166                // Process value with a default policy algorithm, with the following arguments:
167                TrustedScript::get_trusted_type_compliant_string(
168                    cx,
169                    global,
170                    TrustedScriptOrString::String(script_source.into()),
171                    "Location href",
172                )
173                .ok()
174                .map(|s| s.into())
175            },
176        );
177
178        // In case trusted types processing has changed the Javascript contents
179        load_data.url = request.url.into();
180
181        global.report_csp_violations(cx, violations, element, None);
182
183        result == CheckResult::Blocked
184    }
185
186    /// <https://w3c.github.io/webappsec-csp/#should-block-navigation-response>
187    fn should_navigation_response_to_navigation_request_be_blocked(
188        &self,
189        cx: &mut JSContext,
190        window: &Window,
191        url: Url,
192        self_origin: &url::Origin,
193    ) -> bool {
194        let Some(csp_list) = self else {
195            return false;
196        };
197
198        let mut window_proxy = window.window_proxy();
199        let mut parent_navigable_origins = vec![];
200        loop {
201            // Same-origin parents can go via their own script-thread (fast-path)
202            if let Some(container_element) = window_proxy.frame_element() {
203                let container_document = container_element.owner_document();
204                let parent_origin = Url::parse(
205                    container_document
206                        .origin()
207                        .immutable()
208                        .ascii_serialization()
209                        .as_ref(),
210                )
211                .expect("Must always be able to parse document origin");
212                parent_navigable_origins.push(parent_origin);
213                window_proxy = container_document.window().window_proxy();
214                continue;
215            }
216            // Cross-origin parents go via the constellation (slower)
217            if let Some(parent_proxy) = window_proxy.parent() {
218                let Some(parent_origin) = parent_proxy.document_origin() else {
219                    break;
220                };
221                let parent_origin = parent_origin.immutable().ascii_serialization();
222                let parent_origin = Url::parse(&parent_origin)
223                    .expect("Must always be able to parse document origin");
224                parent_navigable_origins.push(parent_origin);
225                window_proxy = DomRoot::from_ref(parent_proxy);
226                continue;
227            }
228            // We don't have a parent, hence we stop traversing
229            break;
230        }
231
232        let (is_navigation_response_blocked, violations) = csp_list
233            .should_navigation_response_to_navigation_request_be_blocked(
234                &CspResponse {
235                    url,
236                    redirect_count: 0,
237                },
238                self_origin,
239                &parent_navigable_origins,
240            );
241
242        window
243            .as_global_scope()
244            .report_csp_violations(cx, violations, None, None);
245
246        is_navigation_response_blocked == CheckResult::Blocked
247    }
248
249    /// <https://www.w3.org/TR/CSP/#should-block-inline>
250    fn should_elements_inline_type_behavior_be_blocked(
251        &self,
252        cx: &mut JSContext,
253        global: &GlobalScope,
254        el: &Element,
255        type_: InlineCheckType,
256        source: &str,
257        current_line: u32,
258    ) -> bool {
259        let Some(csp_list) = self else {
260            return false;
261        };
262        let element = CspElement {
263            nonce: if el.is_nonceable() {
264                Some(Cow::Owned(el.nonce_value().trim().to_owned()))
265            } else {
266                None
267            },
268        };
269        let (result, violations) =
270            csp_list.should_elements_inline_type_behavior_be_blocked(&element, type_, source);
271
272        let source_position = el.compute_source_position(current_line.saturating_sub(2).max(1));
273
274        global.report_csp_violations(cx, violations, Some(el), Some(source_position));
275
276        result == CheckResult::Blocked
277    }
278
279    /// <https://w3c.github.io/trusted-types/dist/spec/#should-block-create-policy>
280    fn is_trusted_type_policy_creation_allowed(
281        &self,
282        cx: &mut JSContext,
283        global: &GlobalScope,
284        policy_name: &str,
285        created_policy_names: &[&str],
286    ) -> bool {
287        let Some(csp_list) = self else {
288            return true;
289        };
290
291        let (allowed_by_csp, violations) =
292            csp_list.is_trusted_type_policy_creation_allowed(policy_name, created_policy_names);
293
294        global.report_csp_violations(cx, violations, None, None);
295
296        allowed_by_csp == CheckResult::Allowed
297    }
298
299    /// <https://w3c.github.io/trusted-types/dist/spec/#abstract-opdef-does-sink-type-require-trusted-types>
300    fn does_sink_type_require_trusted_types(
301        &self,
302        sink_group: &str,
303        include_report_only_policies: bool,
304    ) -> bool {
305        let Some(csp_list) = self else {
306            return false;
307        };
308
309        csp_list.does_sink_type_require_trusted_types(sink_group, include_report_only_policies)
310    }
311
312    /// <https://w3c.github.io/trusted-types/dist/spec/#should-block-sink-type-mismatch>
313    fn should_sink_type_mismatch_violation_be_blocked_by_csp(
314        &self,
315        cx: &mut JSContext,
316        global: &GlobalScope,
317        sink: &str,
318        sink_group: &str,
319        source: &str,
320    ) -> bool {
321        let Some(csp_list) = self else {
322            return false;
323        };
324
325        let (allowed_by_csp, violations) = csp_list
326            .should_sink_type_mismatch_violation_be_blocked_by_csp(sink, sink_group, source);
327
328        global.report_csp_violations(cx, violations, None, None);
329
330        allowed_by_csp == CheckResult::Blocked
331    }
332
333    /// <https://www.w3.org/TR/CSP3/#allow-base-for-document>
334    fn is_base_allowed_for_document(
335        &self,
336        cx: &mut JSContext,
337        global: &GlobalScope,
338        base: &url::Url,
339        self_origin: &url::Origin,
340    ) -> bool {
341        let Some(csp_list) = self else {
342            return true;
343        };
344
345        let (is_base_allowed, violations) =
346            csp_list.is_base_allowed_for_document(base, self_origin);
347
348        global.report_csp_violations(cx, violations, None, None);
349
350        is_base_allowed == CheckResult::Allowed
351    }
352
353    fn concatenate(self, new_csp_list: Option<CspList>) -> Option<CspList> {
354        let Some(new_csp_list) = new_csp_list else {
355            return self;
356        };
357
358        match self {
359            None => Some(new_csp_list),
360            Some(mut old_csp_list) => {
361                old_csp_list.append(new_csp_list);
362                Some(old_csp_list)
363            },
364        }
365    }
366}
367
368pub(crate) struct SourcePosition {
369    pub(crate) source_file: String,
370    pub(crate) line_number: u32,
371    pub(crate) column_number: u32,
372}
373
374pub(crate) trait GlobalCspReporting {
375    fn report_csp_violations(
376        &self,
377        cx: &mut JSContext,
378        violations: Vec<Violation>,
379        element: Option<&Element>,
380        source_position: Option<SourcePosition>,
381    );
382}
383
384fn compute_scripted_caller_source_position(cx: &mut JSContext) -> SourcePosition {
385    match describe_scripted_caller(cx) {
386        Ok(scripted_caller) => SourcePosition {
387            source_file: scripted_caller.filename,
388            line_number: scripted_caller.line,
389            column_number: scripted_caller.col + 1,
390        },
391        Err(()) => SourcePosition {
392            source_file: String::new(),
393            line_number: 0,
394            column_number: 0,
395        },
396    }
397}
398
399/// <https://www.w3.org/TR/CSP3/#obtain-violation-blocked-uri>
400fn obtain_blocked_uri_for_violation_resource_with_sample(
401    resource: ViolationResource,
402) -> (Option<String>, String) {
403    // Step 1. Assert: resource is a URL or a string.
404    //
405    // Already done since we destructure the relevant enum value
406
407    // Step 3. Return resource.
408    match resource {
409        ViolationResource::Inline { sample } => (sample, "inline".to_owned()),
410        // Step 2. If resource is a URL, return the result of executing § 5.4 Strip URL for use in reports on resource.
411        ViolationResource::Url(url) => (
412            Some(String::new()),
413            ReportingObserver::strip_url_for_reports(url.into()),
414        ),
415        ViolationResource::TrustedTypePolicy { sample } => {
416            (Some(sample), "trusted-types-policy".to_owned())
417        },
418        ViolationResource::TrustedTypeSink { sample } => {
419            (Some(sample), "trusted-types-sink".to_owned())
420        },
421        ViolationResource::Eval { sample } => (sample, "eval".to_owned()),
422        ViolationResource::WasmEval => (None, "wasm-eval".to_owned()),
423    }
424}
425
426fn csp_violation_report_tasks(
427    cx: &mut JSContext,
428    global: &GlobalScope,
429    violations: Vec<Violation>,
430    element: Option<&Element>,
431    source_position: Option<SourcePosition>,
432) -> Vec<CSPViolationReportTask> {
433    if violations.is_empty() {
434        return Vec::new();
435    }
436    warn!("Reporting CSP violations: {:?}", violations);
437    let source_position =
438        source_position.unwrap_or_else(|| compute_scripted_caller_source_position(cx));
439    violations
440        .into_iter()
441        .map(|violation| {
442            let (sample, resource) =
443                obtain_blocked_uri_for_violation_resource_with_sample(violation.resource);
444            let report = CSPViolationReportBuilder::default()
445                .resource(resource)
446                .sample(sample)
447                .effective_directive(violation.directive.name)
448                .original_policy(violation.policy.to_string())
449                .report_only(violation.policy.disposition == PolicyDisposition::Report)
450                .source_file(source_position.source_file.clone())
451                .line_number(source_position.line_number)
452                .column_number(source_position.column_number)
453                .build(global);
454            // Step 1: Let global be violation’s global object.
455            // We use the passed-in `global` as the violation's global object.
456            // Step 2: Let target be violation’s element.
457            let target = element.and_then(|event_target| {
458                // Step 3.1: If target is not null, and global is a Window,
459                // and target’s shadow-including root is not global’s associated Document, set target to null.
460                if let Some(window) = global.downcast::<Window>() {
461                    // If a node is connected, its owner document is always the shadow-including root.
462                    // If it isn't connected, then it also doesn't have a corresponding document, hence
463                    // it can't be this document.
464                    if event_target.upcast::<Node>().owner_document() != window.Document() {
465                        return None;
466                    }
467                }
468                Some(event_target)
469            });
470            let target = match target {
471                // Step 3.2: If target is null:
472                None => {
473                    // Step 3.2.2: If target is a Window, set target to target’s associated Document.
474                    if let Some(window) = global.downcast::<Window>() {
475                        Trusted::new(window.Document().upcast())
476                    } else {
477                        // Step 3.2.1: Set target to violation’s global object.
478                        Trusted::new(global.upcast())
479                    }
480                },
481                Some(event_target) => Trusted::new(event_target.upcast()),
482            };
483            CSPViolationReportTask::new(Trusted::new(global), target, report, violation.policy)
484        })
485        .collect()
486}
487
488impl GlobalScope {
489    pub(crate) fn run_worker_csp_violation_report_tasks(
490        &self,
491        violations: Vec<Violation>,
492        cx: &mut CurrentRealm,
493    ) {
494        // Worker CSP violations already crossed an event-loop boundary via
495        // `CommonScriptMsg::ReportCspViolations`, so run the queued report
496        // task here instead of adding another queued task on the owner global.
497        for task in csp_violation_report_tasks(cx, self, violations, None, None) {
498            task.run_once(cx);
499        }
500    }
501}
502
503impl GlobalCspReporting for GlobalScope {
504    /// <https://www.w3.org/TR/CSP/#report-violation>
505    fn report_csp_violations(
506        &self,
507        cx: &mut JSContext,
508        violations: Vec<Violation>,
509        element: Option<&Element>,
510        source_position: Option<SourcePosition>,
511    ) {
512        // Step 3: Queue a task to run the following steps:
513        for task in csp_violation_report_tasks(cx, self, violations, element, source_position) {
514            self.task_manager()
515                .dom_manipulation_task_source()
516                .queue(task);
517        }
518    }
519}
520
521fn parse_and_potentially_append_to_csp_list(
522    old_csp_list: Option<CspList>,
523    csp_header_iter: ValueIter<HeaderValue>,
524    disposition: PolicyDisposition,
525) -> Option<CspList> {
526    let mut csp_list = old_csp_list;
527    for header in csp_header_iter {
528        // This silently ignores the CSP if it contains invalid Unicode.
529        // We should probably report an error somewhere.
530        let new_csp_list = header
531            .to_str()
532            .ok()
533            .map(|value| CspList::parse(value, PolicySource::Header, disposition));
534        csp_list = csp_list.concatenate(new_csp_list);
535    }
536    csp_list
537}
538
539/// <https://www.w3.org/TR/CSP/#parse-response-csp>
540pub(crate) fn parse_csp_list_from_metadata(headers: &Option<Serde<HeaderMap>>) -> Option<CspList> {
541    let headers = headers.as_ref()?;
542    let csp_enforce_list = parse_and_potentially_append_to_csp_list(
543        None,
544        headers.get_all("content-security-policy").iter(),
545        PolicyDisposition::Enforce,
546    );
547
548    parse_and_potentially_append_to_csp_list(
549        csp_enforce_list,
550        headers
551            .get_all("content-security-policy-report-only")
552            .iter(),
553        PolicyDisposition::Report,
554    )
555}