From cf59bc50c7f519c8d4ead392bb4972b6fea4f3fd Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Tue, 31 Jan 2023 19:05:31 +0100 Subject: [PATCH 1/4] Cryptographic Message Syntax ASN.1 de/serialisation --- .../CMSContentInfo.swift | 52 ++++- .../CMSEncapsulatedContentInfo.swift | 33 ++- .../CMSIssuerAndSerialNumber.swift | 29 ++- .../CMSSignedData.swift | 169 ++++++++++++++- .../CMSSignerIdentifier.swift | 29 ++- .../CMSSignerInfo.swift | 87 +++++++- Tests/X509Tests/CMSTests.swift | 198 ++++++++++++++++++ 7 files changed, 587 insertions(+), 10 deletions(-) create mode 100644 Tests/X509Tests/CMSTests.swift diff --git a/Sources/X509/CryptographicMessageSyntax/CMSContentInfo.swift b/Sources/X509/CryptographicMessageSyntax/CMSContentInfo.swift index f81924d..55a29fd 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSContentInfo.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSContentInfo.swift @@ -14,6 +14,17 @@ import SwiftASN1 +extension ASN1ObjectIdentifier { + /// Cryptographic Message Syntax (CMS) Signed Data. + /// + /// ASN.1 definition: + /// ``` + /// id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) + /// us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } + /// ``` + static let cmsSignedData: ASN1ObjectIdentifier = [1, 2, 840, 113549, 1, 7, 2] +} + /// ``ContentInfo`` is defined in ASN.1 as: /// ``` /// ContentInfo ::= SEQUENCE { @@ -21,19 +32,52 @@ import SwiftASN1 /// content [0] EXPLICIT ANY DEFINED BY contentType } /// ContentType ::= OBJECT IDENTIFIER /// ``` -struct CMSContentInfo { +struct CMSContentInfo: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + var contentType: ASN1ObjectIdentifier var content: ASN1Any + + init(contentType: ASN1ObjectIdentifier, content: ASN1Any) { + self.contentType = contentType + self.content = content + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let contentType = try ASN1ObjectIdentifier(derEncoded: &nodes) + + let content = try DER.explicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + ASN1Any(derEncoded: node) + } + return .init(contentType: contentType, content: content) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(contentType) + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serialize(content) + } + } + } } extension CMSContentInfo { - init(_ signedData: CMSSignedData) { - fatalError("TODO: not implemented") + init(_ signedData: CMSSignedData) throws { + self.contentType = .cmsSignedData + self.content = try ASN1Any(erasing: signedData) } var signedData: CMSSignedData? { get throws { - fatalError("TODO: not implemented") + guard contentType == .cmsSignedData else { + return nil + } + return try CMSSignedData(asn1Any: content) } } } diff --git a/Sources/X509/CryptographicMessageSyntax/CMSEncapsulatedContentInfo.swift b/Sources/X509/CryptographicMessageSyntax/CMSEncapsulatedContentInfo.swift index 4a90eaf..8c530ee 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSEncapsulatedContentInfo.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSEncapsulatedContentInfo.swift @@ -21,7 +21,38 @@ import SwiftASN1 /// eContent [0] EXPLICIT OCTET STRING OPTIONAL } /// ContentType ::= OBJECT IDENTIFIER /// ``` -struct CMSEncapsulatedContentInfo { +struct CMSEncapsulatedContentInfo: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + var eContentType: ASN1ObjectIdentifier var eContent: ASN1OctetString? + + init(eContentType: ASN1ObjectIdentifier, eContent: ASN1OctetString? = nil) { + self.eContentType = eContentType + self.eContent = eContent + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let eContentType = try ASN1ObjectIdentifier(derEncoded: &nodes) + let eContent = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + try ASN1OctetString(derEncoded: node) + } + + return .init(eContentType: eContentType, eContent: eContent) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier, { coder in + try coder.serialize(eContentType) + if let eContent { + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serialize(eContent) + } + } + }) + } } diff --git a/Sources/X509/CryptographicMessageSyntax/CMSIssuerAndSerialNumber.swift b/Sources/X509/CryptographicMessageSyntax/CMSIssuerAndSerialNumber.swift index a15e79d..e151727 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSIssuerAndSerialNumber.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSIssuerAndSerialNumber.swift @@ -22,7 +22,34 @@ import SwiftASN1 /// ``` /// The definition of `Name` is taken from X.501 [X.501-88], and the /// definition of `CertificateSerialNumber` is taken from X.509 [X.509-97]. -struct CMSIssuerAndSerialNumber { +struct CMSIssuerAndSerialNumber: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + var issuer: DistinguishedName var serialNumber: Certificate.SerialNumber + + init( + issuer: DistinguishedName, + serialNumber: Certificate.SerialNumber + ) { + self.issuer = issuer + self.serialNumber = serialNumber + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let issuer = try DistinguishedName(derEncoded: &nodes) + let serialNumber = try ArraySlice(derEncoded: &nodes) + return .init(issuer: issuer, serialNumber: .init(bytes: serialNumber)) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.issuer) + try coder.serialize(self.serialNumber.bytes) + } + } } diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift index 2c3f092..b0cf51b 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift @@ -27,6 +27,7 @@ import SwiftASN1 /// DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier /// DigestAlgorithmIdentifier ::= AlgorithmIdentifier /// SignerInfos ::= SET OF SignerInfo +/// CertificateSet ::= SET OF CertificateChoices /// /// CertificateChoices ::= CHOICE { /// certificate Certificate, @@ -40,10 +41,176 @@ import SwiftASN1 /// otherCert ANY DEFINED BY otherCertFormat } /// ``` /// - Note: At the moment we don't support `crls` (`RevocationInfoChoices`) -struct CMSSignedData { +struct CMSSignedData: DERImplicitlyTaggable, Hashable { + private enum Error: Swift.Error { + case multipleDigestAlgorithmsAreNotSupportedYet + case multipleSignerInfosAreNotSupportedYet + } + static var defaultIdentifier: ASN1Identifier { + .sequence + } + var version: CMSVersion var digestAlgorithms: [AlgorithmIdentifier] var encapContentInfo: CMSEncapsulatedContentInfo var certificates: [Certificate]? var signerInfos: [CMSSignerInfo] + + init( + version: CMSVersion, + digestAlgorithms: [AlgorithmIdentifier], + encapContentInfo: CMSEncapsulatedContentInfo, + certificates: [Certificate]?, + signerInfos: [CMSSignerInfo] + ) { + self.version = version + self.digestAlgorithms = digestAlgorithms + self.encapContentInfo = encapContentInfo + self.certificates = certificates + self.signerInfos = signerInfos + } + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(derEncoded, identifier: identifier) { nodes in + let version = try CMSVersion(rawValue: Int.init(derEncoded: &nodes)) + let digestAlgorithms = try DER.sequence(of: AlgorithmIdentifier.self, identifier: .set, nodes: &nodes) + // TODO: support multiple digest algorithms. For this we need to validate that the binary representation of each element is lexicographically sorted. + guard digestAlgorithms.count <= 1 else { + throw Error.multipleDigestAlgorithmsAreNotSupportedYet + } + + let encapContentInfo = try CMSEncapsulatedContentInfo(derEncoded: &nodes) + let certificates = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific)) { node in + // TODO: this is actually a SET OF so we need to verify that the binary representation of each element is lexicographically sorted. + try DER.sequence(of: Certificate.self, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific), rootNode: node) + } + + // we need to skip this node even though we don't support it + let _: CMSRevocationInfoChoices? = try DER._optionalImplicitlyTagged( + &nodes, + tag: .init(tagWithNumber: 1, tagClass: .contextSpecific) + ) + + let signerInfos = try DER.sequence(of: CMSSignerInfo.self, identifier: .set, nodes: &nodes) + + // TODO: support multiple signer infos. For this we need to validate that the binary representation of each element is lexicographically sorted. + guard signerInfos.count <= 1 else { + throw Error.multipleDigestAlgorithmsAreNotSupportedYet + } + + return .init( + version: version, + digestAlgorithms: digestAlgorithms, + encapContentInfo: encapContentInfo, + certificates: certificates, + signerInfos: signerInfos + ) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(version.rawValue) + guard self.digestAlgorithms.count <= 1 else { + throw Error.multipleDigestAlgorithmsAreNotSupportedYet + } + // TODO: this is actually a SET OF. We need to sort the binary representation of each element lexicographically before encoding. + try coder.serializeSequenceOf(self.digestAlgorithms, identifier: .set) + try coder.serialize(self.encapContentInfo) + if let certificates { + // TODO: this is actually a SET OF. We need to sort the binary representation of each element lexicographically before encoding. + try coder.serializeSequenceOf(certificates, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific)) + } + guard self.signerInfos.count <= 1 else { + throw Error.multipleSignerInfosAreNotSupportedYet + } + // TODO: this is actually a SET OF. We need to sort the binary representation of each element lexicographically before encoding. + try coder.serializeSequenceOf(self.signerInfos, identifier: .set) + } + } +} + +fileprivate enum CMSCertificateChoices: DERParseable, DERSerializable { + static var defaultIdentifier: SwiftASN1.ASN1Identifier { + .enumerated + } + + case certificate(Certificate) + + init(derEncoded: ASN1Node) throws { + guard derEncoded.identifier == Certificate.defaultIdentifier else { + throw ASN1Error.unexpectedFieldType + } + self = try .certificate(.init(derEncoded: derEncoded)) + } + func serialize(into coder: inout DER.Serializer) throws { + switch self { + case .certificate(let certificate): + try coder.serialize(certificate) + } + } +} + +/// Not yet supported +fileprivate struct CMSRevocationInfoChoices: DERParseable, DERSerializable { + init(derEncoded: ASN1Node) throws {} + func serialize(into coder: inout DER.Serializer) throws {} +} + +extension DER { + /// Parses an optional implicitly tagged element. + /// + /// - parameters: + /// - nodes: The ``ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tag: The implicit tag. + /// + /// - returns: The parsed element, if it was present, or `nil` if it was not. + static func _optionalImplicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tag: ASN1Identifier + ) 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(derEncoded: &nodes) + } + + /// Parses an optional implicitly tagged element. + /// + /// - parameters: + /// - nodes: The ``ASN1NodeCollection/Iterator`` to parse this element out of. + /// - tag: The implicit tag. + /// + /// - returns: The parsed element, if it was present, or `nil` if it was not. + static func _optionalImplicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tag: ASN1Identifier, + _ builder: (ASN1Node) throws -> T + ) 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 + } + nodes = localNodesCopy + + // We're good: pass the node on. + return try builder(node) + } } diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift index eedf85c..6bfcce7 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift @@ -20,7 +20,34 @@ import SwiftASN1 /// issuerAndSerialNumber IssuerAndSerialNumber, /// subjectKeyIdentifier [0] SubjectKeyIdentifier } /// ``` -enum CMSSignerIdentifier { +enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable { + + private static let subjectKeyIdentifierIdentifier = ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific) + case issuerAndSerialNumber(CMSIssuerAndSerialNumber) case subjectKeyIdentifier(Certificate.Extensions.SubjectKeyIdentifier) + + init(derEncoded node: ASN1Node) throws { + switch node.identifier { + case CMSIssuerAndSerialNumber.defaultIdentifier: + self = try .issuerAndSerialNumber(.init(derEncoded: node)) + + case Self.subjectKeyIdentifierIdentifier: + self = try .subjectKeyIdentifier(.init(keyIdentifier: .init(derEncoded: node, withIdentifier: Self.subjectKeyIdentifierIdentifier))) + + default: + throw ASN1Error.invalidASN1Object + } + } + + func serialize(into coder: inout DER.Serializer) throws { + switch self { + case .issuerAndSerialNumber(let issuerAndSerialNumber): + try issuerAndSerialNumber.serialize(into: &coder) + + case .subjectKeyIdentifier(let subjectKeyIdentifier): + try subjectKeyIdentifier.keyIdentifier.serialize(into: &coder, withIdentifier: Self.subjectKeyIdentifierIdentifier) + + } + } } diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift index de428b3..170eab7 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift @@ -33,11 +33,94 @@ import SwiftASN1 /// then the `version` MUST be 1. If the `SignerIdentifier` is `subjectKeyIdentifier`, /// then the `version` MUST be 3. /// - Note: At the moment we neither support `signedAttrs` (`SignedAttributes`) nor `unsignedAttrs` (`UnsignedAttributes`) -struct CMSSignerInfo { +struct CMSSignerInfo: DERImplicitlyTaggable, Hashable { + enum Error: Swift.Error { + case versionAndSignerIdentifierMismatch(String) + } + static var defaultIdentifier: ASN1Identifier { + .sequence + } + var version: CMSVersion var signerIdentifier: CMSSignerIdentifier var digestAlgorithm: AlgorithmIdentifier var signatureAlgorithm: AlgorithmIdentifier var signature: ASN1OctetString + + init( + signerIdentifier: CMSSignerIdentifier, + digestAlgorithm: AlgorithmIdentifier, + signatureAlgorithm: AlgorithmIdentifier, + signature: ASN1OctetString + ) { + switch signerIdentifier { + case .issuerAndSerialNumber: + self.version = .v1 + case .subjectKeyIdentifier: + self.version = .v3 + } + self.signerIdentifier = signerIdentifier + self.digestAlgorithm = digestAlgorithm + self.signatureAlgorithm = signatureAlgorithm + self.signature = signature + } + + init( + version: CMSVersion, + signerIdentifier: CMSSignerIdentifier, + digestAlgorithm: AlgorithmIdentifier, + signatureAlgorithm: AlgorithmIdentifier, + signature: ASN1OctetString + ) { + self.version = version + self.signerIdentifier = signerIdentifier + self.digestAlgorithm = digestAlgorithm + self.signatureAlgorithm = signatureAlgorithm + self.signature = signature + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let version = try CMSVersion(rawValue: Int(derEncoded: &nodes)) + let signerIdentifier = try CMSSignerIdentifier(derEncoded: &nodes) + switch signerIdentifier { + case .issuerAndSerialNumber: + guard version == .v1 else { + throw Error.versionAndSignerIdentifierMismatch("expected \(CMSVersion.v1) but got \(version) where signerIdentifier is \(signerIdentifier)") + } + case .subjectKeyIdentifier: + guard version == .v3 else { + throw Error.versionAndSignerIdentifierMismatch("expected \(CMSVersion.v3) but got \(version) where signerIdentifier is \(signerIdentifier)") + } + } + let digestAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) + + // we don't support signedAttrs yet but we still need to skip them + _ = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific)) { _ in } + + let signatureAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) + let signature = try ASN1OctetString(derEncoded: &nodes) + + // we don't support unsignedAttrs yet but we still need to skip them + _ = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific)) { _ in } + + return .init( + version: version, + signerIdentifier: signerIdentifier, + digestAlgorithm: digestAlgorithm, + signatureAlgorithm: signatureAlgorithm, + signature: signature + ) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.version.rawValue) + try coder.serialize(self.signerIdentifier) + try coder.serialize(self.digestAlgorithm) + try coder.serialize(self.signatureAlgorithm) + try coder.serialize(self.signature) + } + } } - diff --git a/Tests/X509Tests/CMSTests.swift b/Tests/X509Tests/CMSTests.swift new file mode 100644 index 0000000..15c5222 --- /dev/null +++ b/Tests/X509Tests/CMSTests.swift @@ -0,0 +1,198 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + + +import XCTest +import Crypto +import SwiftASN1 +@testable import X509 + +final class CMSTests: XCTestCase { + private func assertRoundTrips(_ value: ASN1Object) throws { + var serializer = DER.Serializer() + try serializer.serialize(value) + let parsed = try ASN1Object(derEncoded: serializer.serializedBytes) + XCTAssertEqual(parsed, value) + } + + func testIssuerAndSerialNumber() throws { + try assertRoundTrips(CMSIssuerAndSerialNumber(issuer: .init { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("Apple Public EV Server ECC CA 1 - G1") + }, serialNumber: .init(bytes: [10, 20, 30, 40]))) + } + func testSignerIdentifier() throws { + try assertRoundTrips( + CMSSignerIdentifier.issuerAndSerialNumber(.init(issuer: .init { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("Apple Public EV Server ECC CA 1 - G1") + }, serialNumber: .init(bytes: [20, 30, 40, 50]))) + ) + try assertRoundTrips( + CMSSignerIdentifier.subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])) + ) + } + func testCMSSignerInfo() throws { + try assertRoundTrips(CMSSignerInfo( + version: .v1, + signerIdentifier: .issuerAndSerialNumber(.init( + issuer: .init { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("Apple Public EV Server ECC CA 1 - G1") + }, + serialNumber: .init(bytes: [20, 30, 40, 50]) + )), + digestAlgorithm: .sha256WithRSAEncryptionUsingNil, + signatureAlgorithm: .ecdsaWithSHA256, + signature: .init(contentBytes: [100, 110, 120, 130, 140]) + )) + + try assertRoundTrips(CMSSignerInfo( + version: .v3, + signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])), + digestAlgorithm: .sha256WithRSAEncryptionUsingNil, + signatureAlgorithm: .ecdsaWithSHA256, + signature: .init(contentBytes: [100, 110, 120, 130, 140]) + )) + + XCTAssertThrowsError(try assertRoundTrips(CMSSignerInfo( + version: .v3, + signerIdentifier: .issuerAndSerialNumber(.init( + issuer: .init { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("Apple Public EV Server ECC CA 1 - G1") + }, + serialNumber: .init(bytes: [20, 30, 40, 50]) + )), + digestAlgorithm: .sha256WithRSAEncryptionUsingNil, + signatureAlgorithm: .ecdsaWithSHA256, + signature: .init(contentBytes: [100, 110, 120, 130, 140]) + )), "unexpected signerIdentifier for version should throw") + + XCTAssertThrowsError(try assertRoundTrips(CMSSignerInfo( + version: .v1, + signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])), + digestAlgorithm: .sha256WithRSAEncryptionUsingNil, + signatureAlgorithm: .ecdsaWithSHA256, + signature: .init(contentBytes: [100, 110, 120, 130, 140]) + )), "unexpected signerIdentifier for version should throw") + } + func testEncapsulatedContentInfo() throws { + try assertRoundTrips(CMSEncapsulatedContentInfo( + eContentType: [1, 2, 3, 4], + eContent: .init(contentBytes: [5, 6, 7, 8]) + )) + try assertRoundTrips(CMSEncapsulatedContentInfo( + eContentType: [1, 2, 3, 4], + eContent: nil + )) + } + func testSignedData() throws { + try assertRoundTrips(CMSSignedData( + version: .v1, + digestAlgorithms: [], + encapContentInfo: .init(eContentType: [1, 2, 3, 4]), + certificates: nil, + signerInfos: [] + )) + try assertRoundTrips(CMSSignedData( + version: .v1, + digestAlgorithms: [.sha256WithRSAEncryptionUsingNil], + encapContentInfo: .init(eContentType: [1, 2, 3, 4]), + certificates: [], + signerInfos: [] + )) + try assertRoundTrips(CMSSignedData( + version: .v1, + digestAlgorithms: [.sha256WithRSAEncryptionUsingNil], + encapContentInfo: .init(eContentType: [1, 2, 3, 4]), + certificates: [], + signerInfos: [ + CMSSignerInfo( + version: .v3, + signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])), + digestAlgorithm: .sha256WithRSAEncryptionUsingNil, + signatureAlgorithm: .ecdsaWithSHA256, + signature: .init(contentBytes: [100, 110, 120, 130, 140]) + ) + ] + )) + + let privateKey = P384.Signing.PrivateKey() + try assertRoundTrips(CMSSignedData( + version: .v1, + digestAlgorithms: [ + .sha256WithRSAEncryptionUsingNil + ], + encapContentInfo: .init(eContentType: [1, 2, 3, 4]), + certificates: [Certificate( + version: .v3, + serialNumber: .init(bytes: [1, 2, 3, 4]), + publicKey: .init(privateKey.publicKey), + notValidBefore: Date(), + notValidAfter: Date(), + issuer: DistinguishedName { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("Apple Public EV Server ECC CA 1 - G1") + }, + subject: DistinguishedName { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("apple.com") + }, + signatureAlgorithm: .ecdsaWithSHA384, + extensions: .init(), + issuerPrivateKey: .init(privateKey) + )], + signerInfos: [] + )) + } + + func testContentInfo() throws { + let privateKey = P384.Signing.PrivateKey() + try assertRoundTrips(CMSContentInfo(CMSSignedData( + version: .v1, + digestAlgorithms: [ + .sha256WithRSAEncryptionUsingNil + ], + encapContentInfo: .init(eContentType: [1, 2, 3, 4]), + certificates: [Certificate( + version: .v3, + serialNumber: .init(bytes: [1, 2, 3, 4]), + publicKey: .init(privateKey.publicKey), + notValidBefore: Date(), + notValidAfter: Date(), + issuer: DistinguishedName { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("Apple Public EV Server ECC CA 1 - G1") + }, + subject: DistinguishedName { + CountryName("US") + OrganizationName("Apple Inc.") + CommonName("apple.com") + }, + signatureAlgorithm: .ecdsaWithSHA384, + extensions: .init(), + issuerPrivateKey: .init(privateKey) + )], + signerInfos: [] + ))) + } +} From a92d6e89183683f4369ea75f94732219c7f73e07 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 2 Feb 2023 11:47:07 +0100 Subject: [PATCH 2/4] =?UTF-8?q?It=20doesn=E2=80=99t=20make=20sense=20to=20?= =?UTF-8?q?decode=20as=20an=20implicitly=20taggable=20type=20if=20the=20ty?= =?UTF-8?q?pe=20does=20not=20conform=20to=20`DERImplicitlyTaggable`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CMSSignedData.swift | 59 +------------------ 1 file changed, 1 insertion(+), 58 deletions(-) diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift index b0cf51b..cb3a33e 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift @@ -86,10 +86,7 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable { } // we need to skip this node even though we don't support it - let _: CMSRevocationInfoChoices? = try DER._optionalImplicitlyTagged( - &nodes, - tag: .init(tagWithNumber: 1, tagClass: .contextSpecific) - ) + _ = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific)) { _ in } let signerInfos = try DER.sequence(of: CMSSignerInfo.self, identifier: .set, nodes: &nodes) @@ -130,61 +127,7 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable { } } -fileprivate enum CMSCertificateChoices: DERParseable, DERSerializable { - static var defaultIdentifier: SwiftASN1.ASN1Identifier { - .enumerated - } - - case certificate(Certificate) - - init(derEncoded: ASN1Node) throws { - guard derEncoded.identifier == Certificate.defaultIdentifier else { - throw ASN1Error.unexpectedFieldType - } - self = try .certificate(.init(derEncoded: derEncoded)) - } - func serialize(into coder: inout DER.Serializer) throws { - switch self { - case .certificate(let certificate): - try coder.serialize(certificate) - } - } -} - -/// Not yet supported -fileprivate struct CMSRevocationInfoChoices: DERParseable, DERSerializable { - init(derEncoded: ASN1Node) throws {} - func serialize(into coder: inout DER.Serializer) throws {} -} - extension DER { - /// Parses an optional implicitly tagged element. - /// - /// - parameters: - /// - nodes: The ``ASN1NodeCollection/Iterator`` to parse this element out of. - /// - tag: The implicit tag. - /// - /// - returns: The parsed element, if it was present, or `nil` if it was not. - static func _optionalImplicitlyTagged( - _ nodes: inout ASN1NodeCollection.Iterator, - tag: ASN1Identifier - ) 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(derEncoded: &nodes) - } - /// Parses an optional implicitly tagged element. /// /// - parameters: From f153e0ba7b4c7d8aa90e3b683f23e7c3b889826c Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 2 Feb 2023 15:17:13 +0100 Subject: [PATCH 3/4] Use new `DER.optionalImplicitlyTagged` from `swift-asn1` `0.4.0` --- Package.swift | 4 +-- .../CMSSignedData.swift | 35 ++----------------- .../CMSSignerInfo.swift | 4 +-- 3 files changed, 6 insertions(+), 37 deletions(-) diff --git a/Package.swift b/Package.swift index f6dc568..f9c15ae 100644 --- a/Package.swift +++ b/Package.swift @@ -31,8 +31,8 @@ let package = Package( dependencies: [ .package(url: "https://github.com/apple/swift-crypto.git", from: "2.2.1"), // swift-asn1 repo is private, so we can't access it anonymously yet - // .package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.3.0")), - .package(url: "git@github.com:apple/swift-asn1.git", .upToNextMinor(from: "0.3.0")), + // .package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.4.0")), + .package(url: "git@github.com:apple/swift-asn1.git", .upToNextMinor(from: "0.4.0")), .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"), ], targets: [ diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift index cb3a33e..4b72ef0 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift @@ -80,13 +80,13 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable { } let encapContentInfo = try CMSEncapsulatedContentInfo(derEncoded: &nodes) - let certificates = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific)) { node in + let certificates = try DER.optionalImplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in // TODO: this is actually a SET OF so we need to verify that the binary representation of each element is lexicographically sorted. try DER.sequence(of: Certificate.self, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific), rootNode: node) } // we need to skip this node even though we don't support it - _ = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific)) { _ in } + _ = DER.optionalImplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { _ in } let signerInfos = try DER.sequence(of: CMSSignerInfo.self, identifier: .set, nodes: &nodes) @@ -126,34 +126,3 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable { } } } - -extension DER { - /// Parses an optional implicitly tagged element. - /// - /// - parameters: - /// - nodes: The ``ASN1NodeCollection/Iterator`` to parse this element out of. - /// - tag: The implicit tag. - /// - /// - returns: The parsed element, if it was present, or `nil` if it was not. - static func _optionalImplicitlyTagged( - _ nodes: inout ASN1NodeCollection.Iterator, - tag: ASN1Identifier, - _ builder: (ASN1Node) throws -> T - ) 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 - } - nodes = localNodesCopy - - // We're good: pass the node on. - return try builder(node) - } -} diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift index 170eab7..c415fba 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignerInfo.swift @@ -96,13 +96,13 @@ struct CMSSignerInfo: DERImplicitlyTaggable, Hashable { let digestAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) // we don't support signedAttrs yet but we still need to skip them - _ = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific)) { _ in } + _ = DER.optionalImplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in } let signatureAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) let signature = try ASN1OctetString(derEncoded: &nodes) // we don't support unsignedAttrs yet but we still need to skip them - _ = try DER._optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific)) { _ in } + _ = DER.optionalImplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { _ in } return .init( version: version, From c33a826019a264398adbc137707a2ca96c18411c Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 2 Feb 2023 15:32:51 +0100 Subject: [PATCH 4/4] Fix review comments --- .../X509/CryptographicMessageSyntax/CMSSignedData.swift | 2 +- .../CryptographicMessageSyntax/CMSSignerIdentifier.swift | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift index 4b72ef0..c1db119 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignedData.swift @@ -92,7 +92,7 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable { // TODO: support multiple signer infos. For this we need to validate that the binary representation of each element is lexicographically sorted. guard signerInfos.count <= 1 else { - throw Error.multipleDigestAlgorithmsAreNotSupportedYet + throw Error.multipleSignerInfosAreNotSupportedYet } return .init( diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift index 6bfcce7..155bf35 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift @@ -22,7 +22,7 @@ import SwiftASN1 /// ``` enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable { - private static let subjectKeyIdentifierIdentifier = ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific) + private static let skiIdentifier = ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific) case issuerAndSerialNumber(CMSIssuerAndSerialNumber) case subjectKeyIdentifier(Certificate.Extensions.SubjectKeyIdentifier) @@ -32,8 +32,8 @@ enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable { case CMSIssuerAndSerialNumber.defaultIdentifier: self = try .issuerAndSerialNumber(.init(derEncoded: node)) - case Self.subjectKeyIdentifierIdentifier: - self = try .subjectKeyIdentifier(.init(keyIdentifier: .init(derEncoded: node, withIdentifier: Self.subjectKeyIdentifierIdentifier))) + case Self.skiIdentifier: + self = try .subjectKeyIdentifier(.init(keyIdentifier: .init(derEncoded: node, withIdentifier: Self.skiIdentifier))) default: throw ASN1Error.invalidASN1Object @@ -46,7 +46,7 @@ enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable { try issuerAndSerialNumber.serialize(into: &coder) case .subjectKeyIdentifier(let subjectKeyIdentifier): - try subjectKeyIdentifier.keyIdentifier.serialize(into: &coder, withIdentifier: Self.subjectKeyIdentifierIdentifier) + try subjectKeyIdentifier.keyIdentifier.serialize(into: &coder, withIdentifier: Self.skiIdentifier) } }