Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / sri / sri.lucb

#==============================================================================================
#
#   sri - SRI: Subresource Integrity's hash functions, parsing integrity metadata, getting
#   the strongest metadata and matching bytes against a metadata list
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/SRI/SRI.cpp (lines 1-191). The SHA-2 hashes are luce-crypto's
#       (LibCrypto's in C++). Ported by region p2e: the CSP checks parse integrity metadata,
#       and Fetch (region p2c) matches response bytes with it.
#
#       Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

## Ported from Libraries/LibWeb/SRI/SRI.cpp:15 Web::SRI::supported_hash_functions.
# These are sorted by strength, low to high.
# NOTE: We are specifically told to refuse MD5 and SHA1.
#       https://w3c.github.io/webappsec-subresource-integrity/#hash-functions
let sri_supported_hash_functions: str[3] = ["sha256", "sha384", "sha512"]

## `supported_hash_functions.first_index_of(name)`.
func sri_supported_hash_function_index(name: ak.StringView) -> usize?:
    for index in 0..<sri_supported_hash_functions.length:
        if ak.string_view_eq_string_view(&name, ak.sv(sri_supported_hash_functions[index])):
            return index
    return none

## Ported from Libraries/LibWeb/SRI/SRI.cpp:25 Web::SRI::get_prioritized_hash_function.
# https://w3c.github.io/webappsec-subresource-integrity/#getprioritizedhashfunction
func sri_get_prioritized_hash_function(a: ak.StringView, b: ak.StringView) -> ak.StringView:
    if ak.string_view_eq_string_view(&a, b):
        return ak.sv("")

    let a_priority = sri_supported_hash_function_index(a) else trap("VERIFY: Optional::value")
    let b_priority = sri_supported_hash_function_index(b) else trap("VERIFY: Optional::value")
    if a_priority > b_priority:
        return a
    return b

## The SHA-2 digest of `bytes` with luce-crypto's `algorithm` ("sha256", "sha384" or "sha512"),
## base64 encoded (each of apply_algorithm_to_bytes' three cases: `encode_base64(Hash::hash(bytes).bytes())`).
func sri_base64_digest(algorithm: str, bytes: const u8[]) -> ak.String!:
    var digest: u8[64] = ---
    let length = crypto.digest(bytes, digest, algorithm) else trap("MUST: the SHA-2 digest")
    return try ak.encode_base64(digest[0..<length])

## Ported from Libraries/LibWeb/SRI/SRI.cpp:38 Web::SRI::apply_algorithm_to_bytes.
# https://w3c.github.io/webappsec-subresource-integrity/#apply-algorithm-to-response
pub func sri_apply_algorithm_to_bytes(algorithm: ak.StringView, bytes: const ak.ByteBuffer*) -> ak.String!:
    # NOTE: The steps are duplicated here because each hash algorithm returns a different result type.

    if ak.string_view_eq_string_view(&algorithm, ak.sv("sha256")):
        # 1. Let result be the result of applying algorithm to bytes.
        # 2. Return the result of base64 encoding result.
        return try sri_base64_digest("sha256", ak.byte_buffer_bytes_const(bytes))

    if ak.string_view_eq_string_view(&algorithm, ak.sv("sha384")):
        # 1. Let result be the result of applying algorithm to bytes.
        # 2. Return the result of base64 encoding result.
        return try sri_base64_digest("sha384", ak.byte_buffer_bytes_const(bytes))

    if ak.string_view_eq_string_view(&algorithm, ak.sv("sha512")):
        # 1. Let result be the result of applying algorithm to bytes.
        # 2. Return the result of base64 encoding result.
        return try sri_base64_digest("sha512", ak.byte_buffer_bytes_const(bytes))

    trap("VERIFY_NOT_REACHED")

## Ported from Libraries/LibWeb/SRI/SRI.cpp:68 Web::SRI::parse_metadata.
# https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
pub func sri_parse_metadata(metadata: ak.StringView) -> ak.Vector[SriMetadata]!:
    # 1. Let result be the empty set.
    var result = ak.Vector[SriMetadata]()

    # 2. For each item returned by splitting metadata on spaces:
    var items = ak.string_view_split_view_u8(&metadata, ' ', ak.SplitBehavior.nothing)
    for item in ak.vector_span(&items):
        # 1. Let hash-with-opt-token-list be the result of splitting item on U+003F (?).
        var hash_with_opt_token_list = ak.string_view_split_view_u8(&item, '?')

        # 2. Let hash-expression be hash-with-opt-token-list[0].
        let hash_expression = *ak.vector_at(&hash_with_opt_token_list, 0)

        # 3. Let base64-value be the empty string.
        var base64_value = ak.StringView()

        # 4. Let hash-expr-token-list be the result of splitting hash-expression on U+002D (-).
        var hash_expr_token_list = ak.string_view_split_view_u8(&hash_expression, '-')

        # 5. Let algorithm be hash-expr-token-list[0].
        let algorithm = *ak.vector_at(&hash_expr_token_list, 0)

        # 6. If hash-expr-token-list[1] exists, set base64-value to hash-expr-token-list[1].
        if ak.vector_size(&hash_expr_token_list) > 1:
            base64_value = *ak.vector_at(&hash_expr_token_list, 1)

        # 7. If algorithm is not a hash function recognized by the user agent, continue.
        if sri_supported_hash_function_index(algorithm) == none:
            continue

        # 8. Let metadata be the ordered map «["alg" → algorithm, "val" → base64-value]».
        #    Note: Since no options are defined (see the §3.1 Integrity metadata), a corresponding entry is not set in metadata.
        #    If options are defined in a future version, hash-with-opt-token-list[1] can be utilized as options.
        let parsed = SriMetadata(algorithm = try ak.string_from_utf8(algorithm), base64_value = try ak.string_from_utf8(base64_value), options = ak.string_new())

        # 9. Append metadata to result.
        try ak.vector_try_append_t(&result, parsed)

    # 3. Return result.
    return result

## Ported from Libraries/LibWeb/SRI/SRI.cpp:116 Web::SRI::get_strongest_metadata_from_set.
# https://w3c.github.io/webappsec-subresource-integrity/#get-the-strongest-metadata
pub func sri_get_strongest_metadata_from_set(set: const ak.Vector[SriMetadata]*) -> ak.Vector[SriMetadata]!:
    # 1. Let result be the empty set and strongest be the empty string.
    var result = ak.Vector[SriMetadata]()
    var strongest: SriMetadata? = none

    # 2. For each item in set:
    for item in ak.vector_span_const(set):
        # 1. If result is the empty set, add item to result and set strongest to item, skip to the next item.
        if ak.vector_is_empty(&result):
            try ak.vector_try_append_t(&result, item)
            strongest = item
            continue

        # 2. Let currentAlgorithm be the alg component of strongest.
        let current_algorithm = (strongest else trap("VERIFY: Optional::value")).algorithm

        # 3. Let newAlgorithm be the alg component of item.
        let new_algorithm = item.algorithm

        # 4. If the result of getPrioritizedHashFunction(currentAlgorithm, newAlgorithm) is the empty string, add item to result.
        let prioritized_hash_function = sri_get_prioritized_hash_function(ak.string_bytes_as_string_view(&current_algorithm), ak.string_bytes_as_string_view(&new_algorithm))
        if ak.string_view_is_empty(&prioritized_hash_function):
            try ak.vector_try_append_t(&result, item)
        #    If the result is newAlgorithm, set strongest to item, set result to the empty set, and add item to result.
        elif ak.string_eq_string_view(&new_algorithm, prioritized_hash_function):
            strongest = item
            ak.vector_clear_with_capacity(&result)
            try ak.vector_try_append_t(&result, item)

    # 3. Return result.
    return result

## Ported from Libraries/LibWeb/SRI/SRI.cpp:153 Web::SRI::do_bytes_match_metadata_list.
# https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
pub func sri_do_bytes_match_metadata_list(bytes: const ak.ByteBuffer*, metadata_list: ak.StringView) -> bool!:
    # 1. Let parsedMetadata be the result of parsing metadataList.
    let parsed_metadata = try sri_parse_metadata(metadata_list)

    # 2. If parsedMetadata is empty set, return true.
    if ak.vector_is_empty(&parsed_metadata):
        return true

    # 3. Let metadata be the result of getting the strongest metadata from parsedMetadata.
    var metadata = try sri_get_strongest_metadata_from_set(&parsed_metadata)

    # 4. For each item in metadata:
    for item in ak.vector_span(&metadata):
        # 1. Let algorithm be the item["alg"].
        let algorithm = item.algorithm

        # 2. Let expectedValue be the item["val"].
        let expected_value = item.base64_value

        # 3. Let actualValue be the result of applying algorithm to bytes.
        let actual_value = try sri_apply_algorithm_to_bytes(ak.string_bytes_as_string_view(&algorithm), bytes)

        # 4. If actualValue is a case-sensitive match for expectedValue, return true.
        if ak.string_equals(&actual_value, &expected_value):
            return true

    # 5. Return false.
    return false