Truly independent web browser
LibCrypto: Remove the DER decoder
Shannon Booth8fe65a14e301
diff --git a/Libraries/LibCrypto/ASN1/ASN1.cpp b/Libraries/LibCrypto/ASN1/ASN1.cppdeleted file mode 100644index 876aae66ad2..00000000000--- a/Libraries/LibCrypto/ASN1/ASN1.cpp+++ /dev/null@@ -1,93 +0,0 @@-/*- * Copyright (c) 2021, the SerenityOS developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/ASN1/ASN1.h>--namespace Crypto::ASN1 {--StringView kind_name(Kind kind)-{- switch (kind) {- case Kind::Eol:- return "EndOfList"sv;- case Kind::Boolean:- return "Boolean"sv;- case Kind::Integer:- return "Integer"sv;- case Kind::BitString:- return "BitString"sv;- case Kind::OctetString:- return "OctetString"sv;- case Kind::Null:- return "Null"sv;- case Kind::ObjectIdentifier:- return "ObjectIdentifier"sv;- case Kind::ObjectDescriptor:- return "ObjectDescriptor"sv;- case Kind::External:- return "External"sv;- case Kind::Real:- return "Real"sv;- case Kind::Enumerated:- return "Enumerated"sv;- case Kind::EmbeddedPdv:- return "EmbeddedPdv"sv;- case Kind::Utf8String:- return "Utf8String"sv;- case Kind::RelativeOid:- return "RelativeOid"sv;- case Kind::Time:- return "Time"sv;- case Kind::Reserved:- return "Reserved"sv;- case Kind::Sequence:- return "Sequence"sv;- case Kind::Set:- return "Set"sv;- case Kind::NumericString:- return "NumericString"sv;- case Kind::PrintableString:- return "PrintableString"sv;- case Kind::T61String:- return "T61String"sv;- case Kind::VideotexString:- return "VideotexString"sv;- case Kind::IA5String:- return "IA5String"sv;- case Kind::UTCTime:- return "UTCTime"sv;- case Kind::GeneralizedTime:- return "GeneralizedTime"sv;- case Kind::GraphicString:- return "GraphicString"sv;- case Kind::VisibleString:- return "VisibleString"sv;- case Kind::GeneralString:- return "GeneralString"sv;- case Kind::UniversalString:- return "UniversalString"sv;- case Kind::CharacterString:- return "CharacterString"sv;- case Kind::BMPString:- return "BMPString"sv;- case Kind::Date:- return "Date"sv;- case Kind::TimeOfDay:- return "TimeOfDay"sv;- case Kind::DateTime:- return "DateTime"sv;- case Kind::Duration:- return "Duration"sv;- case Kind::OidIri:- return "OidIri"sv;- case Kind::RelativeOidIri:- return "RelativeOidIri"sv;- }-- return "InvalidKind"sv;-}--}diff --git a/Libraries/LibCrypto/ASN1/ASN1.h b/Libraries/LibCrypto/ASN1/ASN1.hindex 9a9a8fa7f16..60f3f571031 100644--- a/Libraries/LibCrypto/ASN1/ASN1.h+++ b/Libraries/LibCrypto/ASN1/ASN1.h@@ -64,12 +64,4 @@ enum class Type : u8 {Constructed = 0x20,};-struct Tag {- Kind kind;- Class class_;- Type type;-};--StringView kind_name(Kind);-}diff --git a/Libraries/LibCrypto/ASN1/DER.cpp b/Libraries/LibCrypto/ASN1/DER.cppindex d4c068825e4..445ce74bc8f 100644--- a/Libraries/LibCrypto/ASN1/DER.cpp+++ b/Libraries/LibCrypto/ASN1/DER.cpp@@ -11,220 +11,6 @@namespace Crypto::ASN1 {-ErrorOr<Tag> Decoder::read_tag()-{- auto byte = TRY(read_byte());- u8 class_ = byte & 0xc0;- u8 type = byte & 0x20;- u8 kind = byte & 0x1f;-- if (kind == 0x1f) {- kind = 0;- while (byte & 0x80) {- byte = TRY(read_byte());- kind = (kind << 7) | (byte & 0x7f);- }- }-- return Tag { (Kind)kind, (Class)class_, (Type)type };-}--ErrorOr<size_t> Decoder::read_length()-{- auto byte = TRY(read_byte());- size_t length = byte;-- if (byte & 0x80) {- auto count = byte & 0x7f;- if (count == 0 || count == 0x7f)- return Error::from_string_literal("ASN1::Decoder: Length has an invalid count value");-- auto data = TRY(read_bytes(count));- length = 0;-- if (data.size() > sizeof(size_t))- return Error::from_string_literal("ASN1::Decoder: Length is larger than the target type");-- for (auto&& byte : data)- length = (length << 8) | (size_t)byte;-- // DER encodes a length in the short form when it fits, and otherwise in as few bytes as possible.- if (data[0] == 0 || length < 0x80)- return Error::from_string_literal("ASN1::Decoder: Length is not encoded in the fewest bytes possible");- }-- return length;-}--ErrorOr<u8> Decoder::read_byte()-{- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Reading byte from an empty stack");-- auto& entry = m_stack.last();- if (entry.is_empty())- return Error::from_string_literal("ASN1::Decoder: Reading byte from an empty entry");-- auto byte = entry[0];- entry = entry.slice(1);-- return byte;-}--ErrorOr<ReadonlyBytes> Decoder::read_bytes(size_t length)-{- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Reading bytes from an empty stack");-- auto& entry = m_stack.last();- if (entry.size() < length)- return Error::from_string_literal("ASN1::Decoder: Reading bytes from an empty entry");-- auto bytes = entry.slice(0, length);- entry = entry.slice(length);-- return bytes;-}--ErrorOr<UnsignedBigInteger> Decoder::decode_arbitrary_sized_integer(ReadonlyBytes data)-{- if (data.size() < 1)- return Error::from_string_literal("ASN1::Decoder: Decoding arbitrary sized integer from an empty span");-- if (data.size() > 1- && ((data[0] == 0xff && data[1] & 0x80)- || (data[0] == 0x00 && !(data[1] & 0x80)))) {- return Error::from_string_literal("ASN1::Decoder: Arbitrary sized integer has an invalid format");- }-- bool is_negative = data[0] & 0x80;- if (is_negative)- return Error::from_string_literal("ASN1::Decoder: Decoding a negative unsigned arbitrary sized integer");-- return UnsignedBigInteger::import_data(data);-}--ErrorOr<StringView> Decoder::decode_octet_string(ReadonlyBytes bytes)-{- return StringView { bytes.data(), bytes.size() };-}--ErrorOr<nullptr_t> Decoder::decode_null(ReadonlyBytes data)-{- if (data.size() != 0)- return Error::from_string_literal("ASN1::Decoder: Decoding null from a non-empty span");-- return nullptr;-}--ErrorOr<ObjectIdentifier> Decoder::decode_object_identifier(ReadonlyBytes data)-{- if (data.is_empty())- return Error::from_string_literal("ASN1::Decoder: Decoding object identifier from an empty span");-- ObjectIdentifier result;- result.append(0); // Reserved space.-- // Subidentifiers must be encoded minimally, i.e. without leading zero digits, and we refuse any that is wider than- // the 28 bits our encoder is able to write back out. Neither a leading zero digit nor an overflow is therefore- // possible, which means a zero accumulator marks the start of a subidentifier.- static constexpr u64 max_subidentifier = 0x0fffffff;-- u64 value = 0;- for (auto byte : data) {- if (value == 0 && byte == 0x80)- return Error::from_string_literal("ASN1::Decoder: Object identifier has a non-minimally encoded subidentifier");-- value = (value << 7) | (byte & 0x7f);- if (value > max_subidentifier)- return Error::from_string_literal("ASN1::Decoder: Object identifier has an excessively large subidentifier");-- if (!(byte & 0x80)) {- result.append(value);- value = 0;- }- }-- if (value != 0)- return Error::from_string_literal("ASN1::Decoder: Object identifier ends with an unterminated subidentifier");-- if (result[1] >= 1600)- return Error::from_string_literal("ASN1::Decoder: Invalid encoding in object identifier");-- result[0] = result[1] / 40;- result[1] = result[1] % 40;-- return result;-}--ErrorOr<BitStringView> Decoder::decode_bit_string(ReadonlyBytes data)-{- if (data.size() < 1)- return Error::from_string_literal("ASN1::Decoder: Decoding bit string from empty span");-- auto unused_bits = data[0];- auto total_size_in_bits = (data.size() - 1) * 8;-- if (unused_bits > total_size_in_bits)- return Error::from_string_literal("ASN1::Decoder: Number of unused bits is larger than the total size");-- return BitStringView { data.slice(1), unused_bits };-}--ErrorOr<Tag> Decoder::peek()-{- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Peeking using an empty stack");-- if (eof())- return Error::from_string_literal("ASN1::Decoder: Peeking using a decoder that is at EOF");-- if (m_current_tag.has_value())- return m_current_tag.value();-- m_current_tag = TRY(read_tag());-- return m_current_tag.value();-}--bool Decoder::eof() const-{- return m_stack.is_empty() || m_stack.last().is_empty();-}--ErrorOr<void> Decoder::enter()-{- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Entering using an empty stack");-- auto tag = TRY(peek());- if (tag.type != Type::Constructed)- return Error::from_string_literal("ASN1::Decoder: Entering a non-constructed type");-- auto length = TRY(read_length());-- auto data = TRY(read_bytes(length));-- m_current_tag.clear();-- m_stack.append(data);- return {};-}--ErrorOr<void> Decoder::leave()-{- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Leaving using an empty stack");-- if (m_stack.size() == 1)- return Error::from_string_literal("ASN1::Decoder: Leaving the main context");-- m_stack.take_last();- m_current_tag.clear();-- return {};-}-ErrorOr<void> Encoder::write_tag(Class class_, Type type, Kind kind){auto class_byte = to_underlying(class_);diff --git a/Libraries/LibCrypto/ASN1/DER.h b/Libraries/LibCrypto/ASN1/DER.hindex ee30d5ced5a..c52f9dbaf32 100644--- a/Libraries/LibCrypto/ASN1/DER.h+++ b/Libraries/LibCrypto/ASN1/DER.h@@ -7,88 +7,15 @@#pragma once#include <AK/Array.h>-#include <AK/String.h>#include <AK/Types.h>#include <AK/Vector.h>#include <LibCrypto/ASN1/ASN1.h>#include <LibCrypto/BigInt/UnsignedBigInteger.h>-namespace {--// Used by ASN1 macros, whose errors are views of it. It keeps the text of the last error of a thread, cut to fit.-// NB: Not a String, so that it needs no destructor and a thread that ends leaves nothing behind.-struct ASN1ErrorString {- ASN1ErrorString& operator=(String const& text)- {- m_length = min(text.bytes().size(), m_buffer.size());- text.bytes().trim(m_length).copy_to(m_buffer);- return *this;- }-- StringView bytes_as_string_view() const { return StringView { m_buffer.span().trim(m_length) }; }-- Array<u8, 512> m_buffer {};- size_t m_length { 0 };-};--static thread_local ASN1ErrorString s_error_string;--}-namespace Crypto::ASN1 {using ObjectIdentifier = Vector<u32, 12>;-#define ERROR_WITH_SCOPE(error) \- do { \- s_error_string = TRY(String::formatted("{}: {}", current_scope, error)); \- return Error::from_string_view(s_error_string.bytes_as_string_view()); \- } while (0)--#define ENTER_TYPED_SCOPE(tag_kind_name, scope) \- do { \- if (auto tag = decoder.peek(); tag.is_error() || tag.value().kind != Crypto::ASN1::Kind::tag_kind_name) { \- if (tag.is_error()) \- ERROR_WITH_SCOPE(TRY(String::formatted(scope " data was invalid: {}", tag.error()))); \- else \- ERROR_WITH_SCOPE(TRY(String::formatted(scope " data was not of kind " #tag_kind_name " was {}", Crypto::ASN1::kind_name(tag.value().kind)))); \- } \- ENTER_SCOPE(scope); \- } while (0)--#define ENTER_SCOPE(scope) \- do { \- if (auto result = decoder.enter(); result.is_error()) { \- ERROR_WITH_SCOPE(TRY(String::formatted("Failed to enter scope: {}", scope))); \- } \- PUSH_SCOPE(scope) \- } while (0)--#define PUSH_SCOPE(scope) current_scope.append(#scope##sv);--#define EXIT_SCOPE() \- do { \- if (auto error = decoder.leave(); error.is_error()) { \- ERROR_WITH_SCOPE(TRY(String::formatted("Failed to exit scope: {}", error.error()))); \- } \- POP_SCOPE(); \- } while (0)--#define POP_SCOPE() current_scope.remove(current_scope.size() - 1);--#define READ_OBJECT(kind_name, type_name, value_name) \- auto value_name##_result = decoder.read<type_name>(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::kind_name); \- if (value_name##_result.is_error()) { \- ERROR_WITH_SCOPE(TRY(String::formatted("Read of kind " #kind_name " failed: {}", value_name##_result.error()))); \- } \- auto value_name = value_name##_result.release_value();--#define REWRITE_TAG(kind_name) \- auto value_name##_result = decoder.rewrite_tag(Crypto::ASN1::Kind::kind_name); \- if (value_name##_result.is_error()) { \- ERROR_WITH_SCOPE(TRY(String::formatted("Rewrite of kind " #kind_name " failed: {}", value_name##_result.error()))); \- }-class BitStringView {public:BitStringView(ReadonlyBytes data, size_t unused_bits)@@ -97,13 +24,6 @@ public:{}- ErrorOr<ReadonlyBytes> raw_bytes() const- {- if (m_unused_bits != 0)- return Error::from_string_literal("ASN1::Decoder: BitStringView contains unexpected partial bytes");- return m_data;- }-size_t unused_bits() const { return m_unused_bits; }size_t byte_length() const { return m_data.size(); }@@ -114,199 +34,6 @@ private:size_t m_unused_bits;};-class Decoder {-public:- Decoder(ReadonlyBytes data)- {- m_stack.append(data);- }-- // Read a tag without consuming it (and its data).- ErrorOr<Tag> peek();-- bool eof() const;-- template<typename ValueType>- struct TaggedValue {- Tag tag;- ValueType value;- };-- ErrorOr<void> rewrite_tag(Kind kind)- {- if (m_stack.is_empty())- return Error::from_string_literal("Nothing on stack to rewrite");-- if (eof())- return Error::from_string_literal("Stream is empty");-- if (m_current_tag.has_value()) {- m_current_tag->kind = kind;- return {};- }-- auto tag = TRY(read_tag());- m_current_tag = tag;- m_current_tag->kind = kind;- return {};- }-- ErrorOr<void> drop()- {- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Trying to drop using an empty stack");-- if (eof())- return Error::from_string_literal("ASN1::Decoder: Trying to drop using a decoder that is EOF");-- auto previous_position = m_stack;- auto previous_tag = m_current_tag;-- auto tag_or_error = peek();- if (tag_or_error.is_error()) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return tag_or_error.release_error();- }-- auto length_or_error = read_length();- if (length_or_error.is_error()) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return length_or_error.release_error();- }-- auto length = length_or_error.value();-- auto bytes_result = read_bytes(length);- if (bytes_result.is_error()) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return bytes_result.release_error();- }-- m_current_tag.clear();- return {};- }-- template<typename ValueType>- ErrorOr<ValueType> read(Optional<Class> class_override = {}, Optional<Kind> kind_override = {})- {- if (m_stack.is_empty())- return Error::from_string_literal("ASN1::Decoder: Trying to read using an empty stack");-- if (eof())- return Error::from_string_literal("ASN1::Decoder: Trying to read using a decoder that is EOF");-- auto previous_position = m_stack;- auto previous_tag = m_current_tag;-- auto tag_or_error = peek();- if (tag_or_error.is_error()) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return tag_or_error.release_error();- }-- if (tag_or_error.value().type != Type::Primitive) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return Error::from_string_literal("ASN1::Decoder: Trying to read a constructed value as primitive");- }-- auto length_or_error = read_length();- if (length_or_error.is_error()) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return length_or_error.release_error();- }-- auto tag = tag_or_error.value();- auto length = length_or_error.value();-- auto value_or_error = read_value<ValueType>(class_override.value_or(tag.class_), kind_override.value_or(tag.kind), length);- if (value_or_error.is_error()) {- m_stack = move(previous_position);- m_current_tag = move(previous_tag);- return value_or_error.release_error();- }-- m_current_tag.clear();-- return value_or_error.release_value();- }-- ErrorOr<void> enter();- ErrorOr<void> leave();--private:- template<typename ValueType, typename DecodedType>- ErrorOr<ValueType> with_type_check(DecodedType&& value)- {- if constexpr (requires { ValueType { value }; })- return ValueType { value };-- return Error::from_string_literal("ASN1::Decoder: Trying to decode a value from an incompatible type");- }-- template<typename ValueType, typename DecodedType>- ErrorOr<ValueType> with_type_check(ErrorOr<DecodedType>&& value_or_error)- {- if (value_or_error.is_error())- return value_or_error.release_error();-- auto&& value = value_or_error.value();- if constexpr (requires { ValueType { value }; })- return ValueType { value };-- return Error::from_string_literal("ASN1::Decoder: Trying to decode a value from an incompatible type");- }-- template<typename ValueType>- ErrorOr<ValueType> read_value(Class klass, Kind kind, size_t length)- {- auto data = TRY(read_bytes(length));-- if constexpr (IsSame<ValueType, ReadonlyBytes>) {- return data;- } else {- if (klass != Class::Universal)- return with_type_check<ValueType>(data);-- if (kind == Kind::Integer)- return with_type_check<ValueType>(decode_arbitrary_sized_integer(data));-- if (kind == Kind::OctetString)- return with_type_check<ValueType>(decode_octet_string(data));-- if (kind == Kind::Null)- return with_type_check<ValueType>(decode_null(data));-- if (kind == Kind::ObjectIdentifier)- return with_type_check<ValueType>(decode_object_identifier(data));-- if (kind == Kind::BitString)- return with_type_check<ValueType>(decode_bit_string(data));-- return with_type_check<ValueType>(data);- }- }-- ErrorOr<Tag> read_tag();- ErrorOr<size_t> read_length();- ErrorOr<u8> read_byte();- ErrorOr<ReadonlyBytes> read_bytes(size_t length);-- static ErrorOr<UnsignedBigInteger> decode_arbitrary_sized_integer(ReadonlyBytes);- static ErrorOr<StringView> decode_octet_string(ReadonlyBytes);- static ErrorOr<nullptr_t> decode_null(ReadonlyBytes);- static ErrorOr<ObjectIdentifier> decode_object_identifier(ReadonlyBytes);- static ErrorOr<BitStringView> decode_bit_string(ReadonlyBytes);-- Vector<ReadonlyBytes> m_stack;- Optional<Tag> m_current_tag;-};-class Encoder {public:Encoder()diff --git a/Libraries/LibCrypto/CMakeLists.txt b/Libraries/LibCrypto/CMakeLists.txtindex 1fe31cfb04a..0960bb799eb 100644--- a/Libraries/LibCrypto/CMakeLists.txt+++ b/Libraries/LibCrypto/CMakeLists.txt@@ -4,7 +4,6 @@ set(SOURCESKeyHandle.cppOpenSSL.cppRustBindings.cpp- ASN1/ASN1.cppASN1/DER.cppAuthentication/HMAC.cppAuthentication/KMAC.cppdiff --git a/Meta/Fuzzers/FuzzASN1.cpp b/Meta/Fuzzers/FuzzASN1.cppdeleted file mode 100644index 7de954268b0..00000000000--- a/Meta/Fuzzers/FuzzASN1.cpp+++ /dev/null@@ -1,22 +0,0 @@-/*- * Copyright (c) 2021, Brian Gianforcaro <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibCrypto/ASN1/DER.h>-#include <stddef.h>-#include <stdint.h>--extern "C" int LLVMFuzzerTestOneInput(uint8_t const* data, size_t size)-{- AK::set_debug_enabled(false);-- Crypto::ASN1::Decoder decoder(ReadonlyBytes { data, size });- while (!decoder.eof()) {- if (decoder.drop().is_error())- break;- }-- return 0;-}diff --git a/Meta/Fuzzers/fuzzers.cmake b/Meta/Fuzzers/fuzzers.cmakeindex 6bcc3dbdb84..6dc0dd7b8a0 100644--- a/Meta/Fuzzers/fuzzers.cmake+++ b/Meta/Fuzzers/fuzzers.cmake@@ -1,5 +1,4 @@set(FUZZER_TARGETS- ASN1Base64RoundtripBMPLoaderGIFLoader@@ -20,7 +19,6 @@ if (TARGET LibWeb)list(APPEND FUZZER_TARGETS CSSParser)endif()-set(FUZZER_DEPENDENCIES_ASN1 LibCrypto LibTLS)set(FUZZER_DEPENDENCIES_BMPLoader LibGfx LibImageDecoders)set(FUZZER_DEPENDENCIES_CSSParser LibWeb)set(FUZZER_DEPENDENCIES_GIFLoader LibGfx LibImageDecoders)diff --git a/Tests/LibCrypto/TestASN1.cpp b/Tests/LibCrypto/TestASN1.cppindex 7c45a52a414..8b588e85c32 100644--- a/Tests/LibCrypto/TestASN1.cpp+++ b/Tests/LibCrypto/TestASN1.cpp@@ -4,164 +4,76 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/StringView.h>-#include <LibCrypto/ASN1/ASN1.h>#include <LibCrypto/ASN1/DER.h>#include <LibTest/TestCase.h>-TEST_CASE(test_encoder_primitives)+template<typename Write>+static ByteBuffer encode(Write write){- auto roundtrip_value = [](auto value) {- Crypto::ASN1::Encoder encoder;- MUST(encoder.write(value));- auto encoded = encoder.finish();- Crypto::ASN1::Decoder decoder(encoded);- auto decoded = MUST(decoder.read<decltype(value)>());- EXPECT_EQ(decoded, value);- };-- roundtrip_value(Crypto::UnsignedBigInteger { 0 });- roundtrip_value(Crypto::UnsignedBigInteger { 1 });- roundtrip_value(TRY_OR_FAIL(Crypto::UnsignedBigInteger { 2 }.shift_left(128)));- roundtrip_value(TRY_OR_FAIL(Crypto::UnsignedBigInteger { 2 }.shift_left(256)));-- roundtrip_value(Crypto::ASN1::ObjectIdentifier { 1, 2, 840, 113549, 1, 1, 1 });- roundtrip_value(Crypto::ASN1::ObjectIdentifier { 1, 2, 840, 113549, 1, 1, 11 });- roundtrip_value(Crypto::ASN1::ObjectIdentifier { 1, 2, 0xfffffff });-- roundtrip_value(nullptr);-- u8 const bit_string_bytes[] { 0x00, 0x01, 0x02, 0x03 };Crypto::ASN1::Encoder encoder;- MUST(encoder.write(Crypto::ASN1::BitStringView { bit_string_bytes, 0 }));- auto encoded = encoder.finish();- Crypto::ASN1::Decoder decoder(encoded);- auto decoded = MUST(decoder.read<Crypto::ASN1::BitStringView>());- EXPECT_EQ(MUST(decoded.raw_bytes()), ReadonlyBytes { bit_string_bytes });+ MUST(write(encoder));+ return encoder.finish();}-TEST_CASE(test_encoder_constructed)+static void expect_encoding(ByteBuffer const& encoded, Vector<u8> const& expected){- Crypto::ASN1::Encoder encoder;- /*- * RSAPrivateKey ::= SEQUENCE {- * version Version, -- Version ::= INTEGER { two-prime(0), multi(1) }- * modulus INTEGER, -- n- * publicExponent INTEGER, -- e- * privateExponent INTEGER, -- d- * prime1 INTEGER, -- p- * prime2 INTEGER, -- q- * exponent1 INTEGER, -- d mod (p-1)- * exponent2 INTEGER, -- d mod (q-1)- * coefficient INTEGER, -- (inverse of q) mod p- * otherPrimeInfos OtherPrimeInfos OPTIONAL- * }- */- (void)encoder.write_constructed(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::Sequence, [&] {- MUST(encoder.write(0u)); // version- MUST(encoder.write(0x1234u)); // modulus- MUST(encoder.write(0x10001u)); // publicExponent- MUST(encoder.write(0x5678u)); // privateExponent- MUST(encoder.write(0x9abcu)); // prime1- MUST(encoder.write(0xdef0u)); // prime2- MUST(encoder.write(0x1234u)); // exponent1- MUST(encoder.write(0x5678u)); // exponent2- MUST(encoder.write(0x9abcu)); // coefficient- });- auto encoded = encoder.finish();- Crypto::ASN1::Decoder decoder(encoded);- MUST(decoder.enter()); // Sequence- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0u); // version- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x1234u); // modulus- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x10001u); // publicExponent- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x5678u); // privateExponent- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x9abcu); // prime1- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0xdef0u); // prime2- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x1234u); // exponent1- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x5678u); // exponent2- EXPECT_EQ(MUST(decoder.read<Crypto::UnsignedBigInteger>()), 0x9abcu); // coefficient- EXPECT(decoder.eof()); // no otherPrimeInfos- MUST(decoder.leave()); // Sequence- EXPECT(decoder.eof()); // no other data+ EXPECT_EQ(encoded.bytes(), expected.span());}-TEST_CASE(test_decoder_restores_state_after_failed_read)+TEST_CASE(test_encoder_integers){- // An Integer tag declaring a length of 5, but only 3 value bytes are present.- u8 const data[] { 0x02, 0x05, 0x00, 0x00, 0x00 };- Crypto::ASN1::Decoder decoder({ data, sizeof(data) });+ expect_encoding(encode([](auto& encoder) { return encoder.write(Crypto::UnsignedBigInteger { 0 }); }), { 0x02, 0x01, 0x00 });+ expect_encoding(encode([](auto& encoder) { return encoder.write(Crypto::UnsignedBigInteger { 1 }); }), { 0x02, 0x01, 0x01 });+ expect_encoding(encode([](auto& encoder) { return encoder.write(0x1234u); }), { 0x02, 0x02, 0x12, 0x34 });- EXPECT(decoder.read<Crypto::UnsignedBigInteger>().is_error());-- // The first failed read should leave the decoder state unchanged, so a second drop should have the same result.- EXPECT(decoder.read<Crypto::UnsignedBigInteger>().is_error());+ // A leading zero keeps an integer whose top bit is set positive.+ expect_encoding(encode([](auto& encoder) { return encoder.write(0x80u); }), { 0x02, 0x02, 0x00, 0x80 });}-TEST_CASE(test_decoder_restores_state_after_failed_drop)+TEST_CASE(test_encoder_object_identifiers){- // A Boolean tag declaring a length of 5, but only 3 value bytes are present.- u8 const data[] { 0x01, 0x05, 0x00, 0x00, 0x00 };- Crypto::ASN1::Decoder decoder({ data, sizeof(data) });-- EXPECT(decoder.drop().is_error());+ expect_encoding(encode([](auto& encoder) { return encoder.write(Crypto::ASN1::ObjectIdentifier { 1, 2, 840, 113549, 1, 1, 1 }); }),+ { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 });- // The first failed drop should leave the decoder state unchanged, so a second drop should have the same result.- EXPECT(decoder.drop().is_error());+ // The widest subidentifier the encoder can write.+ expect_encoding(encode([](auto& encoder) { return encoder.write(Crypto::ASN1::ObjectIdentifier { 1, 2, 0xfffffff }); }),+ { 0x06, 0x05, 0x2a, 0xff, 0xff, 0xff, 0x7f });}-TEST_CASE(test_decode_object_identifier)+TEST_CASE(test_encoder_null_and_strings){- // 1.2.840.113549.1.1.1 (rsaEncryption)- u8 const rsa_encryption[] { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };- Crypto::ASN1::Decoder decoder({ rsa_encryption, sizeof(rsa_encryption) });- EXPECT_EQ(MUST(decoder.read<Crypto::ASN1::ObjectIdentifier>()), (Crypto::ASN1::ObjectIdentifier { 1, 2, 840, 113549, 1, 1, 1 }));-- // The widest subidentifier the encoder can write back out.- u8 const widest_subidentifier[] { 0x06, 0x05, 0x2a, 0xff, 0xff, 0xff, 0x7f };- Crypto::ASN1::Decoder widest_decoder({ widest_subidentifier, sizeof(widest_subidentifier) });- EXPECT_EQ(MUST(widest_decoder.read<Crypto::ASN1::ObjectIdentifier>()), (Crypto::ASN1::ObjectIdentifier { 1, 2, 0xfffffff }));+ expect_encoding(encode([](auto& encoder) { return encoder.write(nullptr); }), { 0x05, 0x00 });++ u8 const bytes[] { 0x00, 0x01, 0x02, 0x03 };+ expect_encoding(encode([&](auto& encoder) { return encoder.write(Crypto::ASN1::BitStringView { bytes, 0 }); }),+ { 0x03, 0x05, 0x00, 0x00, 0x01, 0x02, 0x03 });+ expect_encoding(encode([&](auto& encoder) { return encoder.template write<ReadonlyBytes>(bytes); }),+ { 0x04, 0x04, 0x00, 0x01, 0x02, 0x03 });+ expect_encoding(encode([&](auto& encoder) { return encoder.template write<ReadonlyBytes>(bytes, Crypto::ASN1::Class::Context, static_cast<Crypto::ASN1::Kind>(0)); }),+ { 0x80, 0x04, 0x00, 0x01, 0x02, 0x03 });}-TEST_CASE(test_decode_object_identifier_rejects_invalid_encodings)+TEST_CASE(test_encoder_lengths_in_the_fewest_bytes_possible){- auto expect_decode_failure = [](ReadonlyBytes data) {- Crypto::ASN1::Decoder decoder(data);- EXPECT(decoder.read<Crypto::ASN1::ObjectIdentifier>().is_error());+ auto header_of_octet_string = [](size_t length) {+ auto contents = MUST(ByteBuffer::create_zeroed(length));+ auto encoded = encode([&](auto& encoder) { return encoder.template write<ReadonlyBytes>(contents); });+ return MUST(ByteBuffer::copy(encoded.bytes().trim(encoded.size() - length)));};- // No subidentifiers at all.- u8 const empty[] { 0x06, 0x00 };- expect_decode_failure({ empty, sizeof(empty) });-- // rsaEncryption followed by a subidentifier that asks for a base-128 digit which never arrives.- u8 const unterminated[] { 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x81 };- expect_decode_failure({ unterminated, sizeof(unterminated) });-- // A subidentifier with a leading zero digit.- u8 const non_minimal[] { 0x06, 0x03, 0x2a, 0x80, 0x01 };- expect_decode_failure({ non_minimal, sizeof(non_minimal) });-- // A subidentifier one bit wider than the encoder can represent.- u8 const too_large[] { 0x06, 0x06, 0x2a, 0x81, 0x80, 0x80, 0x80, 0x00 };- expect_decode_failure({ too_large, sizeof(too_large) });+ expect_encoding(header_of_octet_string(127), { 0x04, 0x7f });+ expect_encoding(header_of_octet_string(128), { 0x04, 0x81, 0x80 });+ expect_encoding(header_of_octet_string(256), { 0x04, 0x82, 0x01, 0x00 });}-TEST_CASE(test_decoder_lengths_in_the_fewest_bytes_possible)+TEST_CASE(test_encoder_constructed){- auto read_octet_string_of_length = [](Vector<u8> length_bytes, size_t length) {- Vector<u8> der { 0x04 };- der.extend(length_bytes);- for (size_t i = 0; i < length; ++i)- der.append(0xaa);- Crypto::ASN1::Decoder decoder { der };- return decoder.read<StringView>();- };-- EXPECT_EQ(TRY_OR_FAIL(read_octet_string_of_length({ 0x05 }, 5)).length(), 5u);- EXPECT_EQ(TRY_OR_FAIL(read_octet_string_of_length({ 0x81, 0x80 }, 128)).length(), 128u);- EXPECT_EQ(TRY_OR_FAIL(read_octet_string_of_length({ 0x82, 0x01, 0x00 }, 256)).length(), 256u);-- EXPECT(read_octet_string_of_length({ 0x81, 0x05 }, 5).is_error());- EXPECT(read_octet_string_of_length({ 0x82, 0x00, 0x80 }, 128).is_error());- EXPECT(read_octet_string_of_length({ 0x83, 0x00, 0x01, 0x00 }, 256).is_error());+ auto encoded = encode([](auto& encoder) {+ return encoder.write_constructed(Crypto::ASN1::Class::Universal, Crypto::ASN1::Kind::Sequence, [&]() -> ErrorOr<void> {+ TRY(encoder.write(0u));+ TRY(encoder.write(0x1234u));+ return {};+ });+ });+ expect_encoding(encoded, { 0x30, 0x07, 0x02, 0x01, 0x00, 0x02, 0x02, 0x12, 0x34 });}