From 81b7d4dc722742b364f3c2d2eb6b06986a60e26d Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Tue, 5 Jan 2021 15:33:18 +0000 Subject: [PATCH] Initial commit --- .gitignore | 15 + LICENSE.txt | 203 +++ Package.swift | 30 + README.md | 32 + Sources/SwiftASN1/ASN1.swift | 1176 +++++++++++++++++ .../SwiftASN1/Basic ASN1 Types/ASN1Any.swift | 95 ++ .../Basic ASN1 Types/ASN1BitString.swift | 125 ++ .../Basic ASN1 Types/ASN1Boolean.swift | 54 + .../Basic ASN1 Types/ASN1Identifier.swift | 231 ++++ .../Basic ASN1 Types/ASN1Integer.swift | 301 +++++ .../SwiftASN1/Basic ASN1 Types/ASN1Null.swift | 43 + .../Basic ASN1 Types/ASN1OctetString.swift | 66 + .../Basic ASN1 Types/ASN1Strings.swift | 351 +++++ .../Basic ASN1 Types/ArraySliceBigint.swift | 38 + .../Basic ASN1 Types/GeneralizedTime.swift | 200 +++ .../Basic ASN1 Types/ObjectIdentifier.swift | 345 +++++ .../Basic ASN1 Types/TimeUtilities.swift | 277 ++++ .../SwiftASN1/Basic ASN1 Types/UTCTime.swift | 184 +++ Sources/SwiftASN1/Docs.docc/DecodingASN1.md | 304 +++++ Sources/SwiftASN1/Docs.docc/index.md | 85 ++ Sources/SwiftASN1/ECDSASignature.swift | 53 + Sources/SwiftASN1/Errors.swift | 43 + Sources/SwiftASN1/PEMDocument.swift | 116 ++ Sources/SwiftASN1/PKCS8PrivateKey.swift | 97 ++ Sources/SwiftASN1/SEC1PrivateKey.swift | 104 ++ Sources/SwiftASN1/SubjectPublicKeyInfo.swift | 122 ++ Tests/SwiftASN1Tests/ASN1StringTests.swift | 178 +++ Tests/SwiftASN1Tests/ASN1Tests.swift | 788 +++++++++++ .../SwiftASN1Tests/GeneralizedTimeTests.swift | 180 +++ 29 files changed, 5836 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE.txt create mode 100644 Package.swift create mode 100644 README.md create mode 100644 Sources/SwiftASN1/ASN1.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1Any.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1BitString.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1Boolean.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1Identifier.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1Integer.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ASN1Strings.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/TimeUtilities.swift create mode 100644 Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift create mode 100644 Sources/SwiftASN1/Docs.docc/DecodingASN1.md create mode 100644 Sources/SwiftASN1/Docs.docc/index.md create mode 100644 Sources/SwiftASN1/ECDSASignature.swift create mode 100644 Sources/SwiftASN1/Errors.swift create mode 100644 Sources/SwiftASN1/PEMDocument.swift create mode 100644 Sources/SwiftASN1/PKCS8PrivateKey.swift create mode 100644 Sources/SwiftASN1/SEC1PrivateKey.swift create mode 100644 Sources/SwiftASN1/SubjectPublicKeyInfo.swift create mode 100644 Tests/SwiftASN1Tests/ASN1StringTests.swift create mode 100644 Tests/SwiftASN1Tests/ASN1Tests.swift create mode 100644 Tests/SwiftASN1Tests/GeneralizedTimeTests.swift diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e10443c --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +Package.pins +*.pem +/docs/1.* +/docs/2.* +Package.resolved +.podspecs +DerivedData +.swiftpm +**/gyb.pyc + +.*.sw[nop] diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..6b0b127 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..0f85910 --- /dev/null +++ b/Package.swift @@ -0,0 +1,30 @@ +// swift-tools-version:5.6 +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2022 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import PackageDescription + +let package = Package( + name: "swift-asn1", + products: [ + .library(name: "SwiftASN1", targets: ["SwiftASN1"]), + ], + dependencies: [ + .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"), + ], + targets: [ + .target(name: "SwiftASN1"), + .testTarget(name: "SwiftASN1Tests", dependencies: ["SwiftASN1"]), + ] +) diff --git a/README.md b/README.md new file mode 100644 index 0000000..6e35ad9 --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +# SwiftASN1 + +An implementation of ASN.1 types and DER serialization. + +## Overview + +ASN.1, and the DER encoding scheme, is a commonly used object serialization format. The most common use-cases for ASN.1 in +general computing are in the cryptographic space, but there are a number of use-cases in a wide range of fields. This module +provides an implementation of a number of ASN.1 types, as well as the DER serialization format for ASN.1. + +ASN.1 can be used abstractly to describe essentially any kind of object. ASN.1 objects are made up of either primitive or +composite (called "constructed") types. Individual scalar objects can be combined into aggregate types, and composed essentially +arbitrarily to form abstract object formats. + +Importantly, the ASN.1 object description does not define a specific encoding for these objects. Instead there are a wide range +of possible ways to serialize or deserialize an ASN.1 object. Some of the most prominent are BER (the Basic Encoding Rules), +CER (the Canonical Encoding Rules), DER (the Distinguished Encoding Rules), and XER (the XML Encoding Rules). For the cryptographic +use-case DER is the standard choice, as a given ASN.1 object can be encoded in only one way under DER. This makes signing and verifying +vastly easier, as it is at least in principle possible to perfectly reconstruct the serialization of a parsed object. + +This module provides several moving pieces: + +1. A high-level representation of an ASN.1 object, in the form of a tree of object nodes (`ASN1Node`). +2. A DER parser that can construct the ASN.1 tree from serialized bytes (`ASN1.parse(_:)`). +3. A DER serializer that can construct serialized bytes from the ASN.1 tree (`ASN1.Serializer`). +4. A number of built-in ASN.1 types, representing common constructs. + +These moving pieces combine to provide support for the DER representation of ASN.1 suitable for a wide range of cryptographic uses. + +## Getting Started + +Consult the documentation for examples of how to use the code. A number of examples are also present in the repository itself. diff --git a/Sources/SwiftASN1/ASN1.swift b/Sources/SwiftASN1/ASN1.swift new file mode 100644 index 0000000..e17c500 --- /dev/null +++ b/Sources/SwiftASN1/ASN1.swift @@ -0,0 +1,1176 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +/// ``ASN1`` defines a namespace that is used to store a number of helper methods and types. +public enum ASN1 { } + +// MARK: - Parser Node +extension ASN1 { + /// An ``ASN1ParserNode`` is a representation of a parsed ASN.1 TLV section. + /// + /// An ``ASN1ParserNode`` may be primitive, or may be composed of other ``ASN1ParserNode``s. + /// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections + /// we're uninterested in. + /// + /// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API. + @usableFromInline + struct ASN1ParserNode { + /// The identifier. + @usableFromInline + var identifier: ASN1Identifier + + /// The depth of this node. + @usableFromInline + var depth: Int + + /// The encoded bytes for this complete ASN.1 object. + @usableFromInline + var encodedBytes: ArraySlice + + /// The data bytes for this node, if it is primitive. + @usableFromInline + var dataBytes: ArraySlice? + + @inlinable + init( + identifier: ASN1.ASN1Identifier, + depth: Int, + encodedBytes: ArraySlice, + dataBytes: ArraySlice? = nil + ) { + self.identifier = identifier + self.depth = depth + self.encodedBytes = encodedBytes + self.dataBytes = dataBytes + } + } +} + +extension ASN1.ASN1ParserNode: Hashable { } + +extension ASN1.ASN1ParserNode: Sendable { } + +extension ASN1.ASN1ParserNode: CustomStringConvertible { + @inlinable + var description: String { + return "ASN1.ASN1ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))" + } +} + +// MARK: - Sequence, SequenceOf, and Set +extension ASN1 { + /// Parse the node as an ASN.1 SEQUENCE. + /// + /// The "child" elements in the sequence will be exposed as an iterator to `builder`. + /// + /// - parameters: + /// - node: The ``ASN1Node`` to parse + /// - identifier: The ``ASN1/ASN1Identifier`` that the SEQUENCE is expected to have. + /// - builder: A closure that will be called with the collection of nodes within the sequence. + @inlinable + public static func sequence(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T { + guard node.identifier == identifier, case .constructed(let nodes) = node.content else { + throw ASN1Error.unexpectedFieldType + } + + var iterator = nodes.makeIterator() + + let result = try builder(&iterator) + + guard iterator.next() == nil else { + throw ASN1Error.invalidASN1Object + } + + return result + } + + /// Parse the node as an ASN.1 SEQUENCE OF. + /// + /// Constructs an array of `T` elements parsed from the sequence. + /// + /// - parameters: + /// - of: An optional parameter to express the type to decode. + /// - identifier: The ``ASN1/ASN1Identifier`` that the SEQUENCE OF is expected to have. + /// - rootNode: The ``ASN1Node`` to parse + /// - returns: An array of elements representing the elements in the sequence. + @inlinable + public static func sequence(of: T.Type = T.self, identifier: ASN1.ASN1Identifier, rootNode: ASN1Node) throws -> [T] { + guard rootNode.identifier == identifier, case .constructed(let nodes) = rootNode.content else { + throw ASN1Error.unexpectedFieldType + } + + return try nodes.map { try T(asn1Encoded: $0) } + } + + /// Parse the node as an ASN.1 SEQUENCE OF. + /// + /// Constructs an array of `T` elements parsed from the sequence. + /// + /// - parameters: + /// - of: An optional parameter to express the type to decode. + /// - identifier: The ``ASN1/ASN1Identifier`` that the SEQUENCE OF is expected to have. + /// - nodes: An ``ASN1/ASN1NodeCollection/Iterator`` of nodes to parse. + /// - returns: An array of elements representing the elements in the sequence. + @inlinable + public static func sequence(of: T.Type = T.self, identifier: ASN1.ASN1Identifier, nodes: inout ASN1.ASN1NodeCollection.Iterator) throws -> [T] { + guard let node = nodes.next() else { + // Not present, throw. + throw ASN1Error.invalidASN1Object + } + + return try sequence(of: T.self, identifier: identifier, rootNode: node) + } + + /// Parse the node as an ASN.1 SET. + /// + /// The "child" elements in the sequence will be exposed as an iterator to `builder`. + /// + /// - parameters: + /// - node: The ``ASN1Node`` to parse + /// - identifier: The ``ASN1/ASN1Identifier`` that the SET is expected to have. + /// - builder: A closure that will be called with the collection of nodes within the set. + @inlinable + public static func set(_ node: ASN1Node, identifier: ASN1.ASN1Identifier, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T { + // Shhhh these two are secretly the same with identifier. + return try sequence(node, identifier: identifier, builder) + } +} + +// MARK: - Optional explicitly tagged +extension ASN1 { + /// Parses an optional explicitly tagged element. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tagNumber: The number of the explicit tag. + /// - tagClass: The class of the explicit tag. + /// - builder: A closure that will be called with the node for the element, if the element is present. + /// + /// - returns: The result of `builder` if the element was present, or `nil` if it was not. + @inlinable + public static func optionalExplicitlyTagged(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T? { + var localNodesCopy = nodes + guard let node = localNodesCopy.next() else { + // Node not present, return nil. + return nil + } + + let expectedNodeID = ASN1.ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass) + assert(expectedNodeID.constructed) + guard node.identifier == expectedNodeID else { + // Node is a mismatch, with the wrong tag. Our optional isn't present. + return nil + } + + // We have the right optional, so let's consume it. + nodes = localNodesCopy + + // We expect a single child. + guard case .constructed(let nodes) = node.content else { + // This error is an internal parser error: the tag above is always constructed. + preconditionFailure("Explicit tags are always constructed") + } + + var nodeIterator = nodes.makeIterator() + guard let child = nodeIterator.next(), nodeIterator.next() == nil else { + throw ASN1Error.invalidASN1Object + } + + return try builder(child) + } +} + +// MARK: - Optional implicitly tagged +extension ASN1 { + /// Parses an optional implicitly tagged element. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tag: The implicit tag. Defaults to the default tag for the element. + /// + /// - returns: The parsed element, if it was present, or `nil` if it was not. + @inlinable + public static func optionalImplicitlyTagged(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tag: ASN1Identifier = T.defaultIdentifier) throws -> T? { + var localNodesCopy = nodes + guard let node = localNodesCopy.next() else { + // Node not present, return nil. + return nil + } + + guard node.identifier == tag else { + // Node is a mismatch, with the wrong tag. Our optional isn't present. + return nil + } + + // We're good: pass the node on. + return try T(asn1Encoded: &nodes, withIdentifier: tag) + } +} + +// MARK: - DEFAULT +extension ASN1 { + /// Parses a value that is encoded with a DEFAULT. + /// + /// Such a value is optional, and if absent will be replaced with its default. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - identifier: The implicit tag. Defaults to the default tag for the element. + /// - defaultValue: The default value to use if there was no encoded value. + /// - builder: A closure that will be called with the node for the element, if the element is present. + /// + /// - returns: The parsed element, if it was present, or the default if it was not. + @inlinable + public static func decodeDefault(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, identifier: ASN1.ASN1Identifier, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T { + // A weird trick here: we only want to consume the next node _if_ it has the right tag. To achieve that, + // we work on a copy. + var localNodesCopy = nodes + guard let node = localNodesCopy.next() else { + // Whoops, nothing here. + return defaultValue + } + + guard node.identifier == identifier else { + // Node is a mismatch, with the wrong identifier. Our optional isn't present. + return defaultValue + } + + // We have the right optional, so let's consume it. + nodes = localNodesCopy + let parsed = try builder(node) + + // DER forbids encoding DEFAULT values at their default state. + // We can lift this in BER. + guard parsed != defaultValue else { + throw ASN1Error.invalidASN1Object + } + + return parsed + } + + /// Parses a value that is encoded with a DEFAULT. + /// + /// Such a value is optional, and if absent will be replaced with its default. This function is + /// a helper wrapper for ``decodeDefault(_:identifier:defaultValue:_:)`` that automatically invokes + /// ``ASN1Parseable/init(asn1Encoded:)-507py`` on `T`. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - identifier: The implicit tag. Defaults to the default tag for the element. + /// - defaultValue: The default value to use if there was no encoded value. + /// + /// - returns: The parsed element, if it was present, or the default if it was not. + @inlinable + public static func decodeDefault(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, identifier: ASN1.ASN1Identifier, defaultValue: T) throws -> T { + return try Self.decodeDefault(&nodes, identifier: identifier, defaultValue: defaultValue) { try T(asn1Encoded: $0) } + } + + /// Parses a value that is encoded with a DEFAULT. + /// + /// Such a value is optional, and if absent will be replaced with its default. This function is + /// a helper wrapper for ``decodeDefault(_:identifier:defaultValue:_:)`` that automatically invokes + /// ``ASN1ImplicitlyTaggable/init(asn1Encoded:withIdentifier:)-iudo`` on `T` using ``ASN1ImplicitlyTaggable/defaultIdentifier``. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - defaultValue: The default value to use if there was no encoded value. + /// + /// - returns: The parsed element, if it was present, or the default if it was not. + @inlinable + public static func decodeDefault(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, defaultValue: T) throws -> T { + return try Self.decodeDefault(&nodes, identifier: T.defaultIdentifier, defaultValue: defaultValue) + } + + /// Parses a value that is encoded with a DEFAULT and an explicit tag. + /// + /// Such a value is optional, and if absent will be replaced with its default. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tagNumber: The number of the explicit tag. + /// - tagClass: The class of the explicit tag. + /// - defaultValue: The default value to use if there was no encoded value. + /// - builder: A closure that will be called with the node for the element, if the element is present. + /// + /// - returns: The parsed element, if it was present, or the default if it was not. + @inlinable + public static func decodeDefaultExplicitlyTagged(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T { + if let result = try optionalExplicitlyTagged(&nodes, tagNumber: tagNumber, tagClass: tagClass, builder) { + guard result != defaultValue else { + // DER forbids encoding DEFAULT values at their default state. + // We can lift this in BER. + throw ASN1Error.invalidASN1Object + } + + return result + } else { + return defaultValue + } + } + + /// Parses a value that is encoded with a DEFAULT and an explicit tag. + /// + /// Such a value is optional, and if absent will be replaced with its default. This function is + /// a helper wrapper for ``decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:_:)`` that automatically invokes + /// ``ASN1Parseable/init(asn1Encoded:)-507py`` on `T`. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tagNumber: The number of the explicit tag. + /// - tagClass: The class of the explicit tag. + /// - defaultValue: The default value to use if there was no encoded value. + /// + /// - returns: The parsed element, if it was present, or the default if it was not. + @inlinable + public static func decodeDefaultExplicitlyTagged(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass, defaultValue: T) throws -> T { + return try Self.decodeDefaultExplicitlyTagged( + &nodes, tagNumber: tagNumber, tagClass: tagClass, defaultValue: defaultValue + ) { + try T(asn1Encoded: $0) + } + } +} + +// MARK: - Ordinary, explicit tagging +extension ASN1 { + /// Parses an explicitly tagged element. + /// + /// - parameters: + /// - nodes: The ``ASN1/ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tagNumber: The number of the explicit tag. + /// - tagClass: The class of the explicit tag. + /// - builder: A closure that will be called with the node for the element. + /// + /// - returns: The result of `builder`. + @inlinable + public static func explicitlyTagged(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T { + guard let node = nodes.next() else { + // Node not present, throw. + throw ASN1Error.invalidASN1Object + } + + return try self.explicitlyTagged(node, tagNumber: tagNumber, tagClass: tagClass, builder) + } + + /// Parses an explicitly tagged element. + /// + /// - parameters: + /// - node: The ``ASN1Node`` to parse this element out of. + /// - tagNumber: The number of the explicit tag. + /// - tagClass: The class of the explicit tag. + /// - builder: A closure that will be called with the node for the element. + /// + /// - returns: The result of `builder`. + @inlinable + public static func explicitlyTagged(_ node: ASN1Node, tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T { + let expectedNodeID = ASN1.ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass) + assert(expectedNodeID.constructed) + guard node.identifier == expectedNodeID else { + // Node is a mismatch, with the wrong tag. + throw ASN1Error.invalidFieldIdentifier + } + + // We expect a single child. + guard case .constructed(let nodes) = node.content else { + // This error is an internal parser error: the tag above is always constructed. + preconditionFailure("Explicit tags are always constructed") + } + + var nodeIterator = nodes.makeIterator() + guard let child = nodeIterator.next(), nodeIterator.next() == nil else { + throw ASN1Error.invalidASN1Object + } + + return try builder(child) + } +} + + +// MARK: - Parsing +extension ASN1 { + /// A parsed representation of ASN.1. + @usableFromInline + struct ASN1ParseResult { + @usableFromInline + static let _maximumNodeDepth = 50 + + @usableFromInline + var nodes: ArraySlice + + @inlinable + init(_ nodes: ArraySlice) { + self.nodes = nodes + } + + @inlinable + static func parse(_ data: ArraySlice) throws -> ASN1ParseResult { + var data = data + var nodes = [ASN1ParserNode]() + nodes.reserveCapacity(16) + + try _parseNode(from: &data, depth: 1, into: &nodes) + guard data.count == 0 else { + throw ASN1Error.invalidASN1Object + } + return ASN1ParseResult(nodes[...]) + } + + /// Parses a single ASN.1 node from the data and appends it to the buffer. This may recursively + /// call itself when there are child nodes for constructed nodes. + @inlinable + static func _parseNode(from data: inout ArraySlice, depth: Int, into nodes: inout [ASN1ParserNode]) throws { + guard depth <= ASN1.ASN1ParseResult._maximumNodeDepth else { + // We defend ourselves against stack overflow by refusing to allocate more than 50 stack frames to + // the parsing. + throw ASN1Error.invalidASN1Object + } + + let originalData = data + + guard let rawIdentifier = data.popFirst() else { + throw ASN1Error.truncatedASN1Field + } + + // Check whether the bottom 5 bits are set: if they are, this uses long-form encoding. + let identifier: ASN1Identifier + if (rawIdentifier & 0x1f) == 0x1f { + let tagClass = ASN1Identifier.TagClass(topByteInWireFormat: rawIdentifier) + let constructed = (rawIdentifier & 0x20) != 0 + + // Now we need to read a UInt from the array. + let tagNumber = try data.readUIntUsing8BitBytesASN1Discipline() + + // We need a check here: this number needs to be greater than or equal to 0x1f, or it should have been encoded as short form. + guard tagNumber >= 0x1f else { + throw ASN1Error.invalidASN1Object + } + identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass, constructed: constructed) + } else { + identifier = ASN1Identifier(shortIdentifier: rawIdentifier) + } + + guard let wideLength = try data._readASN1Length() else { + throw ASN1Error.truncatedASN1Field + } + + // UInt is sometimes too large for us! + guard let length = Int(exactly: wideLength) else { + throw ASN1Error.invalidASN1Object + } + + var subData = data.prefix(length) + data = data.dropFirst(length) + + guard subData.count == length else { + throw ASN1Error.truncatedASN1Field + } + + let encodedBytes = originalData[.. 0 { + try _parseNode(from: &subData, depth: depth + 1, into: &nodes) + } + } else { + nodes.append( + ASN1ParserNode( + identifier: identifier, + depth: depth, + encodedBytes: encodedBytes, + dataBytes: subData + ) + ) + } + } + } +} + +extension ASN1.ASN1ParseResult: Hashable { } + +extension ASN1 { + /// Parses an array of bytes as DER-encoded ASN.1 bytes. + /// + /// This function does not produce a complete decoded representation. Instead it produces a tree of ``ASN1Node`` objects, + /// each representing a single ASN.1 object. The leaves of the tree are primitive ASN.1 objects, and the intermediate nodes are + /// constructed. + /// + /// In general this function is not called by users directly. Prefer using ``ASN1Parseable/init(asn1Encoded:)-7otnm``, which encapsulates + /// the use of this function and immediately returns a strongly typed, fully-parsed object. + /// + /// - parameters: + /// - data: The DER-encoded bytes to parse. + /// - returns: The root node in the ASN.1 tree. + @inlinable + public static func parse(_ data: [UInt8]) throws -> ASN1Node { + return try parse(data[...]) + } + + /// Parses an array of bytes as DER-encoded ASN.1 bytes. + /// + /// This function does not produce a complete decoded representation. Instead it produces a tree of ``ASN1Node`` objects, + /// each representing a single ASN.1 object. The leaves of the tree are primitive ASN.1 objects, and the intermediate nodes are + /// constructed. + /// + /// In general this function is not called by users directly. Prefer using ``ASN1Parseable/init(asn1Encoded:)-9ye4i``, which encapsulates + /// the use of this function and immediately returns a strongly typed, fully-parsed object. + /// + /// - parameters: + /// - data: The DER-encoded bytes to parse. + /// - returns: The root node in the ASN.1 tree. + @inlinable + public static func parse(_ data: ArraySlice) throws -> ASN1Node { + var result = try ASN1ParseResult.parse(data) + + // There will always be at least one node if the above didn't throw, so we can safely just removeFirst here. + let firstNode = result.nodes.removeFirst() + + let rootNode: ASN1Node + if firstNode.identifier.constructed { + // We need to feed it the next set of nodes. + let nodeCollection = result.nodes.prefix { $0.depth > firstNode.depth } + result.nodes = result.nodes.dropFirst(nodeCollection.count) + rootNode = ASN1.ASN1Node( + identifier: firstNode.identifier, + content: .constructed(.init(nodes: nodeCollection, depth: firstNode.depth)), + encodedBytes: firstNode.encodedBytes + ) + } else { + rootNode = ASN1.ASN1Node( + identifier: firstNode.identifier, + content: .primitive(firstNode.dataBytes!), + encodedBytes: firstNode.encodedBytes + ) + } + + precondition(result.nodes.count == 0, "ASN1ParseResult unexpectedly allowed multiple root nodes") + + return rootNode + } +} + +// MARK: - ASN1NodeCollection +extension ASN1 { + /// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node. + /// + /// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes. + /// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them. + /// + /// This type cannot be constructed directly, and is instead provided by helper functions such as ``ASN1/sequence(of:identifier:rootNode:)``. + public struct ASN1NodeCollection { + @usableFromInline var _nodes: ArraySlice + + @usableFromInline var _depth: Int + + @inlinable + init(nodes: ArraySlice, depth: Int) { + self._nodes = nodes + self._depth = depth + + precondition(self._nodes.allSatisfy({ $0.depth > depth })) + if let firstDepth = self._nodes.first?.depth { + precondition(firstDepth == depth + 1) + } + } + } +} + +extension ASN1.ASN1NodeCollection: Hashable { } + +extension ASN1.ASN1NodeCollection: Sendable { } + +extension ASN1.ASN1NodeCollection: Sequence { + /// An iterator of ASN.1 nodes that are children of a specific constructed node. + public struct Iterator: IteratorProtocol { + @usableFromInline + var _nodes: ArraySlice + + @usableFromInline + var _depth: Int + + @inlinable + init(nodes: ArraySlice, depth: Int) { + self._nodes = nodes + self._depth = depth + } + + @inlinable + public mutating func next() -> ASN1.ASN1Node? { + guard let nextNode = self._nodes.popFirst() else { + return nil + } + + assert(nextNode.depth == self._depth + 1) + if nextNode.identifier.constructed { + // We need to feed it the next set of nodes. + let nodeCollection = self._nodes.prefix { $0.depth > nextNode.depth } + self._nodes = self._nodes.dropFirst(nodeCollection.count) + return ASN1.ASN1Node( + identifier: nextNode.identifier, + content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)), + encodedBytes: nextNode.encodedBytes + ) + } else { + // There must be data bytes here, even if they're empty. + return ASN1.ASN1Node( + identifier: nextNode.identifier, + content: .primitive(nextNode.dataBytes!), + encodedBytes: nextNode.encodedBytes + ) + } + } + } + + @inlinable + public func makeIterator() -> Iterator { + return Iterator(nodes: self._nodes, depth: self._depth) + } +} + +// MARK: - ASN1Node +extension ASN1 { + /// An ``ASN1/ASN1Node`` is a single entry in the ASN.1 representation of a data structure. + /// + /// Conceptually, an ASN.1 data structure is rooted in a single node, which may itself contain zero or more + /// other nodes. ASN.1 nodes are either "constructed", meaning they contain other nodes, or "primitive", meaning they + /// store a base data type of some kind. + /// + /// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed + /// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects. + public struct ASN1Node: Hashable, Sendable { + /// The tag for this ASN.1 node. + public var identifier: ASN1Identifier + + /// The content of this ASN.1 node. + public var content: Content + + /// The encoded bytes for this node. + /// + /// This is principally intended for diagnostic purposes. + public var encodedBytes: ArraySlice + + @inlinable + internal init( + identifier: ASN1.ASN1Identifier, + content: ASN1.ASN1Node.Content, + encodedBytes: ArraySlice + ) { + self.identifier = identifier + self.content = content + self.encodedBytes = encodedBytes + } + } +} + +// MARK: - ASN1Node.Content +extension ASN1.ASN1Node { + /// The content of a single ``ASN1/ASN1Node``. + public enum Content: Hashable, Sendable { + /// This ``ASN1/ASN1Node`` is constructed, and has a number of child nodes. + case constructed(ASN1.ASN1NodeCollection) + + /// This ``ASN1/ASN1Node`` is primitive, and is made up only of a collection of bytes. + case primitive(ArraySlice) + } +} + +// MARK: - Serializing +extension ASN1 { + /// An object that can serialize ASN.1 bytes. + /// + /// ``Serializer`` is a copy-on-write value type. + public struct Serializer: Sendable { + @usableFromInline + var _serializedBytes: [UInt8] + + /// The bytes that have been serialized by this serializer. + @inlinable + public var serializedBytes: [UInt8] { + self._serializedBytes + } + + /// Construct a new serializer. + @inlinable + public init() { + // We allocate a 1kB array because that should cover us most of the time. + self._serializedBytes = [] + self._serializedBytes.reserveCapacity(1024) + } + + /// Appends a single, non-constructed node to the content. + /// + /// This is a low-level operation that can be used to implement primitive ASN.1 types. + /// + /// - parameters: + /// - identifier: The tag for this ASN.1 node + /// - contentWriter: A callback that will be invoked that allows users to write their bytes into the output stream. + @inlinable + public mutating func appendPrimitiveNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout [UInt8]) throws -> Void) rethrows { + assert(identifier.primitive) + try self._appendNode(identifier: identifier) { try contentWriter(&$0._serializedBytes) } + } + + /// Appends a single constructed node to the content. + /// + /// This is an operation that can be used to implement constructed ASN.1 types. Most ASN.1 types are sequences and rely on using this function + /// to append their SEQUENCE node. + /// + /// - parameters: + /// - identifier: The tag for this ASN.1 node + /// - contentWriter: A callback that will be invoked that allows users to write the objects contained within this constructed node. + @inlinable + public mutating func appendConstructedNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows { + assert(identifier.constructed) + try self._appendNode(identifier: identifier, contentWriter) + } + + /// Serializes a single node to the end of the byte stream. + /// + /// - parameters: + /// node: The node to be serialized. + @inlinable + public mutating func serialize(_ node: T) throws { + try node.serialize(into: &self) + } + + /// Serializes a single node to the end of the byte stream with an explicit ASN.1 tag. + /// + /// This is a wrapper for ``ASN1/Serializer/serialize(_:explicitlyTaggedWithIdentifier:)`` that builds the ASN.1 tag + /// automatically. + /// + /// - parameters: + /// node: The node to be serialized. + /// tagNumber: The number of the explicit tag. + /// tagClass: The number of the explicit tag. + @inlinable + public mutating func serialize(_ node: T, explicitlyTaggedWithTagNumber tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass) throws { + let identifier = ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass) + return try self.serialize(node, explicitlyTaggedWithIdentifier: identifier) + } + + /// Serializes a single node to the end of the byte stream with an explicit ASN.1 tag. + /// + /// - parameters: + /// node: The node to be serialized. + /// identifier: The explicit ASN.1 tag to apply. + @inlinable + public mutating func serialize(_ node: T, explicitlyTaggedWithIdentifier identifier: ASN1.ASN1Identifier) throws { + try self.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(node) + } + } + + /// Serializes a single optional node to the end of the byte stream with an implicit ASN.1 tag. + /// + /// If the node is `nil`, nothing is appended to the stream. + /// + /// The node is appended with its default tag. + /// + /// - parameters: + /// node: The node to be serialized. + @inlinable + public mutating func serializeOptionalImplicitlyTagged(_ node: T?) throws { + if let node = node { + try self.serialize(node) + } + } + + /// Serializes a single optional node to the end of the byte stream with an implicit ASN.1 tag. + /// + /// If the node is `nil`, nothing is appended to the stream. + /// + /// - parameters: + /// node: The node to be serialized. + /// identifier: The implicit ASN.1 tag to apply. + @inlinable + public mutating func serializeOptionalImplicitlyTagged(_ node: T?, withIdentifier identifier: ASN1.ASN1Identifier) throws { + if let node = node { + try node.serialize(into: &self, withIdentifier: identifier) + } + } + + /// Serializes an explicit ASN.1 tag using a custom builder to store the elements of the explicitly tagged node. + /// + /// This is a helper version of ``ASN1/Serializer/serialize(_:explicitlyTaggedWithTagNumber:tagClass:)`` that allows users to avoid defining an object for the + /// explicit node. + /// + /// - parameters: + /// tagNumber: The number of the explicit tag. + /// tagClass: The number of the explicit tag. + /// block: The block that will be invoked to encode the contents of the explicit tag. + @inlinable + public mutating func serialize(explicitlyTaggedWithTagNumber tagNumber: UInt, tagClass: ASN1.ASN1Identifier.TagClass, _ block: (inout Serializer) throws -> Void) rethrows { + let identifier = ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass) + try self.appendConstructedNode(identifier: identifier) { coder in + try block(&coder) + } + } + + /// Serializes a SEQUENCE OF ASN.1 nodes. + /// + /// - parameters: + /// - elements: The members of the ASN.1 SEQUENCE OF. + /// - identifier: The identifier to use for the SEQUENCE OF node. Defaults to ``ASN1/ASN1Identifier/sequence``. + @inlinable + public mutating func serializeSequenceOf(_ elements: Elements, identifier: ASN1.ASN1Identifier = .sequence) throws where Elements.Element: ASN1Serializable { + try self.appendConstructedNode(identifier: identifier) { coder in + for element in elements { + try coder.serialize(element) + } + } + } + + /// Serialize a parsed ASN.1 node directly. + /// + /// This is an extremely low-level helper function that can be used to re-serialize a parsed object when properly deserializing it was not + /// practical. + /// + /// - parameters: + /// - node: The parsed node to serialize. + @inlinable + public mutating func serialize(_ node: ASN1.ASN1Node) { + let identifier = node.identifier + self._appendNode(identifier: identifier) { coder in + switch node.content { + case .constructed(let nodes): + for node in nodes { + coder.serialize(node) + } + case .primitive(let baseData): + coder._serializedBytes.append(contentsOf: baseData) + } + } + } + + // This is the base logical function that all other append methods are built on. This one has most of the logic, and doesn't + // police what we expect to happen in the content writer. + @inlinable + mutating func _appendNode(identifier: ASN1.ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows { + // This is a tricky game to play. We want to write the identifier and the length, but we don't know what the + // length is here. To get around that, we _assume_ the length will be one byte, and let the writer write their content. + // If it turns out to have been longer, we recalculate how many bytes we need and shuffle them in the buffer, + // before updating the length. Most of the time we'll be right: occasionally we'll be wrong and have to shuffle. + self._serializedBytes.writeIdentifier(identifier) + + // Write a zero for the length. + self._serializedBytes.append(0) + + // Save the indices and write. + let originalEndIndex = self._serializedBytes.endIndex + let lengthIndex = self._serializedBytes.index(before: originalEndIndex) + + try contentWriter(&self) + + let contentLength = self._serializedBytes.distance(from: originalEndIndex, to: self._serializedBytes.endIndex) + let lengthBytesNeeded = contentLength._bytesNeededToEncode + if lengthBytesNeeded == 1 { + // We can just set this at the top, and we're done! + assert(contentLength <= 0x7F) + self._serializedBytes[lengthIndex] = UInt8(contentLength) + return + } + + // Whoops, we need more than one byte to represent the length. That's annoying! + // To sort this out we want to "move" the memory to the right. + self._serializedBytes._moveRange(offset: lengthBytesNeeded - 1, range: originalEndIndex..> (shift * 8))) + } + + assert(writeIndex == self._serializedBytes.index(lengthIndex, offsetBy: lengthBytesNeeded - 1)) + } + } +} + +// MARK: - Helpers + +/// Defines a type that can be parsed from a DER-encoded form. +/// +/// Users implementing this type are expected to write the ASN.1 decoding code themselves. This approach is discussed in +/// depth in . When working with a type that may be implicitly tagged (which is most ASN.1 types), +/// users are recommended to implement ``ASN1ImplicitlyTaggable`` instead. +public protocol ASN1Parseable { + /// Initialize this object from a serialized DER representation. + /// + /// This function is invoked by the parser with the root node for the ASN.1 object. Implementers are + /// expected to initialize themselves if possible, or to throw if they cannot. + /// + /// - parameters: + /// - asn1Encoded: The ASN.1 node representing this object. + init(asn1Encoded: ASN1.ASN1Node) throws +} + +extension ASN1Parseable { + /// Initialize this object as one element of a constructed ASN.1 object. + /// + /// This is a helper function for parsing constructed ASN.1 objects. It delegates all its functionality + /// to ``ASN1Parseable/init(asn1Encoded:)-507py``. + /// + /// - parameters: + /// - asn1Encoded: The sequence of nodes that make up this object's parent. The first node in this collection + /// will be used to construct this object. + @inlinable + public init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws { + guard let node = sequenceNodeIterator.next() else { + throw ASN1Error.invalidASN1Object + } + + self = try .init(asn1Encoded: node) + } + + /// Initialize this object from a serialized DER representation. + /// + /// - parameters: + /// - asn1Encoded: The DER-encoded bytes representing this object. + @inlinable + public init(asn1Encoded: [UInt8]) throws { + self = try .init(asn1Encoded: ASN1.parse(asn1Encoded)) + } + + /// Initialize this object from a serialized DER representation. + /// + /// - parameters: + /// - asn1Encoded: The DER-encoded bytes representing this object. + @inlinable + public init(asn1Encoded: ArraySlice) throws { + self = try .init(asn1Encoded: ASN1.parse(asn1Encoded)) + } +} + +/// Defines a type that can be serialized in DER-encoded form. +/// +/// Users implementing this type are expected to write the ASN.1 serialization code themselves. This approach is discussed in +/// depth in . When working with a type that may be implicitly tagged (which is most ASN.1 types), +/// users are recommended to implement ``ASN1ImplicitlyTaggable`` instead. +public protocol ASN1Serializable { + /// Serialize this object into DER-encoded ASN.1 form. + /// + /// - parameters: + /// - coder: A serializer to be used to encode the object. + func serialize(into coder: inout ASN1.Serializer) throws +} + +/// An ASN.1 node that can tolerate having an implicit tag. +/// +/// Implicit tags prevent the decoder from being able to work out what the actual type of the object +/// is, as they replace the tags. This means some objects cannot be implicitly tagged. In particular, +/// CHOICE elements without explicit tags cannot be implicitly tagged. +/// +/// Objects that _can_ be implicitly tagged should prefer to implement this protocol than +/// ``ASN1Serializable`` and ``ASN1Parseable``. +public protocol ASN1ImplicitlyTaggable: ASN1Parseable, ASN1Serializable { + /// The tag that the first node will use "by default" if the grammar omits + /// any more specific tag definition. + static var defaultIdentifier: ASN1.ASN1Identifier { get } + + /// Initialize this object from a serialized DER representation. + /// + /// This function is invoked by the parser with the root node for the ASN.1 object. Implementers are + /// expected to initialize themselves if possible, or to throw if they cannot. The object is expected + /// to use the identifier `identifier`. + /// + /// - parameters: + /// - asn1Encoded: The ASN.1 node representing this object. + /// - identifier: The ASN.1 identifier that `asn1Encoded` is expected to have. + init(asn1Encoded: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws + + /// Serialize this object into DER-encoded ASN.1 form. + /// + /// - parameters: + /// - coder: A serializer to be used to encode the object. + /// - identifier: The ASN.1 identifier that this object should use to represent itself. + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws +} + +extension ASN1ImplicitlyTaggable { + /// Initialize this object as one element of a constructed ASN.1 object. + /// + /// This is a helper function for parsing constructed ASN.1 objects. It delegates all its functionality + /// to ``ASN1ImplicitlyTaggable/init(asn1Encoded:withIdentifier:)-iudo``. + /// + /// - parameters: + /// - asn1Encoded: The sequence of nodes that make up this object's parent. The first node in this collection + /// will be used to construct this object. + /// - identifier: The ASN.1 identifier that `asn1Encoded` is expected to have. + @inlinable + public init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator, + withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws { + guard let node = sequenceNodeIterator.next() else { + throw ASN1Error.invalidASN1Object + } + + self = try .init(asn1Encoded: node, withIdentifier: identifier) + } + + /// Initialize this object from a serialized DER representation. + /// + /// - parameters: + /// - asn1Encoded: The DER-encoded bytes representing this object. + /// - identifier: The ASN.1 identifier that `asn1Encoded` is expected to have. + @inlinable + public init(asn1Encoded: [UInt8], withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws { + self = try .init(asn1Encoded: ASN1.parse(asn1Encoded), withIdentifier: identifier) + } + + /// Initialize this object from a serialized DER representation. + /// + /// - parameters: + /// - asn1Encoded: The DER-encoded bytes representing this object. + /// - identifier: The ASN.1 identifier that `asn1Encoded` is expected to have. + @inlinable + public init(asn1Encoded: ArraySlice, withIdentifier identifier: ASN1.ASN1Identifier = Self.defaultIdentifier) throws { + self = try .init(asn1Encoded: ASN1.parse(asn1Encoded), withIdentifier: identifier) + } + + @inlinable + public init(asn1Encoded: ASN1.ASN1Node) throws { + try self.init(asn1Encoded: asn1Encoded, withIdentifier: Self.defaultIdentifier) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer) throws { + try self.serialize(into: &coder, withIdentifier: Self.defaultIdentifier) + } +} + +extension ArraySlice where Element == UInt8 { + @inlinable + mutating func _readASN1Length() throws -> UInt? { + guard let firstByte = self.popFirst() else { + return nil + } + + switch firstByte { + case 0x80: + // Indefinite form. Unsupported. + throw ASN1Error.unsupportedFieldLength + case let val where val & 0x80 == 0x80: + // Top bit is set, this is the long form. The remaining 7 bits of this octet + // determine how long the length field is. + let fieldLength = Int(val & 0x7F) + guard self.count >= fieldLength else { + return nil + } + + // We need to read the length bytes + let lengthBytes = self.prefix(fieldLength) + self = self.dropFirst(fieldLength) + let length = try UInt(bigEndianBytes: lengthBytes) + + // DER requires that we enforce that the length field was encoded in the minimum number of octets necessary. + let requiredBits = UInt.bitWidth - length.leadingZeroBitCount + switch requiredBits { + case 0...7: + // For 0 to 7 bits, the long form is unnacceptable and we require the short. + throw ASN1Error.unsupportedFieldLength + case 8...: + // For 8 or more bits, fieldLength should be the minimum required. + let requiredBytes = (requiredBits + 7) / 8 + if fieldLength > requiredBytes { + throw ASN1Error.unsupportedFieldLength + } + default: + // This is not reachable, but we'll error anyway. + throw ASN1Error.unsupportedFieldLength + } + + return length + case let val: + // Short form, the length is only one 7-bit integer. + return UInt(val) + } + } +} + +extension FixedWidthInteger { + @inlinable + internal init(bigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 { + guard bytes.count <= (Self.bitWidth / 8) else { + throw ASN1Error.invalidASN1Object + } + + self = 0 + let shiftSizes = stride(from: 0, to: bytes.count * 8, by: 8).reversed() + + var index = bytes.startIndex + for shift in shiftSizes { + self |= Self(truncatingIfNeeded: bytes[index]) << shift + bytes.formIndex(after: &index) + } + } +} + +extension Array where Element == UInt8 { + @inlinable + mutating func _moveRange(offset: Int, range: Range) { + // We only bothered to implement this for positive offsets for now, the algorithm + // generalises. + precondition(offset > 0) + + let distanceFromEndOfRangeToEndOfSelf = self.distance(from: range.endIndex, to: self.endIndex) + if distanceFromEndOfRangeToEndOfSelf < offset { + // We begin by writing some zeroes out to the size we need. + for _ in 0..<(offset - distanceFromEndOfRangeToEndOfSelf) { + self.append(0) + } + } + + // Now we walk the range backwards, moving the elements. + for index in range.reversed() { + self[index + offset] = self[index] + } + } +} + +extension Int { + @inlinable + var _bytesNeededToEncode: Int { + // ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should: + // that requires only one byte. Otherwise, we need multiple bytes: work out how many, + // plus one for the length of the length bytes. + if self <= 0x7F { + return 1 + } else { + // We need to work out how many bytes we need. There are many fancy bit-twiddling + // ways of doing this, but honestly we don't do this enough to need them, so we'll + // do it the easy way. This math is done on UInt because it makes the shift semantics clean. + // We save a branch here because we can never overflow this addition. + return UInt(self).neededBytes &+ 1 + } + } +} + +extension FixedWidthInteger { + // Bytes needed to store a given integer. + @inlinable + internal var neededBytes: Int { + let neededBits = self.bitWidth - self.leadingZeroBitCount + return (neededBits + 7) / 8 + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Any.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Any.swift new file mode 100644 index 0000000..09594c4 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Any.swift @@ -0,0 +1,95 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// An ASN1 ANY represents...well, anything. + /// + /// In this case we store the ASN.1 ANY as a serialized representation. This is a bit limiting, + /// but it's the only safe way to manage this data, as we cannot arbitrarily parse it. + /// + /// The only things users can do with ASN.1 ANYs is to try to decode them as something else, + /// to create them from something else, or to serialize them. + public struct ASN1Any: ASN1Parseable, ASN1Serializable, Hashable, Sendable { + @usableFromInline + var _serializedBytes: ArraySlice + + /// Create an ``ASN1/ASN1Any`` from a serializable ASN1 type. + /// + /// - parameters: + /// erasing: The type to be represented as an ASN1 ANY. + @inlinable + public init(erasing: ASN1Type) throws { + var serializer = ASN1.Serializer() + try erasing.serialize(into: &serializer) + self._serializedBytes = ArraySlice(serializer._serializedBytes) + } + + /// Create an ``ASN1/ASN1Any`` from a serializable implicitly taggable ASN1 type. + /// + /// - parameters: + /// erasing: The type to be represented as an ASN1 ANY. + /// identifier: The tag to use with this node. + @inlinable + public init(erasing: ASN1Type, withIdentifier identifier: ASN1.ASN1Identifier) throws { + var serializer = ASN1.Serializer() + try erasing.serialize(into: &serializer, withIdentifier: identifier) + self._serializedBytes = ArraySlice(serializer._serializedBytes) + } + + @inlinable + public init(asn1Encoded rootNode: ASN1.ASN1Node) { + // This is a bit sad: we just re-serialize this data. In an ideal world + // we'd update the parse representation so that all nodes can point at their + // complete backing storage, but for now this is better. + var serializer = ASN1.Serializer() + serializer.serialize(rootNode) + self._serializedBytes = ArraySlice(serializer._serializedBytes) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer) throws { + // Dangerous to just reach in there like this, but it's the right way to serialize this. + coder._serializedBytes.append(contentsOf: self._serializedBytes) + } + } +} + +extension ASN1Parseable { + /// Construct this node from an ASN.1 ANY object. + /// + /// This operation works by asking the type to decode itself from the serialized representation + /// of this ASN.1 ANY node. + /// + /// - parameters: + /// asn1Any: The ASN.1 ANY object to reinterpret. + @inlinable + public init(asn1Any: ASN1.ASN1Any) throws { + try self.init(asn1Encoded: asn1Any._serializedBytes) + } +} + +extension ASN1ImplicitlyTaggable { + /// Construct this node from an ASN.1 ANY object. + /// + /// This operation works by asking the type to decode itself from the serialized representation + /// of this ASN.1 ANY node. + /// + /// - parameters: + /// asn1Any: The ASN.1 ANY object to reinterpret. + /// identifier: The tag to use with this node. + @inlinable + public init(asn1Any: ASN1.ASN1Any, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try self.init(asn1Encoded: asn1Any._serializedBytes, withIdentifier: identifier) + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1BitString.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1BitString.swift new file mode 100644 index 0000000..fb5ad91 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1BitString.swift @@ -0,0 +1,125 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// A bitstring is a representation of a sequence of bits. + /// + /// In ASN.1, bitstrings serve two different use-cases. The first is as arbitrary-length sequences of bits. + /// These are typically used to encode cryptographic keys, such as RSA keys. The second is as a form of bitset. + /// + /// In the case of a bitset, DER has additonal requirements as to how to represent the object. This type does not + /// enforce those additional rules: users are expected to implement that validation themselves. + public struct ASN1BitString: ASN1ImplicitlyTaggable { + /// The default identifier for this type. + /// + /// Evaluates to ``ASN1/ASN1Identifier/primitiveBitString``. + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveBitString + } + + /// The raw bytes that make up this bitstring. + /// + /// The last ``paddingBits`` number of bits in the final octet of this byte sequence must be zero. + public var bytes: ArraySlice { + didSet { + try! self._validate() + } + } + + /// The number of bits in the last octet of ``bytes`` that are not part of this bitstring. + /// + /// The excluded bits are the least significant bits. + /// + /// If ``bytes`` is empty then this value must be 0. + public var paddingBits: Int { + didSet { + precondition((0..<8).contains(self.paddingBits)) + try! self._validate() + } + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.unexpectedFieldType + } + + guard case .primitive(let content) = node.content else { + preconditionFailure("ASN.1 parser generated primitive node with constructed content") + } + + // The initial octet explains how many of the bits in the _final_ octet are not part of the bitstring. + guard let paddingBits = content.first, (0..<8).contains(paddingBits) else { + throw ASN1Error.invalidASN1Object + } + + self.paddingBits = Int(paddingBits) + self.bytes = content.dropFirst() + + try self._validate() + } + + /// Construct an ``ASN1/ASN1BitString`` from raw components. + /// + /// - parameters: + /// - bytes: The bytes to represent this bitstring + /// - paddingBits: The number of bits in the trailing byte that are not actually part of this bitstring. + @inlinable + public init(bytes: ArraySlice, paddingBits: Int = 0) { + self.bytes = bytes + self.paddingBits = paddingBits + try! self._validate() + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + bytes.append(UInt8(truncatingIfNeeded: self.paddingBits)) + bytes.append(contentsOf: self.bytes) + } + } + + @inlinable + internal func _validate() throws { + guard let finalByte = self.bytes.last else { + if self.paddingBits != 0 { + // If there are no bytes, there must be no padding bits. + throw ASN1Error.invalidASN1Object + } + + return + } + + // Oooh, bit twiddling. + // + // All joking aside, this sets the bottom `self.paddingBits` to 1. + let mask = ~(UInt8.max << self.paddingBits) + if (finalByte & mask) != 0 { + throw ASN1Error.invalidASN1Object + } + } + } +} + +extension ASN1.ASN1BitString: Hashable { } + +extension ASN1.ASN1BitString: Sendable { } + +extension ASN1.ASN1BitString { + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Boolean.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Boolean.swift new file mode 100644 index 0000000..5a4ad75 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Boolean.swift @@ -0,0 +1,54 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension Bool: ASN1ImplicitlyTaggable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .boolean + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.invalidASN1Object + } + + guard case .primitive(let bytes) = node.content, bytes.count == 1 else { + throw ASN1Error.invalidASN1Object + } + + switch bytes[bytes.startIndex] { + case 0: + // Boolean false + self = false + case 0xff: + // Boolean true in DER + self = true + default: + // If we come to support BER then these values are all "true" as well. + throw ASN1Error.invalidASN1Object + } + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + if self { + bytes.append(0xff) + } else { + bytes.append(0) + } + } + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Identifier.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Identifier.swift new file mode 100644 index 0000000..9d94b08 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Identifier.swift @@ -0,0 +1,231 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// An ``ASN1/ASN1Identifier`` is a representation of the abstract notion of an ASN.1 identifier. + public struct ASN1Identifier { + /// The base tag. + public var tagNumber: UInt + + /// The class of the tag. + public var tagClass: TagClass + + /// Whether this tag represents a primitive object. + public var primitive: Bool + + /// Whether this tag represents a constructed object. + @inlinable + public var constructed: Bool { + get { + return !self.primitive + } + set { + self.primitive = !newValue + } + } + + @inlinable + var _shortForm: UInt8? { + // An ASN.1 identifier can be encoded in short form iff the tag number is strictly + // less than 0x1f. + guard self.tagNumber < 0x1f else { return nil } + + var baseNumber = UInt8(truncatingIfNeeded: self.tagNumber) + if self.constructed { + baseNumber |= 0x20 + } + baseNumber |= self.tagClass._topByteFlags + return baseNumber + } + + /// The class of an ASN.1 tag. + public enum TagClass: Hashable, Sendable { + case universal + case application + case contextSpecific + case `private` + + @inlinable + init(topByteInWireFormat topByte: UInt8) { + switch topByte >> 6 { + case 0x00: + self = .universal + case 0x01: + self = .application + case 0x02: + self = .contextSpecific + case 0x03: + self = .private + default: + fatalError("Unreachable") + } + } + + @inlinable + var _topByteFlags: UInt8 { + switch self { + case .universal: + return 0x00 + case .application: + return 0x01 << 6 + case .contextSpecific: + return 0x02 << 6 + case .private: + return 0x03 << 6 + } + } + } + + @inlinable + init(shortIdentifier: UInt8) { + precondition(shortIdentifier & 0x1F != 0x1F) + self.tagClass = TagClass(topByteInWireFormat: shortIdentifier) + self.primitive = (shortIdentifier & 0x20 == 0) + self.tagNumber = UInt(shortIdentifier & 0x1f) + } + + /// Produces a tag suitable for use as an explicit tag from components. + /// + /// This is equivalent to ``init(tagWithNumber:tagClass:constructed:)``, but sets + /// `constructed` to `true` in all cases. + /// + /// - parameters: + /// - number: The tag number. + /// - tagClass: The class of the ASN.1 tag. + @inlinable + public init(explicitTagWithNumber number: UInt, tagClass: TagClass) { + self.tagClass = tagClass + self.tagNumber = number + + // Explicit tags are always constructed + self.primitive = false + } + + /// Produces a tag from components. + /// + /// This is equivalent to ``init(tagWithNumber:tagClass:constructed:)``, but sets + /// `constructed` to `true` in all cases. + /// + /// - parameters: + /// - number: The tag number. + /// - tagClass: The class of the ASN.1 tag. + /// - constructed: Whether this is a constructed tag. + @inlinable + public init(tagWithNumber number: UInt, tagClass: TagClass, constructed: Bool) { + self.tagNumber = number + self.tagClass = tagClass + self.primitive = !constructed + } + } +} + +extension ASN1.ASN1Identifier { + /// This tag represents an OBJECT IDENTIFIER. + public static let objectIdentifier = ASN1.ASN1Identifier(shortIdentifier: 0x06) + + /// This tag represents a BITSTRING. + public static let primitiveBitString = ASN1.ASN1Identifier(shortIdentifier: 0x03) + + /// This tag represents an OCTET STRING. + public static let primitiveOctetString = ASN1.ASN1Identifier(shortIdentifier: 0x04) + + /// This tag represents an INTEGER. + public static let integer = ASN1.ASN1Identifier(shortIdentifier: 0x02) + + /// This tag represents a SEQUENCE or SEQUENCE OF. + public static let sequence = ASN1.ASN1Identifier(shortIdentifier: 0x30) + + /// This tag represents a SET or SET OF. + public static let set = ASN1.ASN1Identifier(shortIdentifier: 0x31) + + /// This tag represents an ASN.1 NULL. + public static let null = ASN1.ASN1Identifier(shortIdentifier: 0x05) + + /// This tag represents a BOOLEAN. + public static let boolean = ASN1.ASN1Identifier(shortIdentifier: 0x01) + + /// This tag represents an ENUMERATED. + public static let enumerated = ASN1.ASN1Identifier(shortIdentifier: 0x0a) + + /// This tag represents a UTF8STRING. + public static let primitiveUTF8String = ASN1.ASN1Identifier(shortIdentifier: 0x0c) + + /// This tag represents a NUMERICSTRING. + public static let primitiveNumericString = ASN1.ASN1Identifier(shortIdentifier: 0x12) + + /// This tag represents a PRINTABLESTRING. + public static let primitivePrintableString = ASN1.ASN1Identifier(shortIdentifier: 0x13) + + /// This tag represents a TELETEXSTRING. + public static let primitiveTeletexString = ASN1.ASN1Identifier(shortIdentifier: 0x14) + + /// This tag represents a VIDEOTEXSTRING. + public static let primitiveVideotexString = ASN1.ASN1Identifier(shortIdentifier: 0x15) + + /// This tag represents an IA5STRING. + public static let primitiveIA5String = ASN1.ASN1Identifier(shortIdentifier: 0x16) + + /// This tag represents a GRAPHICSTRING. + public static let primitiveGraphicString = ASN1.ASN1Identifier(shortIdentifier: 0x19) + + /// This tag represents a VISIBLESTRING. + public static let primitiveVisibleString = ASN1.ASN1Identifier(shortIdentifier: 0x1a) + + /// This tag represents a GENERALSTRING. + public static let primitiveGeneralString = ASN1.ASN1Identifier(shortIdentifier: 0x1b) + + /// This tag represents a UNIVERSALSTRING. + public static let primitiveUniversalString = ASN1.ASN1Identifier(shortIdentifier: 0x1c) + + /// This tag represents a BMPSTRING. + public static let primitiveBMPString = ASN1.ASN1Identifier(shortIdentifier: 0x1e) + + /// This tag represents a GENERALIZEDTIME. + public static let generalizedTime = ASN1.ASN1Identifier(shortIdentifier: 0x18) + + /// This tag represents a UTCTIME. + public static let utcTime = ASN1.ASN1Identifier(shortIdentifier: 0x17) +} + +extension ASN1.ASN1Identifier: Hashable { } + +extension ASN1.ASN1Identifier: Sendable { } + +extension ASN1.ASN1Identifier: CustomStringConvertible { + @inlinable + public var description: String { + return "ASN1Identifier(tagNumber: \(self.tagNumber), tagClass: \(self.tagClass), primitive: \(self.primitive))" + } +} + +extension Array where Element == UInt8 { + @inlinable + mutating func writeIdentifier(_ identifier: ASN1.ASN1Identifier) { + if let shortForm = identifier._shortForm { + self.append(shortForm) + } else { + // Long-form encoded. The top byte is 0x1f plus the various flags. + var topByte = UInt8(0x1f) + if identifier.constructed { + topByte |= 0x20 + } + topByte |= identifier.tagClass._topByteFlags + self.append(topByte) + + // Then we encode this in base128, just like an OID subidentifier. + // TODO: Adjust the ASN1Identifier to use UInt for its storage. + self.writeUsing7BitBytesASN1Discipline(unsignedInteger: UInt(identifier.tagNumber)) + } + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Integer.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Integer.swift new file mode 100644 index 0000000..5635194 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Integer.swift @@ -0,0 +1,301 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +/// A protocol that represents any internal object that can present itself as a INTEGER, or be parsed from +/// a INTEGER. +/// +/// This protocol exists to allow users to handle the possibility of decoding integers that cannot fit into +/// UInt64 or Int64. While both of those types conform by default, users can conform their preferred +/// arbitrary-width integer type as well, or use `ArraySlice` to store the raw bytes of the +/// integer directly. +public protocol ASN1IntegerRepresentable: ASN1ImplicitlyTaggable { + associatedtype IntegerBytes: RandomAccessCollection where IntegerBytes.Element == UInt8 + + /// Whether this type can represent signed integers. + /// + /// If this is set to false, the serializer and parser will automatically handle padding + /// with leading zero bytes as needed. + static var isSigned: Bool { get } + + /// Construct the integer value from the integer bytes. These will be big-endian, and encoded + /// according to DER requirements. + init(asn1IntegerBytes: ArraySlice) throws + + /// Provide the big-endian bytes corresponding to this integer. + func withBigEndianIntegerBytes(_ body: (IntegerBytes) throws -> ReturnType) rethrows -> ReturnType +} + +extension ASN1IntegerRepresentable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .integer + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.unexpectedFieldType + } + + guard case .primitive(var dataBytes) = node.content else { + preconditionFailure("ASN.1 parser generated primitive node with constructed content") + } + + // Zero bytes of integer is not an acceptable encoding. + guard dataBytes.count > 0 else { + throw ASN1Error.invalidASN1IntegerEncoding + } + + // 8.3.2 If the contents octets of an integer value encoding consist of more than one octet, then the bits of the first octet and bit 8 of the second octet: + // + // a) shall not all be ones; and + // b) shall not all be zero. + // + // NOTE – These rules ensure that an integer value is always encoded in the smallest possible number of octets. + if let first = dataBytes.first, let second = dataBytes.dropFirst().first { + if (first == 0xFF) && second._topBitSet || + (first == 0x00) && !second._topBitSet { + throw ASN1Error.invalidASN1IntegerEncoding + } + } + + // If the type we're trying to decode is unsigned, and the top byte is zero, we should strip it. + // If the top bit is set, however, this is an invalid conversion: the number needs to be positive! + if !Self.isSigned, let first = dataBytes.first { + if first == 0x00 { + dataBytes = dataBytes.dropFirst() + } else if first & 0x80 == 0x80 { + throw ASN1Error.invalidASN1IntegerEncoding + } + } + + self = try Self(asn1IntegerBytes: dataBytes) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + self.withBigEndianIntegerBytes { integerBytes in + // If the number of bytes is 0, we're encoding a zero. That actually _does_ require one byte. + if integerBytes.count == 0 { + bytes.append(0) + return + } + + // If self is unsigned and the first byte has the top bit set, we need to prepend a 0 byte. + if !Self.isSigned, let topByte = integerBytes.first, topByte._topBitSet { + bytes.append(0) + bytes.append(contentsOf: integerBytes) + } else { + // Either self is signed, or the top bit isn't set. Either way, trim to make sure the representation is minimal. + bytes.append(contentsOf: integerBytes._trimLeadingExcessBytes()) + } + } + } + } +} + +// MARK: - Auto-conformance for FixedWidthInteger with fixed width magnitude. +extension ASN1IntegerRepresentable where Self: FixedWidthInteger { + @inlinable + public init(asn1IntegerBytes bytes: ArraySlice) throws { + // Defer to the FixedWidthInteger constructor. + // There's a wrinkle here: if this is a signed integer, and the top bit of the data bytes was set, + // then we need to 1-extend the bytes. This is because ASN.1 tries to delete redundant bytes that + // are all 1. + self = try Self(bigEndianBytes: bytes) + + if Self.isSigned, let first = bytes.first, first._topBitSet { + for shift in stride(from: self.bitWidth - self.leadingZeroBitCount, to: self.bitWidth, by: 8) { + self |= 0xFF << shift + } + } + } + + @inlinable + public func withBigEndianIntegerBytes(_ body: (IntegerBytesCollection) throws -> ReturnType) rethrows -> ReturnType { + return try body(IntegerBytesCollection(self)) + } +} + +/// A big-endian `Collection` of bytes representing a fixed width integer. +public struct IntegerBytesCollection { + @usableFromInline var integer: Integer + + /// Construct an ``IntegerBytesCollection`` representing the bytes of this integer. + @inlinable + public init(_ integer: Integer) { + self.integer = integer + } +} + +extension IntegerBytesCollection: Hashable { } + +extension IntegerBytesCollection: Sendable { } + +extension IntegerBytesCollection: RandomAccessCollection { + public struct Index { + @usableFromInline + var _byteNumber: Int + + @inlinable + init(byteNumber: Int) { + self._byteNumber = byteNumber + } + + @inlinable + var _shift: Integer { + // As byte number 0 is the end index, the byte number is one byte too large for the shift. + return Integer((self._byteNumber - 1) * 8) + } + } + + @inlinable + public var startIndex: Index { + return Index(byteNumber: Int(self.integer.neededBytes)) + } + + @inlinable + public var endIndex: Index { + return Index(byteNumber: 0) + } + + @inlinable + public var count: Int { + return Int(self.integer.neededBytes) + } + + @inlinable + public subscript(index: Index) -> UInt8 { + // We perform the bitwise operations in magnitude space. + let shifted = Integer.Magnitude(truncatingIfNeeded: self.integer) >> index._shift + let masked = shifted & 0xFF + return UInt8(masked) + } +} + +extension IntegerBytesCollection.Index: Hashable { } + +extension IntegerBytesCollection.Index: Sendable { } + +extension IntegerBytesCollection.Index: Comparable { + // Comparable here is backwards to the original ordering. + @inlinable + public static func <(lhs: Self, rhs: Self) -> Bool { + return lhs._byteNumber > rhs._byteNumber + } + + @inlinable + public static func >(lhs: Self, rhs: Self) -> Bool { + return lhs._byteNumber < rhs._byteNumber + } + + @inlinable + public static func <=(lhs: Self, rhs: Self) -> Bool { + return lhs._byteNumber >= rhs._byteNumber + } + + @inlinable + public static func >=(lhs: Self, rhs: Self) -> Bool { + return lhs._byteNumber <= rhs._byteNumber + } +} + +extension IntegerBytesCollection.Index: Strideable { + @inlinable + public func advanced(by n: Int) -> IntegerBytesCollection.Index { + return IntegerBytesCollection.Index(byteNumber: self._byteNumber - n) + } + + @inlinable + public func distance(to other: IntegerBytesCollection.Index) -> Int { + // Remember that early indices have high byte numbers and later indices have low ones. + return self._byteNumber - other._byteNumber + } +} + +extension Int8: ASN1IntegerRepresentable { } + +extension UInt8: ASN1IntegerRepresentable { } + +extension Int16: ASN1IntegerRepresentable { } + +extension UInt16: ASN1IntegerRepresentable { } + +extension Int32: ASN1IntegerRepresentable { } + +extension UInt32: ASN1IntegerRepresentable { } + +extension Int64: ASN1IntegerRepresentable { } + +extension UInt64: ASN1IntegerRepresentable { } + +extension Int: ASN1IntegerRepresentable { } + +extension UInt: ASN1IntegerRepresentable { } + +extension RandomAccessCollection where Element == UInt8 { + @inlinable + func _trimLeadingExcessBytes() -> SubSequence { + var slice = self[...] + guard let first = slice.first else { + // Easy case, empty. + return slice + } + + let wholeByte: UInt8 + + switch first { + case 0: + wholeByte = 0 + case 0xFF: + wholeByte = 0xFF + default: + // We're already fine, this is maximally compact. We need the whole thing. + return slice + } + + // We never trim this to less than one byte, as that's always the smallest representation. + while slice.count > 1 { + // If the first byte is equal to our original first byte, and the top bit + // of the next byte is also equal to that, then we need to drop the byte and + // go again. + if slice.first != wholeByte { + break + } + + guard let second = slice.dropFirst().first else { + preconditionFailure("Loop condition violated: must be at least two bytes left") + } + + if second & 0x80 != wholeByte & 0x80 { + // Different top bit, we need the leading byte. + break + } + + // Both the first byte and the top bit of the next are all zero or all 1, drop the leading + // byte. + slice = slice.dropFirst() + } + + return slice + } +} + +extension UInt8 { + @inlinable + var _topBitSet: Bool { + return (self & 0x80) != 0 + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift new file mode 100644 index 0000000..758b66d --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift @@ -0,0 +1,43 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// An ASN1 NULL represents nothing. + public struct ASN1Null: ASN1ImplicitlyTaggable, Hashable, Sendable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .null + } + + /// Construct a new ASN.1 null. + @inlinable + public init() { } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier, case .primitive(let content) = node.content else { + throw ASN1Error.unexpectedFieldType + } + + guard content.count == 0 else { + throw ASN1Error.invalidASN1Object + } + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) { + coder.appendPrimitiveNode(identifier: identifier, { _ in }) + } + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift new file mode 100644 index 0000000..95c506e --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift @@ -0,0 +1,66 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// An OCTET STRING is a representation of a string of octets. + public struct ASN1OctetString: ASN1ImplicitlyTaggable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveOctetString + } + + /// The octets that make up this OCTET STRING. + public var bytes: ArraySlice + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.unexpectedFieldType + } + + guard case .primitive(let content) = node.content else { + preconditionFailure("ASN.1 parser generated primitive node with constructed content") + } + + self.bytes = content + } + + /// Construct an OCTET STRING from a sequence of bytes. + /// + /// - parameters: + /// - contentBytes: The bytes that make up this OCTET STRING. + @inlinable + public init(contentBytes: ArraySlice) { + self.bytes = contentBytes + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + bytes.append(contentsOf: self.bytes) + } + } + } +} + +extension ASN1.ASN1OctetString: Hashable { } + +extension ASN1.ASN1OctetString: Sendable { } + +extension ASN1.ASN1OctetString { + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Strings.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Strings.swift new file mode 100644 index 0000000..280000e --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Strings.swift @@ -0,0 +1,351 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// A UTF8String represents a string made up of UTF-8 bytes. + public struct ASN1UTF8String: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveUTF8String + } + + /// The raw bytes that make up this string. + public var bytes: ArraySlice + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes + } + + /// Construct a UTF8STRING from raw bytes. + @inlinable + public init(contentBytes: ArraySlice) { + self.bytes = contentBytes + } + + @inlinable + public init(stringLiteral value: StringLiteralType) { + self.bytes = ArraySlice(value.utf8) + } + + /// Construct a UTF8STRING from a String. + @inlinable + public init(_ string: String) { + self.bytes = ArraySlice(string.utf8) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + let octet = ASN1OctetString(contentBytes: self.bytes) + try octet.serialize(into: &coder, withIdentifier: identifier) + } + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } + } + + /// TeletexString is an uncommon ASN.1 string type. + /// + /// This module represents a TeletexString as an opaque sequence of bytes. + public struct ASN1TeletexString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveTeletexString + } + + /// The raw bytes that make up this string. + public var bytes: ArraySlice + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes + } + + /// Construct a TeletexString from raw bytes. + @inlinable + public init(contentBytes: ArraySlice) { + self.bytes = contentBytes + } + + @inlinable + public init(stringLiteral value: StringLiteralType) { + self.bytes = ArraySlice(value.utf8) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + let octet = ASN1OctetString(contentBytes: self.bytes) + try octet.serialize(into: &coder, withIdentifier: identifier) + } + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } + } + + /// PrintableString represents a String made up of bytes that can reliably be printed in a terminal. + /// + /// This string will be validated when it is constructed, and will reject characters outside of this + /// space. + /// + /// PrintableString is deprecated for most use-cases and generally ``ASN1/ASN1UTF8String`` should be + /// preferred. + public struct ASN1PrintableString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitivePrintableString + } + + /// The raw bytes that make up this string. + public var bytes: ArraySlice { + didSet { + precondition(Self._isValid(self.bytes)) + } + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes + guard Self._isValid(self.bytes) else { + throw ASN1Error.invalidStringRepresentation + } + } + + /// Construct a PrintableString from raw bytes. + @inlinable + public init(contentBytes: ArraySlice) throws { + self.bytes = contentBytes + guard Self._isValid(self.bytes) else { + throw ASN1Error.invalidStringRepresentation + } + } + + @inlinable + public init(stringLiteral value: StringLiteralType) { + self.bytes = ArraySlice(value.utf8) + precondition(Self._isValid(self.bytes)) + } + + /// Construct a PrintableString from a String. + @inlinable + public init(_ string: String) throws { + self.bytes = ArraySlice(string.utf8) + + guard Self._isValid(self.bytes) else { + throw ASN1Error.invalidStringRepresentation + } + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + let octet = ASN1OctetString(contentBytes: self.bytes) + try octet.serialize(into: &coder, withIdentifier: identifier) + } + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } + + @inlinable + static func _isValid(_ bytes: ArraySlice) -> Bool { + bytes.allSatisfy { + switch $0 { + case UInt8(ascii: "a")...UInt8(ascii: "z"), + UInt8(ascii: "A")...UInt8(ascii: "Z"), + UInt8(ascii: "0")...UInt8(ascii: "9"), + UInt8(ascii: "'"), UInt8(ascii: "("), + UInt8(ascii: ")"), UInt8(ascii: "+"), + UInt8(ascii: "-"), UInt8(ascii: "?"), + UInt8(ascii: ":"), UInt8(ascii: "/"), + UInt8(ascii: "="), UInt8(ascii: " "), + UInt8(ascii: ","), UInt8(ascii: "."): + return true + default: + return false + } + } + } + } + + /// UniversalString is an uncommon ASN.1 string type. + /// + /// This module represents a UniversalString as an opaque sequence of bytes. + public struct ASN1UniversalString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveUniversalString + } + + /// The raw bytes that make up this string. + public var bytes: ArraySlice + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes + } + + /// Construct a UniversalString from raw bytes. + @inlinable + public init(contentBytes: ArraySlice) { + self.bytes = contentBytes + } + + @inlinable + public init(stringLiteral value: StringLiteralType) { + self.bytes = ArraySlice(value.utf8) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + let octet = ASN1OctetString(contentBytes: self.bytes) + try octet.serialize(into: &coder, withIdentifier: identifier) + } + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } + } + + /// BMPString is an uncommon ASN.1 string type. + /// + /// This module represents a BMPString as an opaque sequence of bytes. + public struct ASN1BMPString: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveBMPString + } + + /// The raw bytes that make up this string. + public var bytes: ArraySlice + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes + } + + /// Construct a BMPString from raw bytes. + @inlinable + public init(contentBytes: ArraySlice) { + self.bytes = contentBytes + } + + @inlinable + public init(stringLiteral value: StringLiteralType) { + self.bytes = ArraySlice(value.utf8) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + let octet = ASN1OctetString(contentBytes: self.bytes) + try octet.serialize(into: &coder, withIdentifier: identifier) + } + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } + } + + /// IA5String represents a String made up of ASCII characters. + /// + /// This string will be validated when it is constructed, and will reject characters outside of this + /// space. + /// + /// IA5String is deprecated for most use-cases and generally ``ASN1/ASN1UTF8String`` should be + /// preferred. + public struct ASN1IA5String: ASN1ImplicitlyTaggable, Hashable, Sendable, ExpressibleByStringLiteral { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .primitiveIA5String + } + + /// The raw bytes that make up this string. + public var bytes: ArraySlice { + didSet { + precondition(Self._isValid(self.bytes)) + } + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self.bytes = try ASN1OctetString(asn1Encoded: node, withIdentifier: identifier).bytes + guard Self._isValid(self.bytes) else { + throw ASN1Error.invalidStringRepresentation + } + } + + /// Construct an IA5String from raw bytes. + @inlinable + public init(contentBytes: ArraySlice) throws { + self.bytes = contentBytes + guard Self._isValid(self.bytes) else { + throw ASN1Error.invalidStringRepresentation + } + } + + @inlinable + public init(stringLiteral value: StringLiteralType) { + self.bytes = ArraySlice(value.utf8) + precondition(Self._isValid(self.bytes)) + } + + /// Construct an IA5String from a String. + @inlinable + public init(_ string: String) throws { + self.bytes = ArraySlice(string.utf8) + + guard Self._isValid(self.bytes) else { + throw ASN1Error.invalidStringRepresentation + } + } + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + let octet = ASN1OctetString(contentBytes: self.bytes) + try octet.serialize(into: &coder, withIdentifier: identifier) + } + + @inlinable + public func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { + return try self.bytes.withUnsafeBytes(body) + } + + @inlinable + static func _isValid(_ bytes: ArraySlice) -> Bool { + // Valid IA5Strings are ASCII characters. + bytes.allSatisfy { $0 < 128 } + } + } +} + +extension String { + /// Construct a `String` from an ``ASN1/ASN1UTF8String``. + public init(_ utf8String: ASN1.ASN1UTF8String) { + self = String(decoding: utf8String.bytes, as: UTF8.self) + } + + /// Construct a `String` from an ``ASN1/ASN1PrintableString``. + public init(_ printableString: ASN1.ASN1PrintableString) { + self = String(decoding: printableString.bytes, as: UTF8.self) + } + + /// Construct a `String` from an ``ASN1/ASN1IA5String``. + public init(_ ia5String: ASN1.ASN1IA5String) { + self = String(decoding: ia5String.bytes, as: UTF8.self) + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift b/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift new file mode 100644 index 0000000..00a746a --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +// For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else. +extension ArraySlice: ASN1Serializable where Element == UInt8 { } + +extension ArraySlice: ASN1Parseable where Element == UInt8 { } + +extension ArraySlice: ASN1ImplicitlyTaggable where Element == UInt8 { } + +extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 { + // We only use unsigned "bigint"s + @inlinable + public static var isSigned: Bool { + return false + } + + @inlinable + public init(asn1IntegerBytes: ArraySlice) throws { + self = asn1IntegerBytes + } + + @inlinable + public func withBigEndianIntegerBytes(_ body: (ArraySlice) throws -> ReturnType) rethrows -> ReturnType { + return try body(self) + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift b/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift new file mode 100644 index 0000000..b30af83 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift @@ -0,0 +1,200 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// GeneralizedTime represents a date and time. + /// + /// In DER format, this is always in the form of `YYYYMMDDHHMMSSZ`. The type in + /// general is capable of expressing fractional seconds. The time is always in the + /// UTC time zone. + public struct GeneralizedTime: ASN1ImplicitlyTaggable, Hashable, Sendable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .generalizedTime + } + + /// The numerical year. + @inlinable + public var year: Int { + get { + return self._year + } + set { + self._year = newValue + try! self._validate() + } + } + + /// The numerical month. + @inlinable + public var month: Int { + get { + return self._month + } + set { + self._month = newValue + try! self._validate() + } + } + + /// The numerical day. + @inlinable + public var day: Int { + get { + return self._day + } + set { + self._day = newValue + try! self._validate() + } + } + + /// The numerical hours. + @inlinable + public var hours: Int { + get { + return self._hours + } + set { + self._hours = newValue + try! self._validate() + } + } + + /// The numerical minutes. + @inlinable + public var minutes: Int { + get { + return self._minutes + } + set { + self._minutes = newValue + try! self._validate() + } + } + + /// The numerical seconds. + @inlinable + public var seconds: Int { + get { + return self._seconds + } + set { + self._seconds = newValue + try! self._validate() + } + } + + /// The fractional seconds. + @inlinable + public var fractionalSeconds: Double { + get { + return self._fractionalSeconds + } + set { + self._fractionalSeconds = newValue + try! self._validate() + } + } + + @usableFromInline var _year: Int + @usableFromInline var _month: Int + @usableFromInline var _day: Int + @usableFromInline var _hours: Int + @usableFromInline var _minutes: Int + @usableFromInline var _seconds: Int + @usableFromInline var _fractionalSeconds: Double + + /// Construct a new ``ASN1/GeneralizedTime`` from individual components. + /// + /// - parameters: + /// - year: The numerical year + /// - month: The numerical month + /// - day: The numerical day + /// - hours: The numerical hours + /// - minutes: The numerical minutes + /// - seconds: The numerical seconds + /// - fractionalSeconds: The numerical fractional seconds. + @inlinable + public init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int, fractionalSeconds: Double) throws { + self._year = year + self._month = month + self._day = day + self._hours = hours + self._minutes = minutes + self._seconds = seconds + self._fractionalSeconds = fractionalSeconds + + try self._validate() + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.unexpectedFieldType + } + + guard case .primitive(let content) = node.content else { + preconditionFailure("ASN.1 parser generated primitive node with constructed content") + } + + self = try TimeUtilities.generalizedTimeFromBytes(content) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + bytes.append(self) + } + } + + @inlinable + func _validate() throws { + // Validate that the structure is well-formed. + guard self._year >= 0 && self._year <= 9999 else { + throw ASN1Error.invalidASN1Object + } + + // This also validates the month. + guard let daysInMonth = TimeUtilities.daysInMonth(self._month, ofYear: self._year) else { + throw ASN1Error.invalidASN1Object + } + + guard self._day >= 1 && self._day <= daysInMonth else { + throw ASN1Error.invalidASN1Object + } + + guard self._hours >= 0 && self._hours < 24 else { + throw ASN1Error.invalidASN1Object + } + + guard self._minutes >= 0 && self._minutes < 60 else { + throw ASN1Error.invalidASN1Object + } + + // We allow leap seconds here, but don't validate it. + // This exposes us to potential confusion if we naively implement + // comparison here. We should consider whether this needs to be transformable + // to `Date` or similar. + guard self._seconds >= 0 && self._seconds <= 61 else { + throw ASN1Error.invalidASN1Object + } + + // Fractional seconds may not be negative and may not be 1 or more. + guard self._fractionalSeconds >= 0 && self._fractionalSeconds < 1 else { + throw ASN1Error.invalidASN1Object + } + } + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift b/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift new file mode 100644 index 0000000..10e472b --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift @@ -0,0 +1,345 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// An Object Identifier is a representation of some kind of object. + /// + /// It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers. Object identifiers + /// form a nested tree of namespaces. + /// + /// The most common way to construct an OID is to create one using an array literal. For example, the OID 2.5.4.41 can be created + /// as: + /// + /// ```swift + /// let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41] + /// ``` + /// + /// This object also has a number of pre-existing values defined in namespaces. Users are encouraged to create their own namespaces to + /// make it easier to use OIDs in their own serialization code. + public struct ASN1ObjectIdentifier: ASN1ImplicitlyTaggable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .objectIdentifier + } + + @usableFromInline + var _oidComponents: [UInt] + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.unexpectedFieldType + } + + guard case .primitive(var content) = node.content else { + preconditionFailure("ASN.1 parser generated primitive node with constructed content") + } + + // We have to parse the content. From the spec: + // + // > Each subidentifier is represented as a series of (one or more) octets. Bit 8 of each octet indicates whether it + // > is the last in the series: bit 8 of the last octet is zero, bit 8 of each preceding octet is one. Bits 7 to 1 of + // > the octets in the series collectively encode the subidentifier. Conceptually, these groups of bits are concatenated + // > to form an unsigned binary number whose most significant bit is bit 7 of the first octet and whose least significant + // > bit is bit 1 of the last octet. The subidentifier shall be encoded in the fewest possible octets[...]. + // > + // > The number of subidentifiers (N) shall be one less than the number of object identifier components in the object identifier + // > value being encoded. + // > + // > The numerical value of the first subidentifier is derived from the values of the first _two_ object identifier components + // > in the object identifier value being encoded, using the formula: + // > + // > (X*40) + Y + // > + // > where X is the value of the first object identifier component and Y is the value of the second object identifier component. + // + // Yeah, this is a bit bananas, but basically there are only 3 first OID components (0, 1, 2) and there are no more than 39 children + // of nodes 0 or 1. In my view this is too clever by half, but the ITU.T didn't ask for my opinion when they were coming up with this + // scheme, likely because I was in middle school at the time. + var subcomponents = [UInt]() + while content.count > 0 { + subcomponents.append(try content.readUIntUsing8BitBytesASN1Discipline()) + } + + guard subcomponents.count >= 2 else { + throw ASN1Error.invalidObjectIdentifier + } + + // Now we need to expand the subcomponents out. This means we need to undo the step above. The first component will be in the range 0..<40 + // when the first oidComponent is 0, 40..<80 when the first oidComponent is 1, and 80+ when the first oidComponent is 2. + var oidComponents = [UInt]() + oidComponents.reserveCapacity(subcomponents.count + 1) + + switch subcomponents.first! { + case ..<40: + oidComponents.append(0) + oidComponents.append(subcomponents.first!) + case 40 ..< 80: + oidComponents.append(1) + oidComponents.append(subcomponents.first! - 40) + default: + oidComponents.append(2) + oidComponents.append(subcomponents.first! - 80) + } + + oidComponents.append(contentsOf: subcomponents.dropFirst()) + + self._oidComponents = oidComponents + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + var components = self._oidComponents[...] + guard let firstComponent = components.popFirst(), let secondComponent = components.popFirst() else { + preconditionFailure("Invalid number of OID components: must be at least two!") + } + + let serializedFirstComponent = (firstComponent * 40) + secondComponent + ASN1ObjectIdentifier._writeOIDSubidentifier(serializedFirstComponent, into: &bytes) + + while let component = components.popFirst() { + ASN1ObjectIdentifier._writeOIDSubidentifier(component, into: &bytes) + } + } + } + + @inlinable + static func _writeOIDSubidentifier(_ identifier: UInt, into array: inout [UInt8]) { + array.writeUsing7BitBytesASN1Discipline(unsignedInteger: identifier) + } + } +} + +extension ASN1.ASN1ObjectIdentifier: Hashable {} + +extension ASN1.ASN1ObjectIdentifier: Sendable { } + +extension ASN1.ASN1ObjectIdentifier: ExpressibleByArrayLiteral { + @inlinable + public init(arrayLiteral elements: UInt...) { + self._oidComponents = elements + } +} + +extension ASN1.ASN1ObjectIdentifier { + /// Represents a namespace for OIDs that identify named Elliptic Curves. + /// + /// These OIDs are defined in RFC 5480. + public enum NamedCurves { + /// Represents the NIST P256 curve. Also called `prime256v1`. + public static let secp256r1: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 3, 1, 7] + + /// Represents the NIST P384 curve. + public static let secp384r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 34] + + /// Represents the NIST P521 curve. + public static let secp521r1: ASN1.ASN1ObjectIdentifier = [1, 3, 132, 0, 35] + } + + /// Represents a namespace for OIDs that identify an algorithm within an + /// `AlgorithmIdentifier` object. + public enum AlgorithmIdentifier { + /// Identifies an elliptic curve public key. + /// + /// This identifier is defined in RFC 5480. `AlgorithmIdentifier` objects with this key have a parameters + /// value defined in that RFC. + public static let idEcPublicKey: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 10_045, 2, 1] + + /// Identifies a PKCS#1v1.5 RSA signature using SHA256 as the hash algorithm. + /// + /// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL. + public static let sha256WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 11] + + /// Identifies a PKCS#1v1.5 RSA signature using SHA384 as the hash algorithm. + /// + /// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL. + public static let sha384WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 12] + + /// Identifies a PKCS#1v1.5 RSA signature using SHA512 as the hash algorithm. + /// + /// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL. + public static let sha512WithRSAEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 13] + + /// Identifies an RSA PSS signature. + /// + /// This identifier is defined in RFC 4055. When used, the parameters will be `RSASSA-PSS-params` as + /// defined in that RFC. + public static let rsaPSS: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 10] + + /// Identifies an RSA public key. + /// + /// This identifier is defined in RFC 4055. When used, the parameters MUST be NULL. + public static let rsaEncryption: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 11_3549, 1, 1, 1] + } + + /// Represents a namespace for OIDs that identify Relative Distinguished Name components. + /// + /// An enormous number of these identifiers exist. A non-exhaustive list of them is available in + /// RFC 4519. + public enum NameAttributes { + /// The 'name' attribute type is the attribute supertype from which user + /// attribute types with the name syntax inherit. Such attribute types + /// are typically used for naming. The attribute type is multi-valued. + public static let name: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 41] + + /// The 'sn' ('surname' in X.500) attribute type contains name strings + /// for the family names of a person. + public static let surname: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 4] + + /// The 'givenName' attribute type contains name strings that are the + /// part of a person's name that is not their surname. + public static let givenName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 42] + + /// The 'initials' attribute type contains strings of initials of some or + /// all of an individual's names, except the surname(s). + public static let initials: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 43] + + /// The 'generationQualifier' attribute type contains name strings that + /// are typically the suffix part of a person's name. + public static let generationQualifier: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 44] + + /// The 'cn' ('commonName' in X.500) attribute type contains names of an + /// object. If the object corresponds to a person, it is typically the person's full + /// name. + /// + /// In modern usage, the common name typically represents a general identifier of an actor. + public static let commonName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 3] + + /// The 'l' ('localityName' in X.500) attribute type contains names of a + /// locality or place, such as a city, county, or other geographic + /// region. + public static let localityName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 7] + + /// The 'st' ('stateOrProvinceName' in X.500) attribute type contains the + /// full names of states or provinces. + public static let stateOrProvinceName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 8] + + /// The 'o' ('organizationName' in X.500) attribute type contains the + /// names of an organization. + public static let organizationName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 10] + + /// The 'ou' ('organizationalUnitName' in X.500) attribute type contains + /// the names of an organizational unit. + public static let organizationalUnitName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 11] + + /// The 'title' attribute type contains the title of a person in their + /// organizational context. + public static let title: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 12] + + /// The 'dnQualifier' attribute type contains disambiguating information + /// strings to add to the relative distinguished name of an entry. The + /// information is intended for use when merging data from multiple + /// sources in order to prevent conflicts between entries that would + /// otherwise have the same name. + public static let dnQualifier: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 46] + + /// The 'c' ('countryName' in X.500) attribute type contains a two-letter + /// ISO 3166 [ISO3166] country code. + public static let countryName: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 6] + + /// The 'serialNumber' attribute type contains the serial numbers of + /// devices. + public static let serialNumber: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 5] + + /// The pseudonym attribute type contains a pseudonym of the subject. + public static let pseudonym: ASN1.ASN1ObjectIdentifier = [2, 5, 4, 65] + + /// The 'dc' ('domainComponent' in RFC 1274) attribute type is a string + /// holding one component, a label, of a DNS domain name naming a host. + public static let domainComponent: ASN1.ASN1ObjectIdentifier = [0, 9, 2342, 19200300, 100, 1, 25] + + /// The emailAddress attribute type specifies the electronic-mail address + /// or addresses of a subject as an unstructured ASCII string. + public static let emailAddress: ASN1.ASN1ObjectIdentifier = [1, 2, 840, 113549, 1, 9, 1] + } + + /// Represents a namespace for OIDs corresponding to OCSP identifiers. + /// + /// The meaning of these OIDs is defined in RFC 6960. + public enum OCSP { + /// Identifies a `BasicOCSPResponse`. + public static let basicResponse: ASN1.ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 48, 1, 1] + } +} + +extension ArraySlice where Element == UInt8 { + @inlinable + mutating func readUIntUsing8BitBytesASN1Discipline() throws -> UInt { + // In principle OID subidentifiers and long tags can be too large to fit into a UInt. We are choosing to not care about that + // because for us it shouldn't matter. + guard let subidentifierEndIndex = self.firstIndex(where: { $0 & 0x80 == 0x00 }) else { + throw ASN1Error.invalidASN1Object + } + + let oidSlice = self[self.startIndex ... subidentifierEndIndex] + + guard let firstByte = oidSlice.first, firstByte != 0x80 else { + // If the first byte is 0x80 then we have a leading 0 byte. All numbers encoded this way + // need to be encoded in the minimal number of bytes, so we need to reject this. + throw ASN1Error.invalidASN1Object + } + + self = self[self.index(after: subidentifierEndIndex)...] + + // We need to compact the bits. These are 7-bit integers, which is really awkward. + return try UInt(sevenBitBigEndianBytes: oidSlice) + } +} + +extension UInt { + @inlinable + init(sevenBitBigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 { + // We need to know how many bytes we _need_ to store this "int". As a base optimization we refuse to parse + // anything larger than 9 bytes wide, even though conceptually we could fit a few more bits. + guard ((bytes.count * 7) + 7) / 8 <= MemoryLayout.size else { + throw ASN1Error.invalidASN1Object + } + + self = 0 + let shiftSizes = stride(from: 0, to: bytes.count * 7, by: 7).reversed() + + var index = bytes.startIndex + for shift in shiftSizes { + self |= UInt(bytes[index] & 0x7F) << shift + bytes.formIndex(after: &index) + } + } +} + +extension Array where Element == UInt8 { + @inlinable + mutating func writeUsing7BitBytesASN1Discipline(unsignedInteger identifier: UInt) { + // An OID subidentifier or long-form tag is written as an integer over 7-bit bytes, where the last byte has the top bit unset. + // The first thing we need is to know how many bits we need to write + let bitsToWrite = UInt.bitWidth - identifier.leadingZeroBitCount + let bytesToWrite = (bitsToWrite + 6) / 7 + + guard bytesToWrite > 0 else { + // Just a zero. + self.append(0) + return + } + + for byteNumber in (1..> shift) & 0x7f) | 0x80 + self.append(byte) + } + + // Last byte to append here, we must unset the top bit. + let byte = UInt8((identifier & 0x7F)) + self.append(byte) + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/TimeUtilities.swift b/Sources/SwiftASN1/Basic ASN1 Types/TimeUtilities.swift new file mode 100644 index 0000000..9bf3d0a --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/TimeUtilities.swift @@ -0,0 +1,277 @@ +@usableFromInline +enum TimeUtilities { + @inlinable + static func generalizedTimeFromBytes(_ bytes: ArraySlice) throws -> ASN1.GeneralizedTime { + var bytes = bytes + + // First, there must always be a calendar date. No separators, 4 + // digits for the year, 2 digits for the month, 2 digits for the day. + guard let rawYear = bytes._readFourDigitDecimalInteger(), + let rawMonth = bytes._readTwoDigitDecimalInteger(), + let rawDay = bytes._readTwoDigitDecimalInteger() else { + throw ASN1Error.invalidASN1Object + } + + // Next there must be a _time_. Per DER rules, this time must always go + // to at least seconds, there are no separators, there is no time-zone (but there must be a 'Z'), + // and there may be fractional seconds but they must not have trailing zeros. + guard let rawHour = bytes._readTwoDigitDecimalInteger(), + let rawMinutes = bytes._readTwoDigitDecimalInteger(), + let rawSeconds = bytes._readTwoDigitDecimalInteger() else { + throw ASN1Error.invalidASN1Object + } + + // There may be some fractional seconds. + var fractionalSeconds: Double = 0 + if bytes.first == UInt8(ascii: ".") { + fractionalSeconds = try bytes._readFractionalSeconds() + } + + // The next character _must_ be Z, or the encoding is invalid. + guard bytes.popFirst() == UInt8(ascii: "Z") else { + throw ASN1Error.invalidASN1Object + } + + // Great! There better not be anything left. + guard bytes.count == 0 else { + throw ASN1Error.invalidASN1Object + } + + return try ASN1.GeneralizedTime(year: rawYear, + month: rawMonth, + day: rawDay, + hours: rawHour, + minutes: rawMinutes, + seconds: rawSeconds, + fractionalSeconds: fractionalSeconds) + } + + @inlinable + static func utcTimeFromBytes(_ bytes: ArraySlice) throws -> ASN1.UTCTime { + var bytes = bytes + + // First, there must always be a calendar date. No separators, 2 + // digits for the year, 2 digits for the month, 2 digits for the day. + guard let rawYear = bytes._readTwoDigitDecimalInteger(), + let rawMonth = bytes._readTwoDigitDecimalInteger(), + let rawDay = bytes._readTwoDigitDecimalInteger() else { + throw ASN1Error.invalidASN1Object + } + + // Next there must be a _time_. Per DER rules, this time must always go + // to at least seconds, there are no separators, there is no time-zone (but there must be a 'Z'). + guard let rawHour = bytes._readTwoDigitDecimalInteger(), + let rawMinutes = bytes._readTwoDigitDecimalInteger(), + let rawSeconds = bytes._readTwoDigitDecimalInteger() else { + throw ASN1Error.invalidASN1Object + } + + // The next character _must_ be Z, or the encoding is invalid. + guard bytes.popFirst() == UInt8(ascii: "Z") else { + throw ASN1Error.invalidASN1Object + } + + // Great! There better not be anything left. + guard bytes.count == 0 else { + throw ASN1Error.invalidASN1Object + } + + let actualYear = rawYear < 50 ? rawYear &+ 2000 : rawYear &+ 1900 + + return try ASN1.UTCTime(year: actualYear, + month: rawMonth, + day: rawDay, + hours: rawHour, + minutes: rawMinutes, + seconds: rawSeconds) + } + + @inlinable + static func daysInMonth(_ month: Int, ofYear year: Int) -> Int? { + switch month { + case 1: + return 31 + case 2: + // This one has a dependency on the year! + // A leap year occurs in any year divisible by 4, except when that year is divisible by 100, + // unless the year is divisible by 400. + let isLeapYear = (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) + return isLeapYear ? 29 : 28 + case 3: + return 31 + case 4: + return 30 + case 5: + return 31 + case 6: + return 30 + case 7: + return 31 + case 8: + return 31 + case 9: + return 30 + case 10: + return 31 + case 11: + return 30 + case 12: + return 31 + default: + return nil + } + } +} + +extension ArraySlice where Element == UInt8 { + @inlinable + mutating func _readFourDigitDecimalInteger() -> Int? { + guard let first = self._readTwoDigitDecimalInteger(), + let second = self._readTwoDigitDecimalInteger() else { + return nil + } + + // Unchecked math is still safe here: we're in Int32 space, and this number cannot + // get any larger than 9999. + return (first &* 100) &+ second + } + + @inlinable + mutating func _readTwoDigitDecimalInteger() -> Int? { + guard let firstASCII = self.popFirst(), + let secondASCII = self.popFirst() else { + return nil + } + + guard let first = Int(fromDecimalASCII: firstASCII), + let second = Int(fromDecimalASCII: secondASCII) else { + return nil + } + + // Unchecked math is safe here: we're in Int32 space at the very least, and this number cannot + // possibly be smaller than zero or larger than 99. + return (first &* 10) &+ (second) + } + + /// This may only be called if there's a leading period: we precondition on this fact. + @inlinable + mutating func _readFractionalSeconds() throws -> Double { + precondition(self.popFirst() == UInt8(ascii: ".")) + + var numerator = 0 + var denominator = 1 + + while let nextASCII = self.first, let next = Int(fromDecimalASCII: nextASCII) { + self = self.dropFirst() + + let (newNumerator, multiplyOverflow) = numerator.multipliedReportingOverflow(by: 10) + let (newDenominator, secondMultiplyOverflow) = denominator.multipliedReportingOverflow(by: 10) + let (newNumeratorWithAdded, addingOverflow) = newNumerator.addingReportingOverflow(next) + + // If the new denominator overflows, we just cap to the old value. + if !secondMultiplyOverflow { + denominator = newDenominator + } + + // If the numerator overflows, we don't support the result. + if multiplyOverflow || addingOverflow { + throw ASN1Error.invalidASN1Object + } + + numerator = newNumeratorWithAdded + } + + // Ok, we're either at the end or the next character is a Z. One final check: there may not have + // been any trailing zeros here. This means the number may not be 0 mod 10. + if numerator % 10 == 0 { + throw ASN1Error.invalidASN1Object + } + + return Double(numerator) / Double(denominator) + } +} + +extension Array where Element == UInt8 { + @inlinable + mutating func append(_ generalizedTime: ASN1.GeneralizedTime) { + self._appendFourDigitDecimal(generalizedTime.year) + self._appendTwoDigitDecimal(generalizedTime.month) + self._appendTwoDigitDecimal(generalizedTime.day) + self._appendTwoDigitDecimal(generalizedTime.hours) + self._appendTwoDigitDecimal(generalizedTime.minutes) + self._appendTwoDigitDecimal(generalizedTime.seconds) + + // Ok, tricky moment here. Is the fractional part non-zero? If it is, we need to write it out as well. + if generalizedTime.fractionalSeconds != 0 { + let stringified = String(generalizedTime.fractionalSeconds) + assert(stringified.starts(with: "0.")) + + self.append(contentsOf: stringified.utf8.dropFirst(1)) + // Remove any trailing zeros from self, they are forbidden. + while self.last == 0 { + self = self.dropLast() + } + } + + self.append(UInt8(ascii: "Z")) + } + + @inlinable + mutating func append(_ utcTime: ASN1.UTCTime) { + precondition((1950..<2050).contains(utcTime.year)) + if utcTime.year >= 2000 { + self._appendTwoDigitDecimal(utcTime.year &- 2000) + } else { + self._appendTwoDigitDecimal(utcTime.year &- 1900) + } + self._appendTwoDigitDecimal(utcTime.month) + self._appendTwoDigitDecimal(utcTime.day) + self._appendTwoDigitDecimal(utcTime.hours) + self._appendTwoDigitDecimal(utcTime.minutes) + self._appendTwoDigitDecimal(utcTime.seconds) + self.append(UInt8(ascii: "Z")) + } + + @inlinable + mutating func _appendFourDigitDecimal(_ number: Int) { + assert(number >= 0 && number <= 9999) + + // Each digit can be isolated by dividing by the place and then taking the result modulo 10. + // This is annoyingly division heavy. There may be a better algorithm floating around. + // Unchecked math is fine, there cannot be an overflow here. + let asciiZero = UInt8(ascii: "0") + self.append(UInt8(truncatingIfNeeded: (number / 1000) % 10) &+ asciiZero) + self.append(UInt8(truncatingIfNeeded: (number / 100) % 10) &+ asciiZero) + self.append(UInt8(truncatingIfNeeded: (number / 10) % 10) &+ asciiZero) + self.append(UInt8(truncatingIfNeeded: number % 10) &+ asciiZero) + } + + @inlinable + mutating func _appendTwoDigitDecimal(_ number: Int) { + assert(number >= 0 && number <= 99) + + // Each digit can be isolated by dividing by the place and then taking the result modulo 10. + // This is annoyingly division heavy. There may be a better algorithm floating around. + // Unchecked math is fine, there cannot be an overflow here. + let asciiZero = UInt8(ascii: "0") + self.append(UInt8(truncatingIfNeeded: (number / 10) % 10) &+ asciiZero) + self.append(UInt8(truncatingIfNeeded: number % 10) &+ asciiZero) + } +} + +extension Int { + @inlinable + init?(fromDecimalASCII ascii: UInt8) { + let asciiZero = UInt8(ascii: "0") + let zeroToNine = 0...9 + + // These are all coming from UInt8space, the subtraction cannot overflow. + let converted = Int(ascii) &- Int(asciiZero) + + guard zeroToNine.contains(converted) else { + return nil + } + + self = converted + } +} diff --git a/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift b/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift new file mode 100644 index 0000000..b62f195 --- /dev/null +++ b/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift @@ -0,0 +1,184 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// UTCTime represents a date and time. + /// + /// In DER format, this is always in the form of `YYMMDDHHMMSSZ`, with no support for fractional seconds. + /// The time is always in the UTC time zone. + /// + /// ``UTCTime`` differs from ``GeneralizedTime`` in that it only has support for a two-digit year. This + /// means that it can only encode dates between 1950 and 2049. For dates outside that range, prefer + /// ``GeneralizedTime``. + public struct UTCTime: ASN1ImplicitlyTaggable, Hashable, Sendable { + @inlinable + public static var defaultIdentifier: ASN1.ASN1Identifier { + .utcTime + } + + /// The numerical year. + @inlinable + public var year: Int { + get { + return self._year + } + set { + self._year = newValue + try! self._validate() + } + } + + /// The numerical month. + @inlinable + public var month: Int { + get { + return self._month + } + set { + self._month = newValue + try! self._validate() + } + } + + /// The numerical day. + @inlinable + public var day: Int { + get { + return self._day + } + set { + self._day = newValue + try! self._validate() + } + } + + /// The numerical hours. + @inlinable + public var hours: Int { + get { + return self._hours + } + set { + self._hours = newValue + try! self._validate() + } + } + + /// The numerical minutes. + @inlinable + public var minutes: Int { + get { + return self._minutes + } + set { + self._minutes = newValue + try! self._validate() + } + } + + /// The numerical seconds. + @inlinable + public var seconds: Int { + get { + return self._seconds + } + set { + self._seconds = newValue + try! self._validate() + } + } + + @usableFromInline var _year: Int + @usableFromInline var _month: Int + @usableFromInline var _day: Int + @usableFromInline var _hours: Int + @usableFromInline var _minutes: Int + @usableFromInline var _seconds: Int + + /// Construct a new ``ASN1/UTCTime`` from individual components. + /// + /// - parameters: + /// - year: The numerical year. Must be in the range 1950 to 2049. + /// - month: The numerical month + /// - day: The numerical day + /// - hours: The numerical hours + /// - minutes: The numerical minutes + /// - seconds: The numerical seconds + @inlinable + public init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int) throws { + self._year = year + self._month = month + self._day = day + self._hours = hours + self._minutes = minutes + self._seconds = seconds + + try self._validate() + } + + @inlinable + public init(asn1Encoded node: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + guard node.identifier == identifier else { + throw ASN1Error.unexpectedFieldType + } + + guard case .primitive(let content) = node.content else { + preconditionFailure("ASN.1 parser generated primitive node with constructed content") + } + + self = try TimeUtilities.utcTimeFromBytes(content) + } + + @inlinable + public func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + coder.appendPrimitiveNode(identifier: identifier) { bytes in + bytes.append(self) + } + } + + @inlinable + func _validate() throws { + // Validate that the structure is well-formed. + // UTCTime can only hold years between 1950 and 2049. + guard self._year >= 1950 && self._year < 2050 else { + throw ASN1Error.invalidASN1Object + } + + // This also validates the month. + guard let daysInMonth = TimeUtilities.daysInMonth(self._month, ofYear: self._year) else { + throw ASN1Error.invalidASN1Object + } + + guard self._day >= 1 && self._day <= daysInMonth else { + throw ASN1Error.invalidASN1Object + } + + guard self._hours >= 0 && self._hours < 24 else { + throw ASN1Error.invalidASN1Object + } + + guard self._minutes >= 0 && self._minutes < 60 else { + throw ASN1Error.invalidASN1Object + } + + // We allow leap seconds here, but don't validate it. + // This exposes us to potential confusion if we naively implement + // comparison here. We should consider whether this needs to be transformable + // to `Date` or similar. + guard self._seconds >= 0 && self._seconds <= 61 else { + throw ASN1Error.invalidASN1Object + } + } + } +} diff --git a/Sources/SwiftASN1/Docs.docc/DecodingASN1.md b/Sources/SwiftASN1/Docs.docc/DecodingASN1.md new file mode 100644 index 0000000..e5b13e5 --- /dev/null +++ b/Sources/SwiftASN1/Docs.docc/DecodingASN1.md @@ -0,0 +1,304 @@ +# Encoding and Decoding DER + +Serialize and deserialize objects from DER format. + +## Overview + +When working with your own ASN.1 types, the biggest problem you'll have is writing the code to serialize and deserialize them from DER format. +This module does not provide an ASN.1 compiler which can automatically synthesise this code for you. Instead, you have to write it yourself. +This is some unfortunate boilerplate, but the good news is that it's straightforward enough that you'll get it done in no time. + +By way of a worked example, we can build up a few types in increasing complexity. + +## ECDSA Signature + +Our starting point is the ECDSA signature type, defined like this: + +``` +ECDSASignature ::= SEQUENCE { + r INTEGER, + s INTEGER } +``` + +This defines `ECDSASignature` as a `SEQUENCE` of two `INTEGER` values. + +In ASN.1, `SEQUENCE` is often used to define a record type. This is much like a Swift `struct`: an ordered series of named fields, often +of different types. That makes a `struct` the natural representation for our `ECDSASignature` type: + +```swift +struct ECDSASignature { + +} +``` + +### Storing Fields + +Our next problem is to work out the fields we want to store in our type. A natural choice might be `Int`, but some more careful reading will +clue us in to the fact that an ASN.1 `INTEGER` type is of arbitrary size. In the case of ECDSA signatures, these can be very large: 32 bytes +large or more! These won't fit into `Int`. + +To address this issue, ``SwiftASN1`` defines two helpers. The first is a protocol, ``ASN1IntegerRepresentable``. This allows users that have +access to a preferred arbitrary-precision integer type to decode directly to that type. The second is a conformance of `ArraySlice` to +``ASN1IntegerRepresentable``. This conformance allows us to just store the raw big-endian bytes of the INTEGER fields without needing to +define an arbitrary-precision integer ourselves. As we mostly care about these numbers as arbitrary byte sequences, we'll use this +escape hatch. + +```swift +struct ECDSASignature { + var r: ArraySlice + + var s: ArraySlice + + init(r: ArraySlice, s: ArraySlice) { + self.r = r + self.s = s + } +} +``` + +### Decoding from DER + +To decode from DER, we'll need to implement ``ASN1Parseable``. As this is a `SEQUENCE` type, however, we can safely implement +``ASN1ImplicitlyTaggable``. Most types can do so, especially anything that is a `SEQUENCE` type. + +To conform we need to implement the protocol requirement ``ASN1ImplicitlyTaggable/init(asn1Encoded:withIdentifier:)-iudo``. This function +will pass us a pair of arguments. The first is the ``ASN1/ASN1Node`` representing the root of the ASN.1 object tree we've been asked to parse +the `ECDSASignature` from. The second is the ``ASN1/ASN1Identifier`` we expect to have this node to have. In many cases this will be +``ASN1/ASN1Identifier/sequence``, but we will happily use whatever we're told to. + +The first trick is to unwrap the `SEQUENCE`. To do that, we can use ``ASN1/sequence(_:identifier:_:)``. This checks whether the ``ASN1/ASN1Node`` +we pass to it has the right ``ASN1/ASN1Identifier`` and that it is a constructed node. Assuming all those checks pass, our builder function +will be invoked with an ``ASN1/ASN1NodeCollection/Iterator`` that contains the nodes within the `SEQUENCE`. + +This initial scaffolding will look like this: + +```swift +extension ECDSASignature: ASN1ImplicitlyTaggable { + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + // TODO + } + } +} +``` + +Next, we need to decode the constituent objects. This is where the recursive nature of ASN.1 works in our favour. These sub-objects +(in this case of ASN.1 type `INTEGER`) are themselves described as trees of ASN.1 nodes. For `INTEGER` specifically this tree will +only have a root node, but in general all ASN.1 objects can be parsed from a single root node. + +Fortunately for us, this is exactly the interface that ``ASN1Parseable`` provides us. So we can safely recurse into the child objects using +the helper method ``ASN1Parseable/init(asn1Encoded:)-5tkco``. This handy method will even take care of consuming the node from the iterator for us. +The result is a method body that looks like this: + +```swift +init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let r = try ArraySlice(asn1Encoded: &nodes) + let s = try ArraySlice(asn1Encoded: &nodes) + + return ECDSASignature(r: r, s: s) + } +} +``` + +Note that we don't need to confirm the exact length of the ``ASN1/ASN1NodeCollection/Iterator`` `nodes`. The helper method +``ASN1Parseable/init(asn1Encoded:)-5tkco`` will automatically throw an error if there is no node available to decode an object from, and +``ASN1/sequence(_:identifier:_:)`` will confirm that all the nodes were consumed from the child iterator. + +This composition approach scales to more complex types. Any ASN.1 composite object can be implemented using ``ASN1/sequence(_:identifier:_:)`` +and recursive initialization of ever-smaller ASN.1 objects. + +### Encoding to DER + +Next we need to implement the inverse method, ``ASN1ImplicitlyTaggable/serialize(into:withIdentifier:)``. This method is implemented in much the +same was as our parsing method, but in reverse. + +Importantly, here we don't have a `sequence` helper. Instead we use the more general operation, ``ASN1/Serializer/appendConstructedNode(identifier:_:)``. +This doesn't have any semantic implications: it applies a general purpose ASN.1 constructed node with a given identifier. + +```swift +func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.r) + try coder.serialize(self.s) + } +} +``` + +Note that we have shadowed our `coder` in this block. This is important: we're passed our original ``ASN1/Serializer`` `coder` as an `inout` +variable, and ``ASN1/Serializer/appendConstructedNode(identifier:_:)`` is a `mutating` operation. The closure it takes will receive the same +serializer as an `inout` again, allowing us to subsequently serialize new objects. + +We can then recurse down the tree. ``ASN1/Serializer/serialize(_:)-3281j`` is a handy wrapper that will ultimately invoke ``ASN1Serializable/serialize(into:)`` on +the node in question. + +### Final Result + +We're done! Ultimately we've ended up with the following type. Don't worry too much about our use of ``ASN1ImplicitlyTaggable/defaultIdentifier`` here: we'll cover it +in [Implicit Tagging](#Implicit-Tagging). + +```swift +struct ECDSASignature: ASN1ImplicitlyTaggable { + static var defaultIdentifier: ASN1.ASN1Identifier { + .sequence + } + + var r: ArraySlice + var s: ArraySlice + + init(r: ArraySlice, s: ArraySlice) { + self.r = r + self.s = s + } + + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let r = try ArraySlice(asn1Encoded: &nodes) + let s = try ArraySlice(asn1Encoded: &nodes) + + return ECDSASignature(r: r, s: s) + } + } + + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.r) + try coder.serialize(self.s) + } + } +} +``` + +## Alternative Tagging + +ASN.1 supports overriding tags in two ways: implicit and explicit tagging. ``SwiftASN1`` supports both. + +It's often difficult to work out from an isolated snippet of ASN.1 definition whether a custom tag is explicit +or implicit. For clarity, this document will attempt to express on each line whether a tag is explicit or +implicit. + +### Implicit Tagging + +Implicit tagging replaces the usual tag for an object with a new tag. This makes it impossible to know the type +of the object without having the ASN.1 definition. It can also limit some extensibility. + +The principal advantage of implicit tagging is that there is no need to add the extra tag that explicit tagging requires. +This will save at least 2 bytes on each object, but may save more. + +An object that can be implicitly tagged should conform to ``ASN1ImplicitlyTaggable``. This will make a number of extra +methods available to users of that type, as well as forcing users to implement +``ASN1ImplicitlyTaggable/init(asn1Encoded:withIdentifier:)-iudo`` and ``ASN1ImplicitlyTaggable/serialize(into:withIdentifier:)``. +These two methods allow the caller to tell the type what its implicit tag is. The implementer is required to use that tag +for the top-level object (usually a constructed node). + +> Note: A few objects should not conform to ``ASN1ImplicitlyTaggable``. These objects are ones which, if they lost their tag, +> would not be able to correctly decode themselves. +> +> An example of such a type is a CHOICE type. For example: +> +> ``` +> CannotBeImplicitlyTagged ::= CHOICE { +> integerVal INTEGER +> boolVal BOOLEAN +> stringVal UTF8String } +> ``` +> +> As CHOICE types encode as whatever of the choice values is chosen, the tag is necessary to know which of these cases to decode. +> As a result, we cannot implicitly tag a CHOICE object: it'll be impossible to decode. This is true even if the various CHOICE +> fields are implicitly or explicitly tagged with custom tags: that tag will be obliterated if the CHOICE itself is implicitly +> tagged. + +Users can then decode an implicitly tagged object using one of the helper methods. For example, consider +this simple ASN.1 type: + +``` +ContainsImplicitTag ::= SEQUENCE { + value [0] IMPLICIT INTEGER } +``` + +We can decode it like so: + +```swift +init(asn1Encoded rootNode: ASN1.ASN1Node) throws { + self = try ASN1.sequence(rootNode, identifier: .sequence) { nodes in + let value = try Int64(asn1Encoded: &nodes, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false)) + + return ContainsImplicitTag(value: value) + } +} +``` + +We can also encode it similarly: + +```swift +func serialize(into coder: inout ASN1.Serializer) throws { + try coder.appendConstructedNode(identifier: .sequence) { coder in + try self.value.serialize(into: &coder, withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific, constructed: false)) + } +} +``` + +Note that we need to construct the ``ASN1/ASN1Identifier`` directly in this case. This is common whenever we have an implicit +tag that needs to be passed to an an object that is unconditionally present. It's often a wise idea to store this tag in a `static let` +for ease of access. + +There are a few helper functions for circumstances when an object has an implicit tag and is also either `OPTIONAL` or `DEFAULT`. For parsing, +those are: + +- ``ASN1/optionalImplicitlyTagged(_:tag:)`` +- ``ASN1/decodeDefault(_:identifier:defaultValue:)`` +- ``ASN1/decodeDefault(_:identifier:defaultValue:_:)`` + +For serializing, those are: + +- ``ASN1/Serializer/serializeOptionalImplicitlyTagged(_:)`` +- ``ASN1/Serializer/serializeOptionalImplicitlyTagged(_:withIdentifier:)`` + +Note that in a few cases you will see an object that is `OPTIONAL` or `DEFAULT` without a note of a tag. In this case, the implicit tag is +identical to the normal tag for this object. + +### Explicit Tagging + +Explicit tagging wraps an object in a new constructed object whose tag is equal to the explicit tag defined in the ASN.1 definition. This allows +the explicitly tagged object to still retain its original tag, helping the encoding to remain self-describing. Additionally, unlike with implicit +tagging, all nodes can be explicitly tagged, as the underlying representation of that node is not affected. + +As a worked example of explicit tagging, consider the following object: + +``` +ContainsExplicitTag ::= SEQUENCE { + value [0] EXPLICIT INTEGER } +``` + +We can decode it like so: + +```swift +init(asn1Encoded rootNode: ASN1.ASN1Node) throws { + self = try ASN1.sequence(rootNode, identifier: .sequence) { nodes in + let value = try ASN1.explicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { + try Int64(asn1Encoded: $0) + } + + return ContainsExplicitTag(value: value) + } +} +``` + +We can also encode it similarly: + +```swift +func serialize(into coder: inout ASN1.Serializer) throws { + try coder.appendConstructedNode(identifier: .sequence) { coder in + try coder.serialize(self.value, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } +} +``` + +As with the implicitly tagged case, most explicit tags are used in cases where the object is also either `OPTIONAL` or `DEFAULT`. We have a number +helper methods for those. For parsing: + +- ``ASN1/optionalExplicitlyTagged(_:tagNumber:tagClass:_:)`` +- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:)`` +- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:_:)`` + +For serializing, users are expected to implement the DEFAULT/OPTIONAL logic themselves. diff --git a/Sources/SwiftASN1/Docs.docc/index.md b/Sources/SwiftASN1/Docs.docc/index.md new file mode 100644 index 0000000..5855a89 --- /dev/null +++ b/Sources/SwiftASN1/Docs.docc/index.md @@ -0,0 +1,85 @@ +# ``SwiftASN1`` + +An implementation of ASN.1 types and DER serialization. + +## Overview + +ASN.1, and the DER encoding scheme, is a commonly used object serialization format. The most common use-cases for ASN.1 in +general computing are in the cryptographic space, but there are a number of use-cases in a wide range of fields. This module +provides an implementation of a number of ASN.1 types, as well as the DER serialization format for ASN.1. + +ASN.1 can be used abstractly to describe essentially any kind of object. ASN.1 objects are made up of either primitive or +composite (called "constructed") types. Individual scalar objects can be combined into aggregate types, and composed essentially +arbitrarily to form abstract object formats. + +Importantly, the ASN.1 object description does not define a specific encoding for these objects. Instead there are a wide range +of possible ways to serialize or deserialize an ASN.1 object. Some of the most prominent are BER (the Basic Encoding Rules), +CER (the Canonical Encoding Rules), DER (the Distinguished Encoding Rules), and XER (the XML Encoding Rules). For the cryptographic +use-case DER is the standard choice, as a given ASN.1 object can be encoded in only one way under DER. This makes signing and verifying +vastly easier, as it is at least in principle possible to perfectly reconstruct the serialization of a parsed object. + +This module provides several moving pieces: + +1. A high-level representation of an ASN.1 object, in the form of a tree of object nodes (``ASN1/ASN1Node``). +2. A DER parser that can construct the ASN.1 tree from serialized bytes (``ASN1/parse(_:)-41gug``). +3. A DER serializer that can construct serialized bytes from the ASN.1 tree (``ASN1/Serializer``). +4. A number of built-in ASN.1 types, representing common constructs. + +These moving pieces combine to provide support for the DER representation of ASN.1 suitable for a wide range of cryptographic uses. + +## Topics + +### Articles + +- + +### Parsing DER + +- ``ASN1/parse(_:)-41gug`` +- ``ASN1/parse(_:)-8ar01`` +- ``ASN1Parseable`` +- ``ASN1Serializable`` +- ``ASN1ImplicitlyTaggable`` +- ``ASN1/sequence(_:identifier:_:)`` +- ``ASN1/sequence(of:identifier:rootNode:)`` +- ``ASN1/sequence(of:identifier:nodes:)`` +- ``ASN1/set(_:identifier:_:)`` +- ``ASN1/decodeDefault(_:identifier:defaultValue:_:)`` +- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:_:)`` +- ``ASN1/decodeDefault(_:defaultValue:)`` +- ``ASN1/decodeDefault(_:identifier:defaultValue:)`` +- ``ASN1/decodeDefaultExplicitlyTagged(_:tagNumber:tagClass:defaultValue:)`` +- ``ASN1/optionalExplicitlyTagged(_:tagNumber:tagClass:_:)`` +- ``ASN1/optionalImplicitlyTagged(_:tag:)`` +- ``ASN1/explicitlyTagged(_:tagNumber:tagClass:_:)-6iqvq`` +- ``ASN1/explicitlyTagged(_:tagNumber:tagClass:_:)-4ystp`` + +### Serializing DER + +- ``ASN1/Serializer`` +- ``ASN1Serializable`` +- ``ASN1ImplicitlyTaggable`` + +### Representing ASN.1 types + +- ``ASN1/ASN1Node`` +- ``ASN1/ASN1NodeCollection`` +- ``ASN1/ASN1Identifier`` + +### Built-in ASN.1 types + +- ``ASN1IntegerRepresentable`` +- ``IntegerBytesCollection`` +- ``ASN1/GeneralizedTime`` +- ``ASN1/ASN1BitString`` +- ``ASN1/UTCTime`` +- ``ASN1/ASN1OctetString`` +- ``ASN1/ASN1Any`` +- ``ASN1/ASN1Null`` +- ``ASN1/ASN1ObjectIdentifier`` +- ``ASN1/ASN1UTF8String`` +- ``ASN1/ASN1PrintableString`` +- ``ASN1/ASN1BMPString`` +- ``ASN1/ASN1IA5String`` +- ``ASN1/ASN1TeletexString`` +- ``ASN1/ASN1UniversalString`` diff --git a/Sources/SwiftASN1/ECDSASignature.swift b/Sources/SwiftASN1/ECDSASignature.swift new file mode 100644 index 0000000..52a2037 --- /dev/null +++ b/Sources/SwiftASN1/ECDSASignature.swift @@ -0,0 +1,53 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + /// An ECDSA signature is laid out as follows: + /// + /// ECDSASignature ::= SEQUENCE { + /// r INTEGER, + /// s INTEGER + /// } + /// + /// This type is generic because our different backends want to use different bignum representations. + struct ECDSASignature: ASN1ImplicitlyTaggable { + static var defaultIdentifier: ASN1.ASN1Identifier { + .sequence + } + + var r: IntegerType + var s: IntegerType + + init(r: IntegerType, s: IntegerType) { + self.r = r + self.s = s + } + + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let r = try IntegerType(asn1Encoded: &nodes) + let s = try IntegerType(asn1Encoded: &nodes) + + return ECDSASignature(r: r, s: s) + } + } + + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.r) + try coder.serialize(self.s) + } + } + } +} diff --git a/Sources/SwiftASN1/Errors.swift b/Sources/SwiftASN1/Errors.swift new file mode 100644 index 0000000..0fa4148 --- /dev/null +++ b/Sources/SwiftASN1/Errors.swift @@ -0,0 +1,43 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +/// Errors that may be thrown while encoding or decoding ASN.1 objects. +public enum ASN1Error : Error { + /// The ASN.1 tag for this field is invalid or unsupported. + case invalidFieldIdentifier + + /// The ASN.1 tag for the parsed field does not match the required format. + case unexpectedFieldType + + /// An invalid ASN.1 object identifier was encountered. + case invalidObjectIdentifier + + /// The format of the parsed ASN.1 object does not match the format required for the data type + /// being decoded. + case invalidASN1Object + + /// An ASN.1 integer was decoded that does not use the minimum number of bytes for its encoding. + case invalidASN1IntegerEncoding + + /// An ASN.1 field was truncated and could not be decoded. + case truncatedASN1Field + + /// The encoding used for the field length is not supported. + case unsupportedFieldLength + + /// It was not possible to parse a string as a PEM document. + case invalidPEMDocument + + /// A string was invalid + case invalidStringRepresentation +} diff --git a/Sources/SwiftASN1/PEMDocument.swift b/Sources/SwiftASN1/PEMDocument.swift new file mode 100644 index 0000000..b2faa93 --- /dev/null +++ b/Sources/SwiftASN1/PEMDocument.swift @@ -0,0 +1,116 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +#if canImport(Foundation) +import Foundation + +extension ASN1 { + /// A PEM document is some data, and a discriminator type that is used to advertise the content. + struct PEMDocument { + private static let lineLength = 64 + + var type: String + + var derBytes: Data + + init(pemString: String) throws { + // A PEM document looks like this: + // + // -----BEGIN ----- + // + // -----END ----- + // + // This function attempts to parse this string as a PEM document, and returns the discriminator type + // and the base64 decoded bytes. + var lines = pemString.split { $0.isNewline }[...] + guard let first = lines.first, let last = lines.last else { + throw ASN1Error.invalidPEMDocument + } + + guard let discriminator = first.pemStartDiscriminator, discriminator == last.pemEndDiscriminator else { + throw ASN1Error.invalidPEMDocument + } + + // All but the last line must be 64 bytes. The force unwrap is safe because we require the lines to be + // greater than zero. + lines = lines.dropFirst().dropLast() + guard lines.count > 0, + lines.dropLast().allSatisfy({ $0.utf8.count == PEMDocument.lineLength }), + lines.last!.utf8.count <= PEMDocument.lineLength else { + throw ASN1Error.invalidPEMDocument + } + + guard let derBytes = Data(base64Encoded: lines.joined()) else { + throw ASN1Error.invalidPEMDocument + } + + self.type = discriminator + self.derBytes = derBytes + } + + init(type: String, derBytes: Data) { + self.type = type + self.derBytes = derBytes + } + + var pemString: String { + var encoded = self.derBytes.base64EncodedString()[...] + let pemLineCount = (encoded.utf8.count + PEMDocument.lineLength) / PEMDocument.lineLength + var pemLines = [Substring]() + pemLines.reserveCapacity(pemLineCount + 2) + + pemLines.append("-----BEGIN \(self.type)-----") + + while encoded.count > 0 { + let prefixIndex = encoded.index(encoded.startIndex, offsetBy: PEMDocument.lineLength, limitedBy: encoded.endIndex) ?? encoded.endIndex + pemLines.append(encoded[.. String? { + var utf8Bytes = self.utf8[...] + + // We want to split this sequence into three parts: the prefix, the middle, and the end + let prefixSize = expectedPrefix.utf8.count + let suffixSize = expectedSuffix.utf8.count + + let prefix = utf8Bytes.prefix(prefixSize) + utf8Bytes = utf8Bytes.dropFirst(prefixSize) + let suffix = utf8Bytes.suffix(suffixSize) + utf8Bytes = utf8Bytes.dropLast(suffixSize) + + guard prefix.elementsEqual(expectedPrefix.utf8), suffix.elementsEqual(expectedSuffix.utf8) else { + return nil + } + + return String(utf8Bytes) + } +} + +#endif diff --git a/Sources/SwiftASN1/PKCS8PrivateKey.swift b/Sources/SwiftASN1/PKCS8PrivateKey.swift new file mode 100644 index 0000000..4191246 --- /dev/null +++ b/Sources/SwiftASN1/PKCS8PrivateKey.swift @@ -0,0 +1,97 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + // A PKCS#8 private key is one of two formats, depending on the version: + // + // For PKCS#8 we need the following for the private key: + // + // PrivateKeyInfo ::= SEQUENCE { + // version Version, + // privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, + // privateKey PrivateKey, + // attributes [0] IMPLICIT Attributes OPTIONAL } + // + // Version ::= INTEGER + // + // PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier + // + // PrivateKey ::= OCTET STRING + // + // Attributes ::= SET OF Attribute + // + // We disregard the attributes because we don't support them anyway. + // + // The private key octet string contains (surprise!) a SEC1-encoded private key! So we recursively invoke the + // ASN.1 parser and go again. + struct PKCS8PrivateKey: ASN1ImplicitlyTaggable { + static var defaultIdentifier: ASN1.ASN1Identifier { + return .sequence + } + + var algorithm: RFC5480AlgorithmIdentifier + + var privateKey: ASN1.SEC1PrivateKey + + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let version = try Int(asn1Encoded: &nodes) + guard version == 0 else { + throw ASN1Error.invalidASN1Object + } + + let algorithm = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes) + let privateKeyBytes = try ASN1.ASN1OctetString(asn1Encoded: &nodes) + + // We ignore the attributes + _ = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in } + + let sec1PrivateKeyNode = try ASN1.parse(privateKeyBytes.bytes) + let sec1PrivateKey = try ASN1.SEC1PrivateKey(asn1Encoded: sec1PrivateKeyNode) + if let innerAlgorithm = sec1PrivateKey.algorithm, innerAlgorithm != algorithm { + throw ASN1Error.invalidASN1Object + } + + return try .init(algorithm: algorithm, privateKey: sec1PrivateKey) + } + } + + private init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: ASN1.SEC1PrivateKey) throws { + self.privateKey = privateKey + self.algorithm = algorithm + } + + init(algorithm: ASN1.RFC5480AlgorithmIdentifier, privateKey: [UInt8], publicKey: [UInt8]) { + self.algorithm = algorithm + + // We nil out the private key here. I don't really know why we do this, but OpenSSL does, and it seems + // safe enough to do: it certainly avoids the possibility of disagreeing on what it is! + self.privateKey = ASN1.SEC1PrivateKey(privateKey: privateKey, algorithm: nil, publicKey: publicKey) + } + + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(0) // version + try coder.serialize(self.algorithm) + + // Here's a weird one: we recursively serialize the private key, and then turn the bytes into an octet string. + var subCoder = ASN1.Serializer() + try subCoder.serialize(self.privateKey) + let serializedKey = ASN1.ASN1OctetString(contentBytes: subCoder.serializedBytes[...]) + + try coder.serialize(serializedKey) + } + } + } +} diff --git a/Sources/SwiftASN1/SEC1PrivateKey.swift b/Sources/SwiftASN1/SEC1PrivateKey.swift new file mode 100644 index 0000000..6a075d1 --- /dev/null +++ b/Sources/SwiftASN1/SEC1PrivateKey.swift @@ -0,0 +1,104 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + // For private keys, SEC 1 uses: + // + // ECPrivateKey ::= SEQUENCE { + // version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), + // privateKey OCTET STRING, + // parameters [0] EXPLICIT ECDomainParameters OPTIONAL, + // publicKey [1] EXPLICIT BIT STRING OPTIONAL + // } + struct SEC1PrivateKey: ASN1ImplicitlyTaggable { + static var defaultIdentifier: ASN1.ASN1Identifier { + return .sequence + } + + var algorithm: ASN1.RFC5480AlgorithmIdentifier? + + var privateKey: ASN1.ASN1OctetString + + var publicKey: ASN1.ASN1BitString? + + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let version = try Int(asn1Encoded: &nodes) + guard 1 == version else { + throw ASN1Error.invalidASN1Object + } + + let privateKey = try ASN1OctetString(asn1Encoded: &nodes) + let parameters = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + return try ASN1.ASN1ObjectIdentifier(asn1Encoded: node) + } + let publicKey = try ASN1.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in + return try ASN1.ASN1BitString(asn1Encoded: node) + } + + return try .init(privateKey: privateKey, algorithm: parameters, publicKey: publicKey) + } + } + + private init(privateKey: ASN1.ASN1OctetString, algorithm: ASN1.ASN1ObjectIdentifier?, publicKey: ASN1.ASN1BitString?) throws { + self.privateKey = privateKey + self.publicKey = publicKey + self.algorithm = try algorithm.map { algorithmOID in + switch algorithmOID { + case ASN1ObjectIdentifier.NamedCurves.secp256r1: + return .ecdsaP256 + case ASN1ObjectIdentifier.NamedCurves.secp384r1: + return .ecdsaP384 + case ASN1ObjectIdentifier.NamedCurves.secp521r1: + return .ecdsaP521 + default: + throw ASN1Error.invalidASN1Object + } + } + } + + init(privateKey: [UInt8], algorithm: RFC5480AlgorithmIdentifier?, publicKey: [UInt8]) { + self.privateKey = ASN1OctetString(contentBytes: privateKey[...]) + self.algorithm = algorithm + self.publicKey = ASN1BitString(bytes: publicKey[...]) + } + + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(1) // version + try coder.serialize(self.privateKey) + + if let algorithm = self.algorithm { + let oid: ASN1.ASN1ObjectIdentifier + switch algorithm { + case .ecdsaP256: + oid = ASN1ObjectIdentifier.NamedCurves.secp256r1 + case .ecdsaP384: + oid = ASN1ObjectIdentifier.NamedCurves.secp384r1 + case .ecdsaP521: + oid = ASN1ObjectIdentifier.NamedCurves.secp521r1 + default: + throw ASN1Error.invalidASN1Object + } + + try coder.serialize(oid, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } + + if let publicKey = self.publicKey { + try coder.serialize(publicKey, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific) + } + } + } + } +} diff --git a/Sources/SwiftASN1/SubjectPublicKeyInfo.swift b/Sources/SwiftASN1/SubjectPublicKeyInfo.swift new file mode 100644 index 0000000..b3f3fd6 --- /dev/null +++ b/Sources/SwiftASN1/SubjectPublicKeyInfo.swift @@ -0,0 +1,122 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension ASN1 { + struct SubjectPublicKeyInfo: ASN1ImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1.ASN1Identifier { + .sequence + } + + var algorithmIdentifier: RFC5480AlgorithmIdentifier + + var key: ASN1.ASN1BitString + + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + // The SPKI block looks like this: + // + // SubjectPublicKeyInfo ::= SEQUENCE { + // algorithm AlgorithmIdentifier, + // subjectPublicKey BIT STRING + // } + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let algorithmIdentifier = try ASN1.RFC5480AlgorithmIdentifier(asn1Encoded: &nodes) + let key = try ASN1.ASN1BitString(asn1Encoded: &nodes) + + return SubjectPublicKeyInfo(algorithmIdentifier: algorithmIdentifier, key: key) + } + } + + private init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: ASN1.ASN1BitString) { + self.algorithmIdentifier = algorithmIdentifier + self.key = key + } + + internal init(algorithmIdentifier: RFC5480AlgorithmIdentifier, key: [UInt8]) { + self.algorithmIdentifier = algorithmIdentifier + self.key = ASN1BitString(bytes: key[...]) + } + + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.algorithmIdentifier) + try coder.serialize(self.key) + } + } + } + + struct RFC5480AlgorithmIdentifier: ASN1ImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1.ASN1Identifier { + .sequence + } + + var algorithm: ASN1.ASN1ObjectIdentifier + + var parameters: ASN1.ASN1Any? + +// case ecdsaP256 +// case ecdsaP384 +// case ecdsaP521 + + init(algorithm: ASN1.ASN1ObjectIdentifier, parameters: ASN1.ASN1Any?) { + self.algorithm = algorithm + self.parameters = parameters + } + + init(asn1Encoded rootNode: ASN1.ASN1Node, withIdentifier identifier: ASN1.ASN1Identifier) throws { + // The AlgorithmIdentifier block looks like this. + // + // AlgorithmIdentifier ::= SEQUENCE { + // algorithm OBJECT IDENTIFIER, + // parameters ANY DEFINED BY algorithm OPTIONAL + // } + // + // ECParameters ::= CHOICE { + // namedCurve OBJECT IDENTIFIER + // -- implicitCurve NULL + // -- specifiedCurve SpecifiedECDomain + // } + // + // We don't bother with helpers: we just try to decode it directly. + self = try ASN1.sequence(rootNode, identifier: identifier) { nodes in + let algorithmOID = try ASN1.ASN1ObjectIdentifier(asn1Encoded: &nodes) + + let parameters = nodes.next().map { ASN1.ASN1Any(asn1Encoded: $0) } + + return .init(algorithm: algorithmOID, parameters: parameters) + } + } + + func serialize(into coder: inout ASN1.Serializer, withIdentifier identifier: ASN1.ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.algorithm) + if let parameters = self.parameters { + try coder.serialize(parameters) + } + } + } + } +} + + +// MARK: Algorithm Identifier Statics +extension ASN1.RFC5480AlgorithmIdentifier { + static let ecdsaP256 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp256r1)) + + static let ecdsaP384 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp384r1)) + + static let ecdsaP521 = ASN1.RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1.ASN1ObjectIdentifier.NamedCurves.secp521r1)) +} diff --git a/Tests/SwiftASN1Tests/ASN1StringTests.swift b/Tests/SwiftASN1Tests/ASN1StringTests.swift new file mode 100644 index 0000000..70506b7 --- /dev/null +++ b/Tests/SwiftASN1Tests/ASN1StringTests.swift @@ -0,0 +1,178 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import XCTest + +@testable import SwiftASN1 + +final class ASN1StringTests: XCTestCase { + private func assertRoundTrips(_ value: ASN1Object) throws { + var serializer = ASN1.Serializer() + try serializer.serialize(value) + let parsed = try ASN1Object(asn1Encoded: serializer.serializedBytes) + XCTAssertEqual(parsed, value) + } + + func testUTF8StringEncoding() throws { + var serializer = ASN1.Serializer() + let originalString = ASN1.ASN1UTF8String(contentBytes: [1, 2, 3, 4]) + try serializer.serialize(originalString) + XCTAssertEqual(serializer.serializedBytes, [12, 4, 1, 2, 3, 4]) + } + + func testUTF8StringRoundTrips() throws { + try self.assertRoundTrips(ASN1.ASN1UTF8String(contentBytes: [1, 2, 3, 4])) + } + + func testUTF8StringContiguousBytes() throws { + let string = ASN1.ASN1UTF8String(contentBytes: [1, 2, 3, 4]) + string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) } + } + + func testTeletexStringEncoding() throws { + var serializer = ASN1.Serializer() + let originalString = ASN1.ASN1TeletexString(contentBytes: [1, 2, 3, 4]) + try serializer.serialize(originalString) + XCTAssertEqual(serializer.serializedBytes, [20, 4, 1, 2, 3, 4]) + } + + func testTeletexStringRoundTrips() throws { + try self.assertRoundTrips(ASN1.ASN1TeletexString(contentBytes: [1, 2, 3, 4])) + } + + func testTeletexStringContiguousBytes() throws { + let string = ASN1.ASN1TeletexString(contentBytes: [1, 2, 3, 4]) + string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) } + } + + func testPrintableStringEncoding() throws { + var serializer = ASN1.Serializer() + let originalString = try ASN1.ASN1PrintableString(contentBytes: [0x54, 0x65, 0x73, 0x74]) + try serializer.serialize(originalString) + XCTAssertEqual(serializer.serializedBytes, [19, 4, 0x54, 0x65, 0x73, 0x74]) + } + + func testPrintableStringRoundTrips() throws { + try self.assertRoundTrips(ASN1.ASN1PrintableString(contentBytes: [0x54, 0x65, 0x73, 0x74])) + } + + func testPrintableStringContiguousBytes() throws { + let string = try ASN1.ASN1PrintableString(contentBytes: [0x54, 0x65, 0x73, 0x74]) + string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([0x54, 0x65, 0x73, 0x74])) } + } + + func testUniversalStringEncoding() throws { + var serializer = ASN1.Serializer() + let originalString = ASN1.ASN1UniversalString(contentBytes: [1, 2, 3, 4]) + try serializer.serialize(originalString) + XCTAssertEqual(serializer.serializedBytes, [28, 4, 1, 2, 3, 4]) + } + + func testUniversalStringRoundTrips() throws { + try self.assertRoundTrips(ASN1.ASN1UniversalString(contentBytes: [1, 2, 3, 4])) + } + + func testUniversalStringContiguousBytes() throws { + let string = ASN1.ASN1UniversalString(contentBytes: [1, 2, 3, 4]) + string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) } + } + + func testBMPStringEncoding() throws { + var serializer = ASN1.Serializer() + let originalString = ASN1.ASN1BMPString(contentBytes: [1, 2, 3, 4]) + try serializer.serialize(originalString) + XCTAssertEqual(serializer.serializedBytes, [30, 4, 1, 2, 3, 4]) + } + + func testBMPStringRoundTrips() throws { + try self.assertRoundTrips(ASN1.ASN1BMPString(contentBytes: [1, 2, 3, 4])) + } + + func testBMPStringContiguousBytes() throws { + let string = ASN1.ASN1BMPString(contentBytes: [1, 2, 3, 4]) + string.withUnsafeBytes { XCTAssertTrue($0.elementsEqual([1, 2, 3, 4])) } + } + + func testUTF8StringCanCreateAString() throws { + let string = "hello, world!" + let utf8String = ASN1.ASN1UTF8String(string) + let newString = String(utf8String) + XCTAssertEqual(newString, string) + } + + func testPrintableStringCanCreateAString() throws { + let string = "hello, world" + let utf8String = try ASN1.ASN1PrintableString(string) + let newString = String(utf8String) + XCTAssertEqual(newString, string) + } + + func testIA5StringCanCreateAString() throws { + let string = "hello, world" + let ia5String = try ASN1.ASN1IA5String(string) + let newString = String(ia5String) + XCTAssertEqual(newString, string) + } + + func testPrintableStringRejectsCharacters() throws { + let allBytes = (UInt8(0)...UInt8.max) + + let invalidBytes = (UInt8(0)...UInt8(255)).filter { + switch $0 { + case UInt8(ascii: "a")...UInt8(ascii: "z"), + UInt8(ascii: "A")...UInt8(ascii: "Z"), + UInt8(ascii: "0")...UInt8(ascii: "9"), + UInt8(ascii: "'"), UInt8(ascii: "("), + UInt8(ascii: ")"), UInt8(ascii: "+"), + UInt8(ascii: "-"), UInt8(ascii: "?"), + UInt8(ascii: ":"), UInt8(ascii: "/"), + UInt8(ascii: "="), UInt8(ascii: " "), + UInt8(ascii: ","), UInt8(ascii: "."): + return false + default: + return true + } + } + + let validBytes = allBytes.filter { !invalidBytes.contains($0) } + + for byte in invalidBytes { + XCTAssertThrowsError(try ASN1.ASN1PrintableString(contentBytes: [byte])) + XCTAssertThrowsError(try ASN1.ASN1PrintableString(String(UnicodeScalar(byte)))) + XCTAssertThrowsError(try ASN1.ASN1PrintableString(asn1Encoded: [0x13, 1, byte])) + } + + for byte in validBytes { + XCTAssertNoThrow(try ASN1.ASN1PrintableString(contentBytes: [byte])) + XCTAssertNoThrow(try ASN1.ASN1PrintableString(String(UnicodeScalar(byte)))) + XCTAssertNoThrow(try ASN1.ASN1PrintableString(asn1Encoded: [0x13, 1, byte])) + } + } + + func testIA5StringRejectsCharacters() throws { + let invalidBytes = (UInt8(128)...(UInt8.max)) + let validBytes = (UInt8(0).. = [ + 48, 129, 137, 2, 129, 129, 0, 208, 17, 195, 252, 170, 12, 42, 228, 152, + 70, 130, 93, 102, 40, 199, 142, 89, 182, 244, 88, 82, 164, 36, 168, 248, + 78, 249, 184, 68, 85, 134, 40, 54, 32, 254, 159, 133, 155, 203, 199, 192, + 244, 136, 10, 165, 61, 28, 159, 157, 28, 93, 147, 203, 67, 58, 89, 92, + 21, 149, 254, 145, 37, 210, 70, 178, 186, 117, 179, 215, 27, 197, 247, + 63, 239, 131, 221, 65, 75, 44, 34, 21, 35, 134, 80, 78, 217, 17, 101, 64 + , 64, 155, 128, 218, 112, 229, 73, 94, 68, 31, 69, 46, 113, 3, 167, 125, + 234, 50, 7, 107, 238, 124, 23, 137, 128, 147, 141, 221, 56, 65, 41, 29, + 83, 121, 151, 37, 138, 197, 127, 2, 3, 1, 0, 1 + ] + XCTAssertEqual(spki.key.bytes, expectedKey) + } + + func testSPKIWithUnsupportedCurve() throws { + // This is an EC SPKI object with an unsupported named curve. + let b64SPKI = "MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEzN09Sbb+mhMIlUbOdoIoND8lNcoQPd/yZDjQi1IDyDQEvVvz1yhi5J0FPLAlM3hE2o/a+rASUz2UP4fX5Cpnxw==" + let decodedSPKI = Array(Data(base64Encoded: b64SPKI)!) + + let parsed = try ASN1.parse(decodedSPKI) + let spki = try ASN1.SubjectPublicKeyInfo(asn1Encoded: parsed) + XCTAssertEqual(spki.algorithmIdentifier.algorithm, .AlgorithmIdentifier.idEcPublicKey) + XCTAssertEqual(try ASN1.ASN1ObjectIdentifier(asn1Any: spki.algorithmIdentifier.parameters!), [1, 3, 132, 0, 10]) + + let expectedKey: ArraySlice = [ + 4, 204, 221, 61, 73, 182, 254, 154, 19, 8, 149, 70, 206, 118, 130, 40, + 52, 63, 37, 53, 202, 16, 61, 223, 242, 100, 56, 208, 139, 82, 3, 200, + 52, 4, 189, 91, 243, 215, 40, 98, 228, 157, 5, 60, 176, 37, 51, 120, 68, + 218, 143, 218, 250, 176, 18, 83, 61, 148, 63, 135, 215, 228, 42, 103, + 199 + ] + XCTAssertEqual(spki.key.bytes, expectedKey) + } + + func testSEC1PrivateKeyWithUnknownVersion() throws { + // This is the beginning of a SEC1 private key with hypothetical version number 5. We should reject it + let weirdSEC1: [UInt8] = [0x30, 0x03, 0x02, 0x01, 0x05] + + let parsed = try ASN1.parse(weirdSEC1) + XCTAssertThrowsError(try ASN1.SEC1PrivateKey(asn1Encoded: parsed)) { error in + XCTAssertEqual(error as? ASN1Error, .invalidASN1Object) + } + } + + func testSEC1PrivateKeyUnsupportedKeyType() throws { + // This is an EC SPKI object with an unsupported named curve. + let b64SEC1 = "MHQCAQEEINIuVmNF7g1wNCJWXDpgL+09jATtaS1n0SxqqQneHi+woAcGBSuBBAAKoUQDQgAEB7v/p7gvuV0aDx02EF6a+pr563p+FzRJXI+COWHdr+XRcjg6vEi4n3Jj7ksmEg4t1x6E1xFyTvF3eV/B/XVXbw==" + let decodedSEC1 = Array(Data(base64Encoded: b64SEC1)!) + + let parsed = try ASN1.parse(decodedSEC1) + XCTAssertThrowsError(try ASN1.SEC1PrivateKey(asn1Encoded: parsed)) { error in + XCTAssertEqual(error as? ASN1Error, .invalidASN1Object) + } + } + + func testPKCS8KeyWithNonMatchingKeyOIDS() throws { + // This is a stubbed PKCS8 key with mismatched OIDs in the inner and outer payload. We have to serialize it out, sadly. + var serializer = ASN1.Serializer() + try serializer.appendConstructedNode(identifier: .sequence) { coder in + try coder.serialize(0) + try coder.serialize(ASN1.RFC5480AlgorithmIdentifier.ecdsaP256) + + var subCoder = ASN1.Serializer() + try subCoder.serialize(ASN1.SEC1PrivateKey(privateKey: [], algorithm: .ecdsaP384, publicKey: [])) // We won't notice these are empty either, but we will notice the algo mismatch. + let serializedKey = ASN1.ASN1OctetString(contentBytes: subCoder.serializedBytes[...]) + + try coder.serialize(serializedKey) + } + + let parsed = try ASN1.parse(serializer.serializedBytes) + XCTAssertThrowsError(try ASN1.PKCS8PrivateKey(asn1Encoded: parsed)) { error in + XCTAssertEqual(error as? ASN1Error, .invalidASN1Object) + } + } + + func testNodeSlices() throws { + // This is an SPKI object for RSA instead of EC. This is a 1024-bit RSA key, so hopefully no-one will think to use it. + let rsaSPKI = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQEcP8qgwq5JhGgl1mKMeOWbb0WFKkJKj4Tvm4RFWGKDYg/p+Fm8vHwPSICqU9HJ+dHF2Ty0M6WVwVlf6RJdJGsrp1s9cbxfc/74PdQUssIhUjhlBO2RFlQECbgNpw5UleRB9FLnEDp33qMgdr7nwXiYCTjd04QSkdU3mXJYrFfwIDAQAB" + let decodedSPKI = Array(Data(base64Encoded: rsaSPKI)!) + + let parsed = try ASN1.parse(decodedSPKI) + XCTAssertEqual(parsed.encodedBytes, decodedSPKI[...]) + + guard case .constructed(let firstLayerChildren) = parsed.content else { + XCTFail("Unexpected node") + return + } + var iterator = firstLayerChildren.makeIterator() + guard let algorithmId = iterator.next(), let key = iterator.next() else { + XCTFail("Invalid number of children") + return + } + XCTAssertNil(iterator.next()) + + // Initial offset of the algorithm ID is 3 (3 bytes of encoding for the parent sequence), + // the sequence itself is 13 bytes long, and there are 2 bytes of length and tag. End offset + // is therefore 3 + 13 + 2 == 18. + XCTAssertEqual(algorithmId.encodedBytes, decodedSPKI[3..<18]) + + // Initial offset of the key immediately follows the algorithm ID, so it's 18. It contains the bytes + // up to the end. + XCTAssertEqual(key.encodedBytes, decodedSPKI[18...]) + + guard case .constructed(let algorithmIDChildren) = algorithmId.content else { + XCTFail("Invalid content for algorithm ID node") + return + } + iterator = algorithmIDChildren.makeIterator() + + guard let oid = iterator.next(), let null = iterator.next() else { + XCTFail("Invalid algorithm ID content") + return + } + + // The oid begins at offset 5: 3 bytes for the outer sequence tag/length, 2 bytes for the inner sequence tag/length. + // The oid itself has a 2 byte tag/length combo and a 9 byte length, leaving its end index as 5 + 2 + 9 == 16 + XCTAssertEqual(oid.encodedBytes, decodedSPKI[5..<16]) + + // The null is 2 bytes long. + XCTAssertEqual(null.encodedBytes, decodedSPKI[16..<18]) + } + + func testOptionalImplicitlyTaggedWithCustomTag() throws { + var serializer = ASN1.Serializer() + try serializer.appendConstructedNode(identifier: .sequence) { serializer in + try serializer.serializeOptionalImplicitlyTagged(1, withIdentifier: ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: false)) + } + let bytes = serializer.serializedBytes + + XCTAssertEqual(bytes, [0x30, 0x03, 0x81, 0x1, 0x1]) + + let parseResult = try ASN1.parse(bytes) + let int: Int? = try ASN1.sequence(parseResult, identifier: .sequence) { nodes in + try ASN1.optionalImplicitlyTagged(&nodes, tag: ASN1.ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific, constructed: false)) + } + XCTAssertEqual(int, 1) + } +} diff --git a/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift b/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift new file mode 100644 index 0000000..d3c12ac --- /dev/null +++ b/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift @@ -0,0 +1,180 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCrypto open source project +// +// Copyright (c) 2021 Apple Inc. and the SwiftCrypto project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCrypto project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import XCTest + +@testable import SwiftASN1 + +final class GeneralizedTimeTests: XCTestCase { + private func assertRoundTrips(_ value: ASN1Object) throws { + var serializer = ASN1.Serializer() + try serializer.serialize(value) + let parsed = try ASN1Object(asn1Encoded: serializer.serializedBytes) + XCTAssertEqual(parsed, value) + } + + func testSimpleGeneralizedTimeTestVectors() throws { + // This is a small set of generalized time test vectors derived from the ASN.1 docs. + // We store the byte payload here as a string. + let vectors: [(String, ASN1.GeneralizedTime?)] = [ + // Valid representations + ("19920521000000Z", try .init(year: 1992, month: 5, day: 21, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), + ("19920622123421Z", try .init(year: 1992, month: 6, day: 22, hours: 12, minutes: 34, seconds: 21, fractionalSeconds: 0)), + ("19920722132100.3Z", try .init(year: 1992, month: 7, day: 22, hours: 13, minutes: 21, seconds: 0, fractionalSeconds: 0.3)), + ("19851106210627.3Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.3)), + ("19851106210627.14159Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.14159)), + ("20210131000000Z", try .init(year: 2021, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in January + ("20210228000000Z", try .init(year: 2021, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2021 + ("20200229000000Z", try .init(year: 2020, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2020 + ("21000228000000Z", try .init(year: 2100, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2100 + ("20000229000000Z", try .init(year: 2000, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2000 + ("20210331000000Z", try .init(year: 2021, month: 3, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in March + ("20210430000000Z", try .init(year: 2021, month: 4, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in April + ("20210531000000Z", try .init(year: 2021, month: 5, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in May + ("20210630000000Z", try .init(year: 2021, month: 6, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in June + ("20210731000000Z", try .init(year: 2021, month: 7, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in July + ("20210831000000Z", try .init(year: 2021, month: 8, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in August + ("20210930000000Z", try .init(year: 2021, month: 9, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in September + ("20211031000000Z", try .init(year: 2021, month: 10, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in October + ("20211130000000Z", try .init(year: 2021, month: 11, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in November + ("20211231000000Z", try .init(year: 2021, month: 12, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in December + + // Invalid representations + ("19920520240000Z", nil), // midnight may not be 2400000 + ("19920622123421.0Z", nil), // spurious trailing zeros + ("19920722132100.30Z", nil), // spurious trailing zeros + ("19851106210627,3Z", nil), // comma as decimal separator + ("1985110621.14159Z", nil), // missing minutes and seconds + ("198511062106.14159Z", nil), // missing seconds + ("19851106210627.3", nil), // missing trailing Z + ("19851106210627.3-0500", nil), // explicit time zone + ("20211300000000Z", nil), // there is no 13th month + ("20210000000000Z", nil), // there is no zeroth month + ("20210100000000Z", nil), // there is no zeroth day + ("20210101000062Z", nil), // 62nd second is not allowed + ("20210101236000Z", nil), // 60th minute is not allowed + ("20210132000000Z", nil), // only 31 days in January + ("20210229000000Z", nil), // only 28 days in February 2021 + ("20200230000000Z", nil), // only 29 days in February 2020 + ("21000229000000Z", nil), // only 28 days in February 2100 + ("20000230000000Z", nil), // only 29 days in February 2000 + ("20210332000000Z", nil), // only 31 days in March + ("20210431000000Z", nil), // only 30 days in April + ("20210532000000Z", nil), // only 31 days in May + ("20210631000000Z", nil), // only 30 days in June + ("20210732000000Z", nil), // only 31 days in July + ("20210832000000Z", nil), // only 31 days in August + ("20210931000000Z", nil), // only 30 days in September + ("20211032000000Z", nil), // only 31 days in October + ("20211131000000Z", nil), // only 30 days in November + ("20211232000000Z", nil), // only 31 days in December + ("20200101000000.9223372036854775808Z", nil), // Fractional part will overflow a 64-bit integer by adding + ("20200101000000.92233720368547758071Z", nil), // Fractional part will overflow a 64-bit integer by multiplication + ] + + for (stringRepresentation, expectedResult) in vectors { + var serialized = Array() + serialized.writeIdentifier(ASN1.ASN1Identifier.generalizedTime) + serialized.append(UInt8(stringRepresentation.utf8.count)) + serialized.append(contentsOf: stringRepresentation.utf8) + + let result = try? ASN1.GeneralizedTime(asn1Encoded: serialized) + XCTAssertEqual(result, expectedResult) + + if let expected = expectedResult { + try self.assertRoundTrips(expected) + } + } + } + + func testCreatingOutOfBoundsValuesViaInitFails() throws { + func mustFail(_ code: @autoclosure () throws -> ASN1.GeneralizedTime) { + XCTAssertThrowsError(try code()) + } + + mustFail(try .init(year: -1, month: 1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid year, negative + mustFail(try .init(year: 2000, month: 0, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, zero. + mustFail(try .init(year: 2000, month: -1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, negative. + mustFail(try .init(year: 2000, month: 13, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, too large. + mustFail(try .init(year: 2000, month: 1, day: 0, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid day, zero. + mustFail(try .init(year: 2000, month: 1, day: -1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid day, negative. + mustFail(try .init(year: 2000, month: 1, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in January + mustFail(try .init(year: 2021, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 28 days in February 2021 + mustFail(try .init(year: 2020, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 29 days in February 2020 + mustFail(try .init(year: 2100, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 28 days in February 2100 + mustFail(try .init(year: 2000, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 29 days in February 2000 + mustFail(try .init(year: 2000, month: 3, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in March + mustFail(try .init(year: 2000, month: 4, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in April + mustFail(try .init(year: 2000, month: 5, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in May + mustFail(try .init(year: 2000, month: 6, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in June + mustFail(try .init(year: 2000, month: 7, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in July + mustFail(try .init(year: 2000, month: 8, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in August + mustFail(try .init(year: 2000, month: 9, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in September + mustFail(try .init(year: 2000, month: 10, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in October + mustFail(try .init(year: 2000, month: 11, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in November + mustFail(try .init(year: 2000, month: 11, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in December + mustFail(try .init(year: 2000, month: 1, day: 1, hours: -1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid hour, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 24, minutes: 0, seconds: 0, fractionalSeconds: 0)) // Invalid hour, 24 + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: -1, seconds: 1, fractionalSeconds: 0)) // Invalid minute, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 60, seconds: 0, fractionalSeconds: 0)) // Invalid minute, 60 + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: -1, fractionalSeconds: 0)) // Invalid second, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 62, fractionalSeconds: 0)) // Invalid second, 62 (we allow some leap seconds) + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: -0.5)) // Invalid fractional seconds, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 1.1)) // Invalid fractional seconds, greater than one + } + + func testTruncatedRepresentationsRejected() throws { + func mustNotDeserialize(_ stringRepresentation: Substring) { + var serialized = Array() + serialized.writeIdentifier(ASN1.ASN1Identifier.generalizedTime) + serialized.append(UInt8(stringRepresentation.utf8.count)) + serialized.append(contentsOf: stringRepresentation.utf8) + + XCTAssertThrowsError(try ASN1.GeneralizedTime(asn1Encoded: serialized)) + } + + func deserializes(_ stringRepresentation: Substring) { + var serialized = Array() + serialized.writeIdentifier(ASN1.ASN1Identifier.generalizedTime) + serialized.append(UInt8(stringRepresentation.utf8.count)) + serialized.append(contentsOf: stringRepresentation.utf8) + + XCTAssertNoThrow(try ASN1.GeneralizedTime(asn1Encoded: serialized)) + } + + // Anything that doesn't end up in a Z must fail to deserialize. + let string = Substring("19851106210627.14159Z") + for distance in 0..() + invalidBytes.writeIdentifier(ASN1.ASN1Identifier.integer) // generalizedTime isn't an integer + invalidBytes.append(UInt8(rawValue.count)) + invalidBytes.append(contentsOf: rawValue) + + XCTAssertThrowsError(try ASN1.GeneralizedTime(asn1Encoded: invalidBytes)) + } +}