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