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_safe;
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                )
210                .expect("Must always be able to parse document origin");
211                parent_navigable_origins.push(parent_origin);
212                window_proxy = container_document.window().window_proxy();
213                continue;
214            }
215            // Cross-origin parents go via the constellation (slower)
216            if let Some(parent_proxy) = window_proxy.parent() {
217                let Some(parent_origin) = parent_proxy.document_origin() else {
218                    break;
219                };
220                let parent_origin = Url::parse(&parent_origin)
221                    .expect("Must always be able to parse document origin");
222                parent_navigable_origins.push(parent_origin);
223                window_proxy = DomRoot::from_ref(parent_proxy);
224                continue;
225            }
226            // We don't have a parent, hence we stop traversing
227            break;
228        }
229
230        let (is_navigation_response_blocked, violations) = csp_list
231            .should_navigation_response_to_navigation_request_be_blocked(
232                &CspResponse {
233                    url,
234                    redirect_count: 0,
235                },
236                self_origin,
237                &parent_navigable_origins,
238            );
239
240        window
241            .as_global_scope()
242            .report_csp_violations(cx, violations, None, None);
243
244        is_navigation_response_blocked == CheckResult::Blocked
245    }
246
247    /// <https://www.w3.org/TR/CSP/#should-block-inline>
248    fn should_elements_inline_type_behavior_be_blocked(
249        &self,
250        cx: &mut JSContext,
251        global: &GlobalScope,
252        el: &Element,
253        type_: InlineCheckType,
254        source: &str,
255        current_line: u32,
256    ) -> bool {
257        let Some(csp_list) = self else {
258            return false;
259        };
260        let element = CspElement {
261            nonce: if el.is_nonceable() {
262                Some(Cow::Owned(el.nonce_value().trim().to_owned()))
263            } else {
264                None
265            },
266        };
267        let (result, violations) =
268            csp_list.should_elements_inline_type_behavior_be_blocked(&element, type_, source);
269
270        let source_position = el.compute_source_position(current_line.saturating_sub(2).max(1));
271
272        global.report_csp_violations(cx, violations, Some(el), Some(source_position));
273
274        result == CheckResult::Blocked
275    }
276
277    /// <https://w3c.github.io/trusted-types/dist/spec/#should-block-create-policy>
278    fn is_trusted_type_policy_creation_allowed(
279        &self,
280        cx: &mut JSContext,
281        global: &GlobalScope,
282        policy_name: &str,
283        created_policy_names: &[&str],
284    ) -> bool {
285        let Some(csp_list) = self else {
286            return true;
287        };
288
289        let (allowed_by_csp, violations) =
290            csp_list.is_trusted_type_policy_creation_allowed(policy_name, created_policy_names);
291
292        global.report_csp_violations(cx, violations, None, None);
293
294        allowed_by_csp == CheckResult::Allowed
295    }
296
297    /// <https://w3c.github.io/trusted-types/dist/spec/#abstract-opdef-does-sink-type-require-trusted-types>
298    fn does_sink_type_require_trusted_types(
299        &self,
300        sink_group: &str,
301        include_report_only_policies: bool,
302    ) -> bool {
303        let Some(csp_list) = self else {
304            return false;
305        };
306
307        csp_list.does_sink_type_require_trusted_types(sink_group, include_report_only_policies)
308    }
309
310    /// <https://w3c.github.io/trusted-types/dist/spec/#should-block-sink-type-mismatch>
311    fn should_sink_type_mismatch_violation_be_blocked_by_csp(
312        &self,
313        cx: &mut JSContext,
314        global: &GlobalScope,
315        sink: &str,
316        sink_group: &str,
317        source: &str,
318    ) -> bool {
319        let Some(csp_list) = self else {
320            return false;
321        };
322
323        let (allowed_by_csp, violations) = csp_list
324            .should_sink_type_mismatch_violation_be_blocked_by_csp(sink, sink_group, source);
325
326        global.report_csp_violations(cx, violations, None, None);
327
328        allowed_by_csp == CheckResult::Blocked
329    }
330
331    /// <https://www.w3.org/TR/CSP3/#allow-base-for-document>
332    fn is_base_allowed_for_document(
333        &self,
334        cx: &mut JSContext,
335        global: &GlobalScope,
336        base: &url::Url,
337        self_origin: &url::Origin,
338    ) -> bool {
339        let Some(csp_list) = self else {
340            return true;
341        };
342
343        let (is_base_allowed, violations) =
344            csp_list.is_base_allowed_for_document(base, self_origin);
345
346        global.report_csp_violations(cx, violations, None, None);
347
348        is_base_allowed == CheckResult::Allowed
349    }
350
351    fn concatenate(self, new_csp_list: Option<CspList>) -> Option<CspList> {
352        let Some(new_csp_list) = new_csp_list else {
353            return self;
354        };
355
356        match self {
357            None => Some(new_csp_list),
358            Some(mut old_csp_list) => {
359                old_csp_list.append(new_csp_list);
360                Some(old_csp_list)
361            },
362        }
363    }
364}
365
366pub(crate) struct SourcePosition {
367    pub(crate) source_file: String,
368    pub(crate) line_number: u32,
369    pub(crate) column_number: u32,
370}
371
372pub(crate) trait GlobalCspReporting {
373    fn report_csp_violations(
374        &self,
375        cx: &mut JSContext,
376        violations: Vec<Violation>,
377        element: Option<&Element>,
378        source_position: Option<SourcePosition>,
379    );
380}
381
382fn compute_scripted_caller_source_position(cx: &mut JSContext) -> SourcePosition {
383    match describe_scripted_caller_safe(cx) {
384        Ok(scripted_caller) => SourcePosition {
385            source_file: scripted_caller.filename,
386            line_number: scripted_caller.line,
387            column_number: scripted_caller.col + 1,
388        },
389        Err(()) => SourcePosition {
390            source_file: String::new(),
391            line_number: 0,
392            column_number: 0,
393        },
394    }
395}
396
397/// <https://www.w3.org/TR/CSP3/#obtain-violation-blocked-uri>
398fn obtain_blocked_uri_for_violation_resource_with_sample(
399    resource: ViolationResource,
400) -> (Option<String>, String) {
401    // Step 1. Assert: resource is a URL or a string.
402    //
403    // Already done since we destructure the relevant enum value
404
405    // Step 3. Return resource.
406    match resource {
407        ViolationResource::Inline { sample } => (sample, "inline".to_owned()),
408        // Step 2. If resource is a URL, return the result of executing § 5.4 Strip URL for use in reports on resource.
409        ViolationResource::Url(url) => (
410            Some(String::new()),
411            ReportingObserver::strip_url_for_reports(url.into()),
412        ),
413        ViolationResource::TrustedTypePolicy { sample } => {
414            (Some(sample), "trusted-types-policy".to_owned())
415        },
416        ViolationResource::TrustedTypeSink { sample } => {
417            (Some(sample), "trusted-types-sink".to_owned())
418        },
419        ViolationResource::Eval { sample } => (sample, "eval".to_owned()),
420        ViolationResource::WasmEval => (None, "wasm-eval".to_owned()),
421    }
422}
423
424fn csp_violation_report_tasks(
425    cx: &mut JSContext,
426    global: &GlobalScope,
427    violations: Vec<Violation>,
428    element: Option<&Element>,
429    source_position: Option<SourcePosition>,
430) -> Vec<CSPViolationReportTask> {
431    if violations.is_empty() {
432        return Vec::new();
433    }
434    warn!("Reporting CSP violations: {:?}", violations);
435    let source_position =
436        source_position.unwrap_or_else(|| compute_scripted_caller_source_position(cx));
437    violations
438        .into_iter()
439        .map(|violation| {
440            let (sample, resource) =
441                obtain_blocked_uri_for_violation_resource_with_sample(violation.resource);
442            let report = CSPViolationReportBuilder::default()
443                .resource(resource)
444                .sample(sample)
445                .effective_directive(violation.directive.name)
446                .original_policy(violation.policy.to_string())
447                .report_only(violation.policy.disposition == PolicyDisposition::Report)
448                .source_file(source_position.source_file.clone())
449                .line_number(source_position.line_number)
450                .column_number(source_position.column_number)
451                .build(global);
452            // Step 1: Let global be violation’s global object.
453            // We use the passed-in `global` as the violation's global object.
454            // Step 2: Let target be violation’s element.
455            let target = element.and_then(|event_target| {
456                // Step 3.1: If target is not null, and global is a Window,
457                // and target’s shadow-including root is not global’s associated Document, set target to null.
458                if let Some(window) = global.downcast::<Window>() {
459                    // If a node is connected, its owner document is always the shadow-including root.
460                    // If it isn't connected, then it also doesn't have a corresponding document, hence
461                    // it can't be this document.
462                    if event_target.upcast::<Node>().owner_document() != window.Document() {
463                        return None;
464                    }
465                }
466                Some(event_target)
467            });
468            let target = match target {
469                // Step 3.2: If target is null:
470                None => {
471                    // Step 3.2.2: If target is a Window, set target to target’s associated Document.
472                    if let Some(window) = global.downcast::<Window>() {
473                        Trusted::new(window.Document().upcast())
474                    } else {
475                        // Step 3.2.1: Set target to violation’s global object.
476                        Trusted::new(global.upcast())
477                    }
478                },
479                Some(event_target) => Trusted::new(event_target.upcast()),
480            };
481            CSPViolationReportTask::new(Trusted::new(global), target, report, violation.policy)
482        })
483        .collect()
484}
485
486impl GlobalScope {
487    pub(crate) fn run_worker_csp_violation_report_tasks(
488        &self,
489        violations: Vec<Violation>,
490        cx: &mut CurrentRealm,
491    ) {
492        // Worker CSP violations already crossed an event-loop boundary via
493        // `CommonScriptMsg::ReportCspViolations`, so run the queued report
494        // task here instead of adding another queued task on the owner global.
495        for task in csp_violation_report_tasks(cx, self, violations, None, None) {
496            task.run_once(cx);
497        }
498    }
499}
500
501impl GlobalCspReporting for GlobalScope {
502    /// <https://www.w3.org/TR/CSP/#report-violation>
503    fn report_csp_violations(
504        &self,
505        cx: &mut JSContext,
506        violations: Vec<Violation>,
507        element: Option<&Element>,
508        source_position: Option<SourcePosition>,
509    ) {
510        // Step 3: Queue a task to run the following steps:
511        for task in csp_violation_report_tasks(cx, self, violations, element, source_position) {
512            self.task_manager()
513                .dom_manipulation_task_source()
514                .queue(task);
515        }
516    }
517}
518
519fn parse_and_potentially_append_to_csp_list(
520    old_csp_list: Option<CspList>,
521    csp_header_iter: ValueIter<HeaderValue>,
522    disposition: PolicyDisposition,
523) -> Option<CspList> {
524    let mut csp_list = old_csp_list;
525    for header in csp_header_iter {
526        // This silently ignores the CSP if it contains invalid Unicode.
527        // We should probably report an error somewhere.
528        let new_csp_list = header
529            .to_str()
530            .ok()
531            .map(|value| CspList::parse(value, PolicySource::Header, disposition));
532        csp_list = csp_list.concatenate(new_csp_list);
533    }
534    csp_list
535}
536
537/// <https://www.w3.org/TR/CSP/#parse-response-csp>
538pub(crate) fn parse_csp_list_from_metadata(headers: &Option<Serde<HeaderMap>>) -> Option<CspList> {
539    let headers = headers.as_ref()?;
540    let csp_enforce_list = parse_and_potentially_append_to_csp_list(
541        None,
542        headers.get_all("content-security-policy").iter(),
543        PolicyDisposition::Enforce,
544    );
545
546    parse_and_potentially_append_to_csp_list(
547        csp_enforce_list,
548        headers
549            .get_all("content-security-policy-report-only")
550            .iter(),
551        PolicyDisposition::Report,
552    )
553}