Skip to content

Truly independent web browser

LibWeb: Separate fetch's CSP and SRI checks from DOM-side algorithms

Luke Wildecf50a30e3511
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 8f151f8ec6d..53680fdc877 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -48,6 +48,7 @@ set(SOURCES
ContentSecurityPolicy/Directives/Names.cpp
ContentSecurityPolicy/Directives/SourceExpression.cpp
ContentSecurityPolicy/Directives/WebRTCIntegration.cpp
+ ContentSecurityPolicy/FetchIntegration.cpp
ContentSecurityPolicy/Policy.cpp
ContentSecurityPolicy/PolicyList.cpp
ContentSecurityPolicy/SecurityPolicyViolationEvent.cpp
@@ -830,6 +831,7 @@ set(SOURCES
Speech/SpeechSynthesis.cpp
Speech/SpeechSynthesisUtterance.cpp
Speech/SpeechSynthesisVoice.cpp
+ SRI/IntegrityPolicy.cpp
SRI/SRI.cpp
StorageAPI/NavigatorStorage.cpp
StorageAPI/StorageAreaMirror.cpp
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp
index a3865a86b7e..75fa8b15215 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp
+++ b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.cpp
@@ -9,7 +9,6 @@
#include <LibGC/Heap.h>
#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>
#include <LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h>
-#include <LibWeb/ContentSecurityPolicy/Directives/FetchIntegration.h>
#include <LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h>
#include <LibWeb/ContentSecurityPolicy/Directives/KeywordSources.h>
#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
@@ -23,7 +22,6 @@
#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
-#include <LibWeb/SRI/SRI.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWeb/TrustedTypes/TrustedScript.h>
#include <LibWeb/TrustedTypes/TrustedTypePolicy.h>
@@ -33,81 +31,6 @@
namespace Web::ContentSecurityPolicy {
-// https://w3c.github.io/webappsec-csp/#does-resource-hint-violate-policy
-[[nodiscard]] static Directives::Directive const* does_resource_hint_request_violate_policy(Fetch::Infrastructure::Request const& request, Policy const& policy)
-{
- // 1. Let defaultDirective be policy’s first directive whose name is "default-src".
- auto default_directive_iterator = policy.directives().find_if([](auto const& directive) {
- return directive.kind() == Directives::Directive::Kind::DefaultSrc;
- });
-
- // 2. If defaultDirective does not exist, return "Does Not Violate".
- if (default_directive_iterator.is_end())
- return nullptr;
-
- // 3. For each directive of policy:
- for (auto const& directive : policy.directives()) {
- // 1. Let result be the result of executing directive’s pre-request check on request and policy.
- auto result = Directives::pre_request_check(directive, request, policy);
-
- // 2. If result is "Allowed", then return "Does Not Violate".
- if (result == Directives::Directive::Result::Allowed) {
- return nullptr;
- }
- }
-
- // 4. Return defaultDirective.
- return &*default_directive_iterator;
-}
-
-// https://w3c.github.io/webappsec-csp/#does-request-violate-policy
-[[nodiscard]] static Directives::Directive const* does_request_violate_policy(Fetch::Infrastructure::Request const& request, Policy const& policy)
-{
- // 1. If request’s initiator is "prefetch", then return the result of executing § 6.7.2.2 Does resource hint
- // request violate policy? on request and policy.
- if (request.initiator() == Fetch::Infrastructure::Request::Initiator::Prefetch)
- return does_resource_hint_request_violate_policy(request, policy);
-
- // 2. Let violates be "Does Not Violate".
- Directives::Directive const* violates = nullptr;
-
- // 3. For each directive of policy:
- for (auto const& directive : policy.directives()) {
- // 1. Let result be the result of executing directive’s pre-request check on request and policy.
- auto result = Directives::pre_request_check(directive, request, policy);
-
- // 2. If result is "Blocked", then let violates be directive.
- if (result == Directives::Directive::Result::Blocked) {
- violates = &directive;
- }
- }
-
- // 4. Return violates.
- return violates;
-}
-
-// https://w3c.github.io/webappsec-csp/#report-for-request
-void report_content_security_policy_violations_for_request(Fetch::Infrastructure::Request const& request, ViolationReporter const& report_violation)
-{
- // 1. Let CSP list be request’s policy container's CSP list.
- auto const& csp_list = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list;
-
- // 2. For each policy of CSP list:
- for (auto const& policy : csp_list.policies()) {
- // 1. If policy’s disposition is "enforce", then skip to the next policy.
- if (policy->disposition() == Policy::Disposition::Enforce)
- continue;
-
- // 2. Let violates be the result of executing § 6.7.2.1 Does request violate policy? on request and policy.
- auto violates = does_request_violate_policy(request, policy);
-
- // 3. If violates is not "Does Not Violate", then execute § 5.5 Report a violation on the result of executing
- // § 2.4.2 Create a violation object for request, and policy. on request, and policy.
- if (violates)
- report_violation(policy);
- }
-}
-
ViolationReporter violation_reporter_for_request(JS::Realm& realm, GC::Ref<Fetch::Infrastructure::Request> request)
{
return [&realm, request](NonnullRefPtr<Policy const> policy) {
@@ -116,132 +39,6 @@ ViolationReporter violation_reporter_for_request(JS::Realm& realm, GC::Ref<Fetch
};
}
-// https://w3c.github.io/webappsec-csp/#should-block-request
-Directives::Directive::Result should_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Request const& request, ViolationReporter const& report_violation)
-{
- // 1. Let CSP list be request’s policy container's CSP list.
- auto const& csp_list = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list;
-
- // 2. Let result be "Allowed".
- auto result = Directives::Directive::Result::Allowed;
-
- // 3. For each policy of CSP list:
- for (auto const& policy : csp_list.policies()) {
- // 1. If policy’s disposition is "report", then skip to the next policy.
- if (policy->disposition() == Policy::Disposition::Report)
- continue;
-
- // 2. Let violates be the result of executing § 6.7.2.1 Does request violate policy? on request and policy.
- auto violates = does_request_violate_policy(request, policy);
-
- // 3. If violates is not "Does Not Violate", then:
- if (violates) {
- // 1. Execute § 5.5 Report a violation on the result of executing § 2.4.2 Create a violation object for
- // request, and policy. on request, and policy.
- report_violation(policy);
-
- // 2. Set result to "Blocked".
- result = Directives::Directive::Result::Blocked;
- }
- }
-
- // 4. Return result.
- return result;
-}
-
-// https://w3c.github.io/webappsec-subresource-integrity/#should-request-be-blocked-by-integrity-policy
-Directives::Directive::Result should_request_be_blocked_by_integrity_policy(GC::Ref<Fetch::Infrastructure::Request> request)
-{
- VERIFY(request->policy_container().has<NonnullRefPtr<HTML::PolicyContainer const>>());
-
- // 1. Let policyContainer be request’s policy container.
- auto const& policy_container = request->policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>();
-
- // 2. Let parsedMetadata be the result of calling parse metadata with request’s integrity metadata.
- auto parsed_metadata = MUST(SRI::parse_metadata(request->integrity_metadata().utf16_view()));
-
- // 3. If parsedMetadata is not the empty set and request’s mode is either "cors" or "same-origin", return "Allowed".
- if (!parsed_metadata.is_empty() && (request->mode() == Fetch::Infrastructure::Request::Mode::CORS || request->mode() == Fetch::Infrastructure::Request::Mode::SameOrigin))
- return Directives::Directive::Result::Allowed;
-
- // 4. If request’s url is local, return "Allowed".
- if (Fetch::Infrastructure::is_local_url(request->url()))
- return Directives::Directive::Result::Allowed;
-
- // 5. Let policy be policyContainer’s integrity policy.
- auto const& policy = policy_container->integrity_policy;
-
- // 6. Let reportPolicy be policyContainer’s report only integrity policy.
- auto const& report_policy = policy_container->report_only_integrity_policy;
-
- // 7. If both policy and reportPolicy are empty integrity policys, return "Allowed".
- if (policy.is_empty() && report_policy.is_empty())
- return Directives::Directive::Result::Allowed;
-
- // 8. Let global be request’s client’s global object.
- auto& global = request->client()->global_object();
-
- // 9. If global is not a Window nor a WorkerGlobalScope, return "Allowed".
- if (!HTML::window_or_worker_global_scope_from_global_object(global))
- return Directives::Directive::Result::Allowed;
-
- // 10. Let block be a boolean, initially false.
- bool block = false;
-
- // FIXME: 11. Let reportBlock be a boolean, initially false.
- [[maybe_unused]] auto report_block = false;
-
- // 12. If policy’s sources contains "inline" and policy’s blocked destinations contains request’s destination, set block to true.
- if (policy.sources.contains_slow(u"inline"sv)
- && request->destination().has_value()
- && policy.blocked_destinations.contains_slow(request->destination().value()))
- block = true;
-
- // 13. If reportPolicy’s sources contains "inline" and reportPolicy’s blocked destinations contains request’s destination, set reportBlock to true.
- if (report_policy.sources.contains_slow(u"inline"sv)
- && request->destination().has_value()
- && report_policy.blocked_destinations.contains_slow(request->destination().value()))
- report_block = true;
-
- // FIXME: 14. If block is true or reportBlock is true, then report violation with request, block, reportBlock, policy and reportPolicy.
-
- // 15. If block is true, then return "Blocked"; otherwise "Allowed".
- return block ? Directives::Directive::Result::Blocked : Directives::Directive::Result::Allowed;
-}
-
-// https://w3c.github.io/webappsec-csp/#should-block-response
-Directives::Directive::Result should_response_to_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Response const& response, Fetch::Infrastructure::Request const& request, ViolationReporter const& report_violation)
-{
- // 1. Let CSP list be request’s policy container's CSP list.
- auto const& csp_list = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list;
-
- // 2. Let result be "Allowed".
- auto result = Directives::Directive::Result::Allowed;
-
- // 3. For each policy of CSP list:
- // Spec Note: This portion of the check verifies that the page can load the response. That is, that a Service
- // Worker hasn't substituted a file which would violate the page’s CSP.
- for (auto const& policy : csp_list.policies()) {
- // 1. For each directive of policy:
- for (auto const& directive : policy->directives()) {
- // 1. If the result of executing directive’s post-request check is "Blocked", then:
- if (Directives::post_request_check(directive, request, response, policy) == Directives::Directive::Result::Blocked) {
- // 1. Execute § 5.5 Report a violation on the result of executing § 2.4.2 Create a violation object for
- // request, and policy. on request, and policy.
- report_violation(policy);
-
- // 2. If policy’s disposition is "enforce", then set result to "Blocked".
- if (policy->disposition() == Policy::Disposition::Enforce) {
- result = Directives::Directive::Result::Blocked;
- }
- }
- }
- }
-
- // 4. Return result.
- return result;
-}
-
// https://w3c.github.io/webappsec-csp/#should-block-navigation-request
Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_content_security_policy(GC::Ref<Fetch::Infrastructure::Request> navigation_request, Directives::Directive::NavigationType navigation_type)
{
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h
index 049cc6a6281..d8e7e043425 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h
+++ b/Libraries/LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h
@@ -6,23 +6,14 @@
#pragma once
-#include <AK/Function.h>
-#include <AK/NonnullRefPtr.h>
#include <AK/Utf16View.h>
#include <LibJS/Runtime/VM.h>
#include <LibURL/Forward.h>
#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>
+#include <LibWeb/ContentSecurityPolicy/FetchIntegration.h>
namespace Web::ContentSecurityPolicy {
-// Reports the violation for the request being checked and the given policy.
-using ViolationReporter = Function<void(NonnullRefPtr<Policy const>)>;
-
-void report_content_security_policy_violations_for_request(Fetch::Infrastructure::Request const&, ViolationReporter const&);
-Directives::Directive::Result should_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Request const&, ViolationReporter const&);
-Directives::Directive::Result should_request_be_blocked_by_integrity_policy(GC::Ref<Fetch::Infrastructure::Request>);
-Directives::Directive::Result should_response_to_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Response const&, Fetch::Infrastructure::Request const&, ViolationReporter const&);
-
[[nodiscard]] ViolationReporter violation_reporter_for_request(JS::Realm&, GC::Ref<Fetch::Infrastructure::Request>);
Directives::Directive::Result should_navigation_request_of_type_be_blocked_by_content_security_policy(GC::Ref<Fetch::Infrastructure::Request> navigation_request, Directives::Directive::NavigationType navigation_type);
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp b/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp
index 2ea1287bf52..13e18ba7dc1 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp
+++ b/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.cpp
@@ -4,29 +4,17 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Base64.h>
#include <AK/Utf16FlyString.h>
#include <AK/Vector.h>
-#include <LibCrypto/Hash/SHA2.h>
#include <LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h>
#include <LibWeb/ContentSecurityPolicy/Directives/KeywordSources.h>
#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
#include <LibWeb/ContentSecurityPolicy/Directives/SourceExpression.h>
#include <LibWeb/ContentSecurityPolicy/Policy.h>
-#include <LibWeb/DOM/Attr.h>
-#include <LibWeb/DOM/Element.h>
-#include <LibWeb/DOM/NamedNodeMap.h>
-#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
-#include <LibWeb/HTML/HTMLScriptElement.h>
-#include <LibWeb/HTML/HTMLStyleElement.h>
#include <LibWeb/SRI/SRI.h>
-#include <LibWeb/SVG/SVGElement.h>
-#include <LibWeb/SVG/SVGScriptElement.h>
-#include <LibWeb/SVG/SVGStyleElement.h>
#include <LibWebCommon/Fetch/Infrastructure/URL.h>
-#include <LibWebCommon/Infra/Strings.h>
namespace Web::ContentSecurityPolicy::Directives {
@@ -283,40 +271,6 @@ ShouldExecute should_fetch_directive_execute(Optional<Utf16FlyString> effective_
return ShouldExecute::No;
}
-// https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check
-Utf16FlyString get_the_effective_directive_for_inline_checks(Directive::InlineType type)
-{
- // Spec Note: While the effective directive is only defined for requests, in this algorithm it is used similarly to
- // mean the directive that is most relevant to a particular type of inline check.
-
- // Switch on type:
- switch (type) {
- // "script"
- // "navigation"
- // Return script-src-elem.
- case Directive::InlineType::Script:
- case Directive::InlineType::Navigation:
- return Names::ScriptSrcElem;
- // "script attribute"
- // Return script-src-attr.
- case Directive::InlineType::ScriptAttribute:
- return Names::ScriptSrcAttr;
- // "style"
- // Return style-src-elem.
- case Directive::InlineType::Style:
- return Names::StyleSrcElem;
- // "style attribute"
- // Return style-src-attr.
- case Directive::InlineType::StyleAttribute:
- return Names::StyleSrcAttr;
- }
-
- // 2. Return null.
- // FIXME: File spec issue that this should be invalid, as the result of this algorithm ends up being piped into
- // Violation's effective directive, which is defined to be a non-empty string.
- VERIFY_NOT_REACHED();
-}
-
// https://w3c.github.io/webappsec-csp/#scheme-part-match
// An ASCII string scheme-part matches another ASCII string if a CSP source expression that contained the first as a
// scheme-part could potentially match a URL containing the latter as a scheme. For example, we say that "http"
@@ -882,265 +836,4 @@ Directive::Result script_directives_post_request_check(GC::Ref<Fetch::Infrastruc
return Directive::Result::Allowed;
}
-enum class [[nodiscard]] AllowsResult {
- DoesNotAllow,
- Allows,
-};
-
-static AllowsResult does_a_source_list_allow_all_inline_behavior_for_type(Vector<Utf16String> const& source_list, Directive::InlineType type)
-{
- // 1. Let allow all inline be false.
- bool allow_all_inline = false;
-
- // 2. For each expression of list:
- for (auto const& expression : source_list) {
- // 1. If expression matches the nonce-source or hash-source grammar, return "Does Not Allow".
- auto nonce_source_parse_result = parse_source_expression(Production::NonceSource, expression);
- if (nonce_source_parse_result.has_value())
- return AllowsResult::DoesNotAllow;
-
- auto hash_source_parse_result = parse_source_expression(Production::HashSource, expression);
- if (hash_source_parse_result.has_value())
- return AllowsResult::DoesNotAllow;
-
- // 2. If type is "script", "script attribute" or "navigation" and expression matches the keyword-source
- // "'strict-dynamic'", return "Does Not Allow".
- if (type == Directive::InlineType::Script || type == Directive::InlineType::ScriptAttribute || type == Directive::InlineType::Navigation) {
- if (expression.equals_ignoring_ascii_case(KeywordSources::StrictDynamic.view()))
- return AllowsResult::DoesNotAllow;
- }
-
- // 3. If expression is an ASCII case-insensitive match for the keyword-source "'unsafe-inline'", set allow all
- // inline to true.
- if (expression.equals_ignoring_ascii_case(KeywordSources::UnsafeInline.view()))
- allow_all_inline = true;
- }
-
- // 3. If allow all inline is true, return "Allows". Otherwise, return "Does Not Allow".
- return allow_all_inline ? AllowsResult::Allows : AllowsResult::DoesNotAllow;
-}
-
-enum class NonceableResult {
- NotNonceable,
- Nonceable,
-};
-
-// https://w3c.github.io/webappsec-csp/#is-element-nonceable
-[[nodiscard]] static NonceableResult is_element_nonceable(GC::Ptr<DOM::Element const> element)
-{
- // SPEC ISSUE 7: This processing is meant to mitigate the risk of dangling markup attacks that steal the nonce from
- // an existing element in order to load injected script. It is fairly expensive, however, as it
- // requires that we walk through all attributes and their values in order to determine whether the
- // script should execute. Here, we try to minimize the impact by doing this check only for script
- // elements when a nonce is present, but we should probably consider this algorithm as "at risk"
- // until we know its impact. [Issue #w3c/webappsec-csp#98] (https://github.com/w3c/webappsec-csp/issues/98)
-
- // FIXME: See FIXME in `does_element_match_source_list_for_type_and_source`
- if (!element)
- return NonceableResult::NotNonceable;
-
- // 1. If element does not have an attribute named "nonce", return "Not Nonceable".
- if (!is<HTML::HTMLElement>(element.ptr()) && !is<SVG::SVGElement>(element.ptr()))
- return NonceableResult::NotNonceable;
-
- // INTEROP: An element whose [[CryptographicNonce]] was set through the nonce IDL attribute, which intentionally
- // does not update the content attribute, is treated as if it had a nonce attribute.
- auto const& internal_nonce = is<HTML::HTMLElement>(element.ptr()) ? as<HTML::HTMLElement>(*element).nonce() : as<SVG::SVGElement>(*element).nonce();
- if (!element->has_attribute(HTML::AttributeNames::nonce) && internal_nonce.is_empty())
- return NonceableResult::NotNonceable;
-
- // 2. If element is a script element, then for each attribute of element’s attribute list:
- // FIXME: File spec issue to ask if this should include SVGScriptElement.
- if (is<HTML::HTMLScriptElement>(element.ptr())) {
- for (size_t attribute_index = 0; attribute_index < element->attributes()->length(); ++attribute_index) {
- auto attribute = element->attributes()->item(attribute_index);
- VERIFY(attribute);
-
- auto contains_dangling_markup = [](Utf16View string) {
- return string.find_code_unit_offset_ignoring_case("<link"sv).has_value()
- || string.find_code_unit_offset_ignoring_case("<script"sv).has_value()
- || string.find_code_unit_offset_ignoring_case("<style"sv).has_value();
- };
-
- // 1. If attribute’s name contains an ASCII case-insensitive match for "<link", "<script", or "<style",
- // return "Not Nonceable".
- if (contains_dangling_markup(attribute->name().view()))
- return NonceableResult::NotNonceable;
-
- // 2. If attribute’s value contains an ASCII case-insensitive match for "<link", "<script", or "<style",
- // return "Not Nonceable".
- if (contains_dangling_markup(attribute->value()))
- return NonceableResult::NotNonceable;
- }
- }
-
- // 3. If element had a duplicate-attribute parse error during tokenization, return "Not Nonceable".
- // SPEC ISSUE 6: We need some sort of hook in HTML to record this error if we’re planning on using it here.
- // [Issue #whatwg/html#3257] (https://github.com/whatwg/html/issues/3257)
- if (element->had_duplicate_attribute_during_tokenization())
- return NonceableResult::NotNonceable;
-
- // 4. Return "Nonceable".
- return NonceableResult::Nonceable;
-}
-
-// https://w3c.github.io/webappsec-csp/#match-element-to-source-list
-MatchResult does_element_match_source_list_for_type_and_source(GC::Ptr<DOM::Element const> element, Vector<Utf16String> const& source_list, Directive::InlineType type, Utf16View source)
-{
- // Spec Note: Regardless of the encoding of the document, source will be converted to UTF-8 before applying any
- // hashing algorithms.
-
- // 1. If § 6.7.3.2 Does a source list allow all inline behavior for type? returns "Allows" given list and type,
- // return "Matches".
- if (does_a_source_list_allow_all_inline_behavior_for_type(source_list, type) == AllowsResult::Allows)
- return MatchResult::Matches;
-
- // 2. If type is "script" or "style", and § 6.7.3.1 Is element nonceable? returns "Nonceable" when executed upon
- // element:
- // Spec Note: Nonces only apply to inline script and inline style, not to attributes of either element or to
- // javascript: navigations.
- // FIXME: File spec issue that this algorithm doesn't handle `element` being null, which is it when doing a
- // javascript: URL navigation. For now, we say that the element is not nonceable if it's null, because
- // we simply can't pull a nonce attribute value from a null element.
- // AD-HOC: For interoperability, match a style element's internal nonce without requiring a nonce content
- // attribute. This allows styles whose nonce was set through the IDL attribute, which intentionally does not update
- // the content attribute. Keep applying the nonceability checks above to script elements to prevent dangling markup
- // attacks.
- auto is_nonceable = (type == Directive::InlineType::Style && element && (is<HTML::HTMLStyleElement>(element.ptr()) || is<SVG::SVGStyleElement>(element.ptr())))
- || (type == Directive::InlineType::Script && is_element_nonceable(element) == NonceableResult::Nonceable);
- if (is_nonceable) {
- // 1. For each expression of list:
- for (auto const& expression : source_list) {
- // 1. If expression matches the nonce-source grammar, and element has a nonce attribute whose value is
- // expression's base64-value part, return "Matches".
- auto nonce_source_parse_result = parse_source_expression(Production::NonceSource, expression);
- if (nonce_source_parse_result.has_value()) {
- VERIFY(element);
- VERIFY(is<HTML::HTMLElement>(element.ptr()) || is<SVG::SVGElement>(element.ptr()));
-
- Utf16String element_nonce;
- if (auto* html_element = as_if<HTML::HTMLElement>(element.ptr())) {
- element_nonce = html_element->nonce();
- } else {
- auto const& svg_element = as<SVG::SVGElement>(*element);
- element_nonce = svg_element.nonce();
- }
-
- if (element_nonce == nonce_source_parse_result->base64_value.value())
- return MatchResult::Matches;
- }
- }
- }
-
- // 3. Let unsafe-hashes flag be false.
- bool unsafe_hashes_flag = false;
-
- // 4. For each expression of list:
- for (auto const& expression : source_list) {
- // 1. If expression is an ASCII case-insensitive match for the keyword-source "'unsafe-hashes'", set
- // unsafe-hashes flag to true. Break out of the loop.
- if (expression.equals_ignoring_ascii_case(KeywordSources::UnsafeHashes.view())) {
- unsafe_hashes_flag = true;
- break;
- }
- }
-
- // 5. If type is "script" or "style", or unsafe-hashes flag is true:
- // NOTE: Hashes apply to inline script and inline style. If the "'unsafe-hashes'" source expression is present,
- // they will also apply to event handlers, style attributes and javascript: navigations.
- if (type == Directive::InlineType::Script || type == Directive::InlineType::Style || unsafe_hashes_flag) {
- // 1. Set source to the result of executing UTF-8 encode on the result of executing JavaScript string
- // converting on source.
- auto converted_source = MUST(Infra::convert_to_scalar_value_string(source));
- auto converted_source_utf8 = converted_source.to_utf8(AllowLonelySurrogates::No);
-
- // NOTE: converted_source_utf8 is already UTF-8 encoded.
- auto converted_source_bytes = converted_source_utf8.bytes();
-
- // 2. For each expression of list:
- for (auto const& expression : source_list) {
- // 1. If expression is the "'strict-dynamic'" keyword-source:
- if (expression.equals_ignoring_ascii_case(KeywordSources::StrictDynamic.view())) {
- // 1. If type is "script", and element is not parser-inserted, return "Matches".
- if (type == Directive::InlineType::Script && element) {
- if (auto const* html_script_element = as_if<HTML::HTMLScriptElement>(element.ptr())) {
- if (!html_script_element->is_parser_inserted())
- return MatchResult::Matches;
- } else if (auto const* svg_script_element = as_if<SVG::SVGScriptElement>(element.ptr())) {
- if (!svg_script_element->is_parser_inserted())
- return MatchResult::Matches;
- }
- }
- }
-
- // 2. If expression matches the hash-source grammar:
- auto hash_source_parse_result = parse_source_expression(Production::HashSource, expression);
- if (hash_source_parse_result.has_value()) {
- // 1. Let algorithm be null.
- Optional<StringView> algorithm;
-
- // 2. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha256", set
- // algorithm to SHA-256.
- VERIFY(hash_source_parse_result->hash_algorithm.has_value());
- auto hash_algorithm_from_expression = hash_source_parse_result->hash_algorithm.value();
-
- if (hash_algorithm_from_expression.equals_ignoring_ascii_case(u"sha256"sv))
- algorithm = "SHA-256"sv;
-
- // 3. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha384", set
- // algorithm to SHA-384.
- if (hash_algorithm_from_expression.equals_ignoring_ascii_case(u"sha384"sv))
- algorithm = "SHA-384"sv;
-
- // 4. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha512", set
- // algorithm to SHA-512.
- if (hash_algorithm_from_expression.equals_ignoring_ascii_case(u"sha512"sv))
- algorithm = "SHA-512"sv;
-
- // 5. If algorithm is not null:
- if (algorithm.has_value()) {
- // 1. Let actual be the result of base64 encoding the result of applying algorithm to source.
- auto apply_algorithm_to_source = [&] {
- if (*algorithm == "SHA-256"sv) {
- auto result = ::Crypto::Hash::SHA256::hash(converted_source_bytes);
- return MUST(encode_base64(result.bytes()));
- }
-
- if (*algorithm == "SHA-384"sv) {
- auto result = ::Crypto::Hash::SHA384::hash(converted_source_bytes);
- return MUST(encode_base64(result.bytes()));
- }
-
- if (*algorithm == "SHA-512"sv) {
- auto result = ::Crypto::Hash::SHA512::hash(converted_source_bytes);
- return MUST(encode_base64(result.bytes()));
- }
-
- VERIFY_NOT_REACHED();
- };
-
- auto actual = apply_algorithm_to_source();
-
- // 2. Let expected be expression’s base64-value part, with all '-' characters replaced with '+',
- // and all '_' characters replaced with '/'.
- // Spec Note: This replacement normalizes hashes expressed in base64url encoding into base64
- // encoding for matching.
- VERIFY(hash_source_parse_result->base64_value.has_value());
- auto base64_value_string = MUST(hash_source_parse_result->base64_value->to_utf8());
-
- auto expected = MUST(base64_value_string.replace("-"sv, "+"sv, ReplaceMode::All));
- expected = MUST(expected.replace("_"sv, "/"sv, ReplaceMode::All));
-
- // 3. If actual is identical to expected, return "Matches".
- if (actual == expected)
- return MatchResult::Matches;
- }
- }
- }
- }
-
- // 6. Return "Does Not Match".
- return MatchResult::DoesNotMatch;
-}
-
}
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h b/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h
index be6c9ef1ca0..64b6fbeb857 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h
+++ b/Libraries/LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h
@@ -30,8 +30,6 @@ enum class [[nodiscard]] MatchResult {
[[nodiscard]] Vector<Utf16FlyString> get_fetch_directive_fallback_list(Optional<Utf16FlyString> directive_name);
ShouldExecute should_fetch_directive_execute(Optional<Utf16FlyString> effective_directive_name, Utf16FlyString const& directive_name, Policy const& policy);
-[[nodiscard]] Utf16FlyString get_the_effective_directive_for_inline_checks(Directive::InlineType type);
-
MatchResult does_url_match_expression_in_origin_with_redirect_count(URL::URL const& url, Utf16View expression, URL::Origin const& origin, u8 redirect_count);
MatchResult does_url_match_source_list_in_origin_with_redirect_count(URL::URL const& url, Vector<Utf16String> const& source_list, URL::Origin const& origin, u8 redirect_count);
@@ -42,6 +40,4 @@ MatchResult does_nonce_match_source_list(Utf16View nonce, Vector<Utf16String> co
Directive::Result script_directives_pre_request_check(GC::Ref<Fetch::Infrastructure::Request const> request, Directive const& directive, Policy const& policy);
Directive::Result script_directives_post_request_check(GC::Ref<Fetch::Infrastructure::Request const> request, GC::Ref<Fetch::Infrastructure::Response const> response, Directive const& directive, Policy const& policy);
-MatchResult does_element_match_source_list_for_type_and_source(GC::Ptr<DOM::Element const> element, Vector<Utf16String> const& source_list, Directive::InlineType type, Utf16View source);
-
}
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.cpp b/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.cpp
index 0fa9e570ed8..2f955d4c1b5 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.cpp
+++ b/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.cpp
@@ -5,22 +5,330 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Base64.h>
+#include <LibCrypto/Hash/SHA2.h>
#include <LibURL/Origin.h>
#include <LibWeb/ContentSecurityPolicy/Directives/DirectiveOperations.h>
#include <LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h>
+#include <LibWeb/ContentSecurityPolicy/Directives/KeywordSources.h>
#include <LibWeb/ContentSecurityPolicy/Directives/Names.h>
+#include <LibWeb/ContentSecurityPolicy/Directives/SourceExpression.h>
#include <LibWeb/ContentSecurityPolicy/Policy.h>
+#include <LibWeb/DOM/Attr.h>
#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/NamedNodeMap.h>
#include <LibWeb/DOMURL/DOMURL.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
+#include <LibWeb/HTML/HTMLScriptElement.h>
+#include <LibWeb/HTML/HTMLStyleElement.h>
#include <LibWeb/HTML/WorkerGlobalScope.h>
+#include <LibWeb/SVG/SVGElement.h>
+#include <LibWeb/SVG/SVGScriptElement.h>
+#include <LibWeb/SVG/SVGStyleElement.h>
#include <LibWeb/TrustedTypes/RequireTrustedTypesForDirective.h>
#include <LibWebCommon/Fetch/Infrastructure/URL.h>
#include <LibWebCommon/HTML/SandboxingFlagSet.h>
+#include <LibWebCommon/Infra/Strings.h>
namespace Web::ContentSecurityPolicy::Directives {
+// https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check
+Utf16FlyString get_the_effective_directive_for_inline_checks(Directive::InlineType type)
+{
+ // Spec Note: While the effective directive is only defined for requests, in this algorithm it is used similarly to
+ // mean the directive that is most relevant to a particular type of inline check.
+
+ // Switch on type:
+ switch (type) {
+ // "script"
+ // "navigation"
+ // Return script-src-elem.
+ case Directive::InlineType::Script:
+ case Directive::InlineType::Navigation:
+ return Names::ScriptSrcElem;
+ // "script attribute"
+ // Return script-src-attr.
+ case Directive::InlineType::ScriptAttribute:
+ return Names::ScriptSrcAttr;
+ // "style"
+ // Return style-src-elem.
+ case Directive::InlineType::Style:
+ return Names::StyleSrcElem;
+ // "style attribute"
+ // Return style-src-attr.
+ case Directive::InlineType::StyleAttribute:
+ return Names::StyleSrcAttr;
+ }
+
+ // 2. Return null.
+ // FIXME: File spec issue that this should be invalid, as the result of this algorithm ends up being piped into
+ // Violation's effective directive, which is defined to be a non-empty string.
+ VERIFY_NOT_REACHED();
+}
+
+enum class [[nodiscard]] AllowsResult {
+ DoesNotAllow,
+ Allows,
+};
+
+static AllowsResult does_a_source_list_allow_all_inline_behavior_for_type(Vector<Utf16String> const& source_list, Directive::InlineType type)
+{
+ // 1. Let allow all inline be false.
+ bool allow_all_inline = false;
+
+ // 2. For each expression of list:
+ for (auto const& expression : source_list) {
+ // 1. If expression matches the nonce-source or hash-source grammar, return "Does Not Allow".
+ auto nonce_source_parse_result = parse_source_expression(Production::NonceSource, expression);
+ if (nonce_source_parse_result.has_value())
+ return AllowsResult::DoesNotAllow;
+
+ auto hash_source_parse_result = parse_source_expression(Production::HashSource, expression);
+ if (hash_source_parse_result.has_value())
+ return AllowsResult::DoesNotAllow;
+
+ // 2. If type is "script", "script attribute" or "navigation" and expression matches the keyword-source
+ // "'strict-dynamic'", return "Does Not Allow".
+ if (type == Directive::InlineType::Script || type == Directive::InlineType::ScriptAttribute || type == Directive::InlineType::Navigation) {
+ if (expression.equals_ignoring_ascii_case(KeywordSources::StrictDynamic.view()))
+ return AllowsResult::DoesNotAllow;
+ }
+
+ // 3. If expression is an ASCII case-insensitive match for the keyword-source "'unsafe-inline'", set allow all
+ // inline to true.
+ if (expression.equals_ignoring_ascii_case(KeywordSources::UnsafeInline.view()))
+ allow_all_inline = true;
+ }
+
+ // 3. If allow all inline is true, return "Allows". Otherwise, return "Does Not Allow".
+ return allow_all_inline ? AllowsResult::Allows : AllowsResult::DoesNotAllow;
+}
+
+enum class NonceableResult {
+ NotNonceable,
+ Nonceable,
+};
+
+// https://w3c.github.io/webappsec-csp/#is-element-nonceable
+[[nodiscard]] static NonceableResult is_element_nonceable(GC::Ptr<DOM::Element const> element)
+{
+ // SPEC ISSUE 7: This processing is meant to mitigate the risk of dangling markup attacks that steal the nonce from
+ // an existing element in order to load injected script. It is fairly expensive, however, as it
+ // requires that we walk through all attributes and their values in order to determine whether the
+ // script should execute. Here, we try to minimize the impact by doing this check only for script
+ // elements when a nonce is present, but we should probably consider this algorithm as "at risk"
+ // until we know its impact. [Issue #w3c/webappsec-csp#98] (https://github.com/w3c/webappsec-csp/issues/98)
+
+ // FIXME: See FIXME in `does_element_match_source_list_for_type_and_source`
+ if (!element)
+ return NonceableResult::NotNonceable;
+
+ // 1. If element does not have an attribute named "nonce", return "Not Nonceable".
+ if (!is<HTML::HTMLElement>(element.ptr()) && !is<SVG::SVGElement>(element.ptr()))
+ return NonceableResult::NotNonceable;
+
+ // INTEROP: An element whose [[CryptographicNonce]] was set through the nonce IDL attribute, which intentionally
+ // does not update the content attribute, is treated as if it had a nonce attribute.
+ auto const& internal_nonce = is<HTML::HTMLElement>(element.ptr()) ? as<HTML::HTMLElement>(*element).nonce() : as<SVG::SVGElement>(*element).nonce();
+ if (!element->has_attribute(HTML::AttributeNames::nonce) && internal_nonce.is_empty())
+ return NonceableResult::NotNonceable;
+
+ // 2. If element is a script element, then for each attribute of element’s attribute list:
+ // FIXME: File spec issue to ask if this should include SVGScriptElement.
+ if (is<HTML::HTMLScriptElement>(element.ptr())) {
+ for (size_t attribute_index = 0; attribute_index < element->attributes()->length(); ++attribute_index) {
+ auto attribute = element->attributes()->item(attribute_index);
+ VERIFY(attribute);
+
+ auto contains_dangling_markup = [](Utf16View string) {
+ return string.find_code_unit_offset_ignoring_case("<link"sv).has_value()
+ || string.find_code_unit_offset_ignoring_case("<script"sv).has_value()
+ || string.find_code_unit_offset_ignoring_case("<style"sv).has_value();
+ };
+
+ // 1. If attribute’s name contains an ASCII case-insensitive match for "<link", "<script", or "<style",
+ // return "Not Nonceable".
+ if (contains_dangling_markup(attribute->name().view()))
+ return NonceableResult::NotNonceable;
+
+ // 2. If attribute’s value contains an ASCII case-insensitive match for "<link", "<script", or "<style",
+ // return "Not Nonceable".
+ if (contains_dangling_markup(attribute->value()))
+ return NonceableResult::NotNonceable;
+ }
+ }
+
+ // 3. If element had a duplicate-attribute parse error during tokenization, return "Not Nonceable".
+ // SPEC ISSUE 6: We need some sort of hook in HTML to record this error if we’re planning on using it here.
+ // [Issue #whatwg/html#3257] (https://github.com/whatwg/html/issues/3257)
+ if (element->had_duplicate_attribute_during_tokenization())
+ return NonceableResult::NotNonceable;
+
+ // 4. Return "Nonceable".
+ return NonceableResult::Nonceable;
+}
+
+// https://w3c.github.io/webappsec-csp/#match-element-to-source-list
+static MatchResult does_element_match_source_list_for_type_and_source(GC::Ptr<DOM::Element const> element, Vector<Utf16String> const& source_list, Directive::InlineType type, Utf16View source)
+{
+ // Spec Note: Regardless of the encoding of the document, source will be converted to UTF-8 before applying any
+ // hashing algorithms.
+
+ // 1. If § 6.7.3.2 Does a source list allow all inline behavior for type? returns "Allows" given list and type,
+ // return "Matches".
+ if (does_a_source_list_allow_all_inline_behavior_for_type(source_list, type) == AllowsResult::Allows)
+ return MatchResult::Matches;
+
+ // 2. If type is "script" or "style", and § 6.7.3.1 Is element nonceable? returns "Nonceable" when executed upon
+ // element:
+ // Spec Note: Nonces only apply to inline script and inline style, not to attributes of either element or to
+ // javascript: navigations.
+ // FIXME: File spec issue that this algorithm doesn't handle `element` being null, which is it when doing a
+ // javascript: URL navigation. For now, we say that the element is not nonceable if it's null, because
+ // we simply can't pull a nonce attribute value from a null element.
+ // AD-HOC: For interoperability, match a style element's internal nonce without requiring a nonce content
+ // attribute. This allows styles whose nonce was set through the IDL attribute, which intentionally does not update
+ // the content attribute. Keep applying the nonceability checks above to script elements to prevent dangling markup
+ // attacks.
+ auto is_nonceable = (type == Directive::InlineType::Style && element && (is<HTML::HTMLStyleElement>(element.ptr()) || is<SVG::SVGStyleElement>(element.ptr())))
+ || (type == Directive::InlineType::Script && is_element_nonceable(element) == NonceableResult::Nonceable);
+ if (is_nonceable) {
+ // 1. For each expression of list:
+ for (auto const& expression : source_list) {
+ // 1. If expression matches the nonce-source grammar, and element has a nonce attribute whose value is
+ // expression's base64-value part, return "Matches".
+ auto nonce_source_parse_result = parse_source_expression(Production::NonceSource, expression);
+ if (nonce_source_parse_result.has_value()) {
+ VERIFY(element);
+ VERIFY(is<HTML::HTMLElement>(element.ptr()) || is<SVG::SVGElement>(element.ptr()));
+
+ Utf16String element_nonce;
+ if (auto* html_element = as_if<HTML::HTMLElement>(element.ptr())) {
+ element_nonce = html_element->nonce();
+ } else {
+ auto const& svg_element = as<SVG::SVGElement>(*element);
+ element_nonce = svg_element.nonce();
+ }
+
+ if (element_nonce == nonce_source_parse_result->base64_value.value())
+ return MatchResult::Matches;
+ }
+ }
+ }
+
+ // 3. Let unsafe-hashes flag be false.
+ bool unsafe_hashes_flag = false;
+
+ // 4. For each expression of list:
+ for (auto const& expression : source_list) {
+ // 1. If expression is an ASCII case-insensitive match for the keyword-source "'unsafe-hashes'", set
+ // unsafe-hashes flag to true. Break out of the loop.
+ if (expression.equals_ignoring_ascii_case(KeywordSources::UnsafeHashes.view())) {
+ unsafe_hashes_flag = true;
+ break;
+ }
+ }
+
+ // 5. If type is "script" or "style", or unsafe-hashes flag is true:
+ // NOTE: Hashes apply to inline script and inline style. If the "'unsafe-hashes'" source expression is present,
+ // they will also apply to event handlers, style attributes and javascript: navigations.
+ if (type == Directive::InlineType::Script || type == Directive::InlineType::Style || unsafe_hashes_flag) {
+ // 1. Set source to the result of executing UTF-8 encode on the result of executing JavaScript string
+ // converting on source.
+ auto converted_source = MUST(Infra::convert_to_scalar_value_string(source));
+ auto converted_source_utf8 = converted_source.to_utf8(AllowLonelySurrogates::No);
+
+ // NOTE: converted_source_utf8 is already UTF-8 encoded.
+ auto converted_source_bytes = converted_source_utf8.bytes();
+
+ // 2. For each expression of list:
+ for (auto const& expression : source_list) {
+ // 1. If expression is the "'strict-dynamic'" keyword-source:
+ if (expression.equals_ignoring_ascii_case(KeywordSources::StrictDynamic.view())) {
+ // 1. If type is "script", and element is not parser-inserted, return "Matches".
+ if (type == Directive::InlineType::Script && element) {
+ if (auto const* html_script_element = as_if<HTML::HTMLScriptElement>(element.ptr())) {
+ if (!html_script_element->is_parser_inserted())
+ return MatchResult::Matches;
+ } else if (auto const* svg_script_element = as_if<SVG::SVGScriptElement>(element.ptr())) {
+ if (!svg_script_element->is_parser_inserted())
+ return MatchResult::Matches;
+ }
+ }
+ }
+
+ // 2. If expression matches the hash-source grammar:
+ auto hash_source_parse_result = parse_source_expression(Production::HashSource, expression);
+ if (hash_source_parse_result.has_value()) {
+ // 1. Let algorithm be null.
+ Optional<StringView> algorithm;
+
+ // 2. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha256", set
+ // algorithm to SHA-256.
+ VERIFY(hash_source_parse_result->hash_algorithm.has_value());
+ auto hash_algorithm_from_expression = hash_source_parse_result->hash_algorithm.value();
+
+ if (hash_algorithm_from_expression.equals_ignoring_ascii_case(u"sha256"sv))
+ algorithm = "SHA-256"sv;
+
+ // 3. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha384", set
+ // algorithm to SHA-384.
+ if (hash_algorithm_from_expression.equals_ignoring_ascii_case(u"sha384"sv))
+ algorithm = "SHA-384"sv;
+
+ // 4. If expression’s hash-algorithm part is an ASCII case-insensitive match for "sha512", set
+ // algorithm to SHA-512.
+ if (hash_algorithm_from_expression.equals_ignoring_ascii_case(u"sha512"sv))
+ algorithm = "SHA-512"sv;
+
+ // 5. If algorithm is not null:
+ if (algorithm.has_value()) {
+ // 1. Let actual be the result of base64 encoding the result of applying algorithm to source.
+ auto apply_algorithm_to_source = [&] {
+ if (*algorithm == "SHA-256"sv) {
+ auto result = ::Crypto::Hash::SHA256::hash(converted_source_bytes);
+ return MUST(encode_base64(result.bytes()));
+ }
+
+ if (*algorithm == "SHA-384"sv) {
+ auto result = ::Crypto::Hash::SHA384::hash(converted_source_bytes);
+ return MUST(encode_base64(result.bytes()));
+ }
+
+ if (*algorithm == "SHA-512"sv) {
+ auto result = ::Crypto::Hash::SHA512::hash(converted_source_bytes);
+ return MUST(encode_base64(result.bytes()));
+ }
+
+ VERIFY_NOT_REACHED();
+ };
+
+ auto actual = apply_algorithm_to_source();
+
+ // 2. Let expected be expression’s base64-value part, with all '-' characters replaced with '+',
+ // and all '_' characters replaced with '/'.
+ // Spec Note: This replacement normalizes hashes expressed in base64url encoding into base64
+ // encoding for matching.
+ VERIFY(hash_source_parse_result->base64_value.has_value());
+ auto base64_value_string = MUST(hash_source_parse_result->base64_value->to_utf8());
+
+ auto expected = MUST(base64_value_string.replace("-"sv, "+"sv, ReplaceMode::All));
+ expected = MUST(expected.replace("_"sv, "/"sv, ReplaceMode::All));
+
+ // 3. If actual is identical to expected, return "Matches".
+ if (actual == expected)
+ return MatchResult::Matches;
+ }
+ }
+ }
+ }
+
+ // 6. Return "Does Not Match".
+ return MatchResult::DoesNotMatch;
+}
+
// https://w3c.github.io/webappsec-csp/#default-src-inline
static Directive::Result default_src_inline_check(Directive const& directive, GC::Ptr<DOM::Element const> element, Directive::InlineType type, Policy const& policy, Utf16View source)
{
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h b/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h
index ccc4c085964..26153218fa5 100644
--- a/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h
+++ b/Libraries/LibWeb/ContentSecurityPolicy/Directives/HTMLIntegration.h
@@ -16,6 +16,9 @@
namespace Web::ContentSecurityPolicy::Directives {
+// https://w3c.github.io/webappsec-csp/#effective-directive-for-inline-check
+[[nodiscard]] Utf16FlyString get_the_effective_directive_for_inline_checks(Directive::InlineType);
+
// https://w3c.github.io/webappsec-csp/#directive-inline-check
// An inline check, which takes an Element, a type string, a policy, and a source string as arguments, and is executed
// during § 4.2.3 Should element’s inline type behavior be blocked by Content Security Policy? and during § 4.2.4 Should
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/FetchIntegration.cpp b/Libraries/LibWeb/ContentSecurityPolicy/FetchIntegration.cpp
new file mode 100644
index 00000000000..f3efd21e81f
--- /dev/null
+++ b/Libraries/LibWeb/ContentSecurityPolicy/FetchIntegration.cpp
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2025, Luke Wilde <[email protected]>
+ * Copyright (c) 2025, Kenneth Myhra <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/ContentSecurityPolicy/Directives/FetchIntegration.h>
+#include <LibWeb/ContentSecurityPolicy/FetchIntegration.h>
+#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
+#include <LibWeb/HTML/PolicyContainers.h>
+
+namespace Web::ContentSecurityPolicy {
+
+// https://w3c.github.io/webappsec-csp/#does-resource-hint-violate-policy
+[[nodiscard]] static Directives::Directive const* does_resource_hint_request_violate_policy(Fetch::Infrastructure::Request const& request, Policy const& policy)
+{
+ // 1. Let defaultDirective be policy’s first directive whose name is "default-src".
+ auto default_directive_iterator = policy.directives().find_if([](auto const& directive) {
+ return directive.kind() == Directives::Directive::Kind::DefaultSrc;
+ });
+
+ // 2. If defaultDirective does not exist, return "Does Not Violate".
+ if (default_directive_iterator.is_end())
+ return nullptr;
+
+ // 3. For each directive of policy:
+ for (auto const& directive : policy.directives()) {
+ // 1. Let result be the result of executing directive’s pre-request check on request and policy.
+ auto result = Directives::pre_request_check(directive, request, policy);
+
+ // 2. If result is "Allowed", then return "Does Not Violate".
+ if (result == Directives::Directive::Result::Allowed) {
+ return nullptr;
+ }
+ }
+
+ // 4. Return defaultDirective.
+ return &*default_directive_iterator;
+}
+
+// https://w3c.github.io/webappsec-csp/#does-request-violate-policy
+[[nodiscard]] static Directives::Directive const* does_request_violate_policy(Fetch::Infrastructure::Request const& request, Policy const& policy)
+{
+ // 1. If request’s initiator is "prefetch", then return the result of executing § 6.7.2.2 Does resource hint
+ // request violate policy? on request and policy.
+ if (request.initiator() == Fetch::Infrastructure::Request::Initiator::Prefetch)
+ return does_resource_hint_request_violate_policy(request, policy);
+
+ // 2. Let violates be "Does Not Violate".
+ Directives::Directive const* violates = nullptr;
+
+ // 3. For each directive of policy:
+ for (auto const& directive : policy.directives()) {
+ // 1. Let result be the result of executing directive’s pre-request check on request and policy.
+ auto result = Directives::pre_request_check(directive, request, policy);
+
+ // 2. If result is "Blocked", then let violates be directive.
+ if (result == Directives::Directive::Result::Blocked) {
+ violates = &directive;
+ }
+ }
+
+ // 4. Return violates.
+ return violates;
+}
+
+// https://w3c.github.io/webappsec-csp/#report-for-request
+void report_content_security_policy_violations_for_request(Fetch::Infrastructure::Request const& request, ViolationReporter const& report_violation)
+{
+ // 1. Let CSP list be request’s policy container's CSP list.
+ auto const& csp_list = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list;
+
+ // 2. For each policy of CSP list:
+ for (auto const& policy : csp_list.policies()) {
+ // 1. If policy’s disposition is "enforce", then skip to the next policy.
+ if (policy->disposition() == Policy::Disposition::Enforce)
+ continue;
+
+ // 2. Let violates be the result of executing § 6.7.2.1 Does request violate policy? on request and policy.
+ auto violates = does_request_violate_policy(request, policy);
+
+ // 3. If violates is not "Does Not Violate", then execute § 5.5 Report a violation on the result of executing
+ // § 2.4.2 Create a violation object for request, and policy. on request, and policy.
+ if (violates)
+ report_violation(policy);
+ }
+}
+
+// https://w3c.github.io/webappsec-csp/#should-block-request
+Directives::Directive::Result should_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Request const& request, ViolationReporter const& report_violation)
+{
+ // 1. Let CSP list be request’s policy container's CSP list.
+ auto const& csp_list = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list;
+
+ // 2. Let result be "Allowed".
+ auto result = Directives::Directive::Result::Allowed;
+
+ // 3. For each policy of CSP list:
+ for (auto const& policy : csp_list.policies()) {
+ // 1. If policy’s disposition is "report", then skip to the next policy.
+ if (policy->disposition() == Policy::Disposition::Report)
+ continue;
+
+ // 2. Let violates be the result of executing § 6.7.2.1 Does request violate policy? on request and policy.
+ auto violates = does_request_violate_policy(request, policy);
+
+ // 3. If violates is not "Does Not Violate", then:
+ if (violates) {
+ // 1. Execute § 5.5 Report a violation on the result of executing § 2.4.2 Create a violation object for
+ // request, and policy. on request, and policy.
+ report_violation(policy);
+
+ // 2. Set result to "Blocked".
+ result = Directives::Directive::Result::Blocked;
+ }
+ }
+
+ // 4. Return result.
+ return result;
+}
+
+// https://w3c.github.io/webappsec-csp/#should-block-response
+Directives::Directive::Result should_response_to_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Response const& response, Fetch::Infrastructure::Request const& request, ViolationReporter const& report_violation)
+{
+ // 1. Let CSP list be request’s policy container's CSP list.
+ auto const& csp_list = request.policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>()->csp_list;
+
+ // 2. Let result be "Allowed".
+ auto result = Directives::Directive::Result::Allowed;
+
+ // 3. For each policy of CSP list:
+ // Spec Note: This portion of the check verifies that the page can load the response. That is, that a Service
+ // Worker hasn't substituted a file which would violate the page’s CSP.
+ for (auto const& policy : csp_list.policies()) {
+ // 1. For each directive of policy:
+ for (auto const& directive : policy->directives()) {
+ // 1. If the result of executing directive’s post-request check is "Blocked", then:
+ if (Directives::post_request_check(directive, request, response, policy) == Directives::Directive::Result::Blocked) {
+ // 1. Execute § 5.5 Report a violation on the result of executing § 2.4.2 Create a violation object for
+ // request, and policy. on request, and policy.
+ report_violation(policy);
+
+ // 2. If policy’s disposition is "enforce", then set result to "Blocked".
+ if (policy->disposition() == Policy::Disposition::Enforce) {
+ result = Directives::Directive::Result::Blocked;
+ }
+ }
+ }
+ }
+
+ // 4. Return result.
+ return result;
+}
+
+}
diff --git a/Libraries/LibWeb/ContentSecurityPolicy/FetchIntegration.h b/Libraries/LibWeb/ContentSecurityPolicy/FetchIntegration.h
new file mode 100644
index 00000000000..61422222d0a
--- /dev/null
+++ b/Libraries/LibWeb/ContentSecurityPolicy/FetchIntegration.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2025, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Function.h>
+#include <AK/NonnullRefPtr.h>
+#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>
+#include <LibWeb/Forward.h>
+
+namespace Web::ContentSecurityPolicy {
+
+// Reports the violation for the request being checked and the given policy.
+using ViolationReporter = Function<void(NonnullRefPtr<Policy const>)>;
+
+// https://w3c.github.io/webappsec-csp/#report-for-request
+void report_content_security_policy_violations_for_request(Fetch::Infrastructure::Request const&, ViolationReporter const&);
+
+// https://w3c.github.io/webappsec-csp/#should-block-request
+Directives::Directive::Result should_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Request const&, ViolationReporter const&);
+
+// https://w3c.github.io/webappsec-csp/#should-block-response
+Directives::Directive::Result should_response_to_request_be_blocked_by_content_security_policy(Fetch::Infrastructure::Response const&, Fetch::Infrastructure::Request const&, ViolationReporter const&);
+
+}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 517d742c74e..c581458faee 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -69,6 +69,7 @@
#include <LibWeb/Platform/EventLoopPlugin.h>
#include <LibWeb/ReferrerPolicy/AbstractOperations.h>
#include <LibWeb/ResourceTiming/PerformanceResourceTiming.h>
+#include <LibWeb/SRI/IntegrityPolicy.h>
#include <LibWeb/SRI/SRI.h>
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
@@ -468,7 +469,7 @@ GC::Ptr<PendingResponse> main_fetch(JS::Realm& realm, Infrastructure::FetchParam
if (Infrastructure::block_bad_port(request) == Infrastructure::RequestOrResponseBlocking::Blocked
|| MixedContent::should_fetching_request_be_blocked_as_mixed_content(request) == Infrastructure::RequestOrResponseBlocking::Blocked
|| ContentSecurityPolicy::should_request_be_blocked_by_content_security_policy(request, report_violation) == ContentSecurityPolicy::Directives::Directive::Result::Blocked
- || ContentSecurityPolicy::should_request_be_blocked_by_integrity_policy(request) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {
+ || SRI::should_request_be_blocked_by_integrity_policy(request) == ContentSecurityPolicy::Directives::Directive::Result::Blocked) {
response = Infrastructure::Response::network_error("Request was blocked"_string);
}
diff --git a/Libraries/LibWeb/HTML/PolicyContainers.h b/Libraries/LibWeb/HTML/PolicyContainers.h
index 58aeec77bf3..0de66b11c52 100644
--- a/Libraries/LibWeb/HTML/PolicyContainers.h
+++ b/Libraries/LibWeb/HTML/PolicyContainers.h
@@ -15,20 +15,12 @@
#include <LibWeb/ContentSecurityPolicy/PolicyList.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Forward.h>
+#include <LibWeb/SRI/IntegrityPolicy.h>
#include <LibWebCommon/HTML/EmbedderPolicy.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
namespace Web::HTML {
-// https://w3c.github.io/webappsec-subresource-integrity/#integrity-policy
-struct IntegrityPolicy {
- Vector<Utf16String> sources;
- Vector<Fetch::Infrastructure::Request::Destination> blocked_destinations;
- Vector<Utf16String> endpoints;
-
- bool is_empty() const { return sources.is_empty() && blocked_destinations.is_empty() && endpoints.is_empty(); }
-};
-
// https://html.spec.whatwg.org/multipage/origin.html#policy-container
// A policy container is a struct containing policies that apply to a Document, a WorkerGlobalScope, or a WorkletGlobalScope. It has the following items:
struct PolicyContainer final : public AtomicRefCounted<PolicyContainer> {
@@ -48,11 +40,11 @@ struct PolicyContainer final : public AtomicRefCounted<PolicyContainer> {
// https://html.spec.whatwg.org/multipage/browsers.html#policy-container-integrity-policy
// An integrity policy, which is an integrity policy, initially a new integrity policy.
- IntegrityPolicy integrity_policy {};
+ SRI::IntegrityPolicy integrity_policy {};
// https://html.spec.whatwg.org/multipage/browsers.html#policy-container-report-only-integrity-policy
// A report only integrity policy, which is an integrity policy, initially a new integrity policy.
- IntegrityPolicy report_only_integrity_policy {};
+ SRI::IntegrityPolicy report_only_integrity_policy {};
// https://wicg.github.io/scroll-to-text-fragment/#document-policy-integration
// This specification defines a configuration point in Document Policy with name
diff --git a/Libraries/LibWeb/SRI/IntegrityPolicy.cpp b/Libraries/LibWeb/SRI/IntegrityPolicy.cpp
new file mode 100644
index 00000000000..fbc4a1d1a7c
--- /dev/null
+++ b/Libraries/LibWeb/SRI/IntegrityPolicy.cpp
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2025, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/HTML/PolicyContainers.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/SRI/IntegrityPolicy.h>
+#include <LibWeb/SRI/SRI.h>
+#include <LibWebCommon/Fetch/Infrastructure/URL.h>
+
+namespace Web::SRI {
+
+// https://w3c.github.io/webappsec-subresource-integrity/#should-request-be-blocked-by-integrity-policy
+ContentSecurityPolicy::Directives::Directive::Result should_request_be_blocked_by_integrity_policy(GC::Ref<Fetch::Infrastructure::Request> request)
+{
+ VERIFY(request->policy_container().has<NonnullRefPtr<HTML::PolicyContainer const>>());
+
+ // 1. Let policyContainer be request’s policy container.
+ auto const& policy_container = request->policy_container().get<NonnullRefPtr<HTML::PolicyContainer const>>();
+
+ // 2. Let parsedMetadata be the result of calling parse metadata with request’s integrity metadata.
+ auto parsed_metadata = MUST(parse_metadata(request->integrity_metadata().utf16_view()));
+
+ // 3. If parsedMetadata is not the empty set and request’s mode is either "cors" or "same-origin", return "Allowed".
+ if (!parsed_metadata.is_empty() && (request->mode() == Fetch::Infrastructure::Request::Mode::CORS || request->mode() == Fetch::Infrastructure::Request::Mode::SameOrigin))
+ return ContentSecurityPolicy::Directives::Directive::Result::Allowed;
+
+ // 4. If request’s url is local, return "Allowed".
+ if (Fetch::Infrastructure::is_local_url(request->url()))
+ return ContentSecurityPolicy::Directives::Directive::Result::Allowed;
+
+ // 5. Let policy be policyContainer’s integrity policy.
+ auto const& policy = policy_container->integrity_policy;
+
+ // 6. Let reportPolicy be policyContainer’s report only integrity policy.
+ auto const& report_policy = policy_container->report_only_integrity_policy;
+
+ // 7. If both policy and reportPolicy are empty integrity policys, return "Allowed".
+ if (policy.is_empty() && report_policy.is_empty())
+ return ContentSecurityPolicy::Directives::Directive::Result::Allowed;
+
+ // 8. Let global be request’s client’s global object.
+ auto& global = request->client()->global_object();
+
+ // 9. If global is not a Window nor a WorkerGlobalScope, return "Allowed".
+ if (!HTML::window_or_worker_global_scope_from_global_object(global))
+ return ContentSecurityPolicy::Directives::Directive::Result::Allowed;
+
+ // 10. Let block be a boolean, initially false.
+ bool block = false;
+
+ // FIXME: 11. Let reportBlock be a boolean, initially false.
+ [[maybe_unused]] auto report_block = false;
+
+ // 12. If policy’s sources contains "inline" and policy’s blocked destinations contains request’s destination, set block to true.
+ if (policy.sources.contains_slow(u"inline"sv)
+ && request->destination().has_value()
+ && policy.blocked_destinations.contains_slow(request->destination().value()))
+ block = true;
+
+ // 13. If reportPolicy’s sources contains "inline" and reportPolicy’s blocked destinations contains request’s destination, set reportBlock to true.
+ if (report_policy.sources.contains_slow(u"inline"sv)
+ && request->destination().has_value()
+ && report_policy.blocked_destinations.contains_slow(request->destination().value()))
+ report_block = true;
+
+ // FIXME: 14. If block is true or reportBlock is true, then report violation with request, block, reportBlock, policy and reportPolicy.
+
+ // 15. If block is true, then return "Blocked"; otherwise "Allowed".
+ return block ? ContentSecurityPolicy::Directives::Directive::Result::Blocked : ContentSecurityPolicy::Directives::Directive::Result::Allowed;
+}
+
+}
diff --git a/Libraries/LibWeb/SRI/IntegrityPolicy.h b/Libraries/LibWeb/SRI/IntegrityPolicy.h
new file mode 100644
index 00000000000..a1716de9e73
--- /dev/null
+++ b/Libraries/LibWeb/SRI/IntegrityPolicy.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2025, Luke Wilde <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/ContentSecurityPolicy/Directives/Directive.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
+
+namespace Web::SRI {
+
+// https://w3c.github.io/webappsec-subresource-integrity/#integrity-policy
+struct IntegrityPolicy {
+ Vector<Utf16String> sources;
+ Vector<Fetch::Infrastructure::Request::Destination> blocked_destinations;
+ Vector<Utf16String> endpoints;
+
+ bool is_empty() const { return sources.is_empty() && blocked_destinations.is_empty() && endpoints.is_empty(); }
+};
+
+// https://w3c.github.io/webappsec-subresource-integrity/#should-request-be-blocked-by-integrity-policy
+ContentSecurityPolicy::Directives::Directive::Result should_request_be_blocked_by_integrity_policy(GC::Ref<Fetch::Infrastructure::Request>);
+
+}
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cpp
index 63c6f67d717..fde3e2bc7f3 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp
+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp
@@ -16,6 +16,7 @@
#include <LibWeb/Bindings/Wrappable.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/ContentSecurityPolicy/BlockingAlgorithms.h>
+#include <LibWeb/ContentSecurityPolicy/FetchIntegration.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Event.h>
#include <LibWeb/DOM/EventDispatcher.h>