From d9a8b6583a85e6c56b1b786f9304e8292c19e10c Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Thu, 4 May 2023 12:08:23 +0100 Subject: [PATCH] Certificate Signing Request (#59) * Add support for Certificate Signing Requests This patch adds support for working with Certificate Signing Requests to swift-certificates. CSRs are a common feature of X.509 based PKIs. They're used to encapsulate a number of details about the certificate being requested, and are typically handed to CAs in exchange for a certificate. Their purpose is to prove possession of a private key, and optionally some other useful pieces of data. This patch provides a complete representation of the CSR type, as well as semantic types to cover the attributes that can be applied to a CSR. Additionally, CSR signature validation is also available. * Code review * Fix up equality and hashing * Count matters too * Comment explaining XOR --- NOTICE.txt | 8 + Package.swift | 1 + Sources/X509/CMakeLists.txt | 6 + Sources/X509/CSR/CSRAttribute.swift | 124 +++++ Sources/X509/CSR/CSRAttributes.swift | 178 +++++++ Sources/X509/CSR/CSRVersion.swift | 53 ++ .../X509/CSR/CertificateSigningRequest.swift | 217 ++++++++ .../X509/CSR/CertificationRequestInfo.swift | 87 +++ Sources/X509/CSR/ExtensionRequest.swift | 95 ++++ Sources/X509/CertificatePublicKey.swift | 15 + Sources/X509/Error.swift | 36 ++ .../CSR Vectors/cryptography/LICENSE.APACHE | 202 +++++++ .../CSR Vectors/cryptography/bad-version.pem | 7 + .../cryptography/basic_constraints.pem | 17 + .../cryptography/challenge-invalid.der | Bin 0 -> 633 bytes .../cryptography/challenge-multi-valued.der | Bin 0 -> 643 bytes .../cryptography/challenge-unstructured.pem | 17 + .../CSR Vectors/cryptography/challenge.pem | 16 + .../CSR Vectors/cryptography/ec_sha256.der | Bin 0 -> 339 bytes .../CSR Vectors/cryptography/ec_sha256.pem | 10 + .../cryptography/freeipa-bad-critical.pem | 23 + .../cryptography/invalid_signature.pem | 10 + .../cryptography/long-form-attribute.pem | 15 + .../CSR Vectors/cryptography/rsa_md4.der | Bin 0 -> 672 bytes .../CSR Vectors/cryptography/rsa_md4.pem | 16 + .../CSR Vectors/cryptography/rsa_sha1.der | Bin 0 -> 672 bytes .../CSR Vectors/cryptography/rsa_sha1.pem | 16 + .../CSR Vectors/cryptography/rsa_sha256.der | Bin 0 -> 672 bytes .../CSR Vectors/cryptography/rsa_sha256.pem | 16 + .../CSR Vectors/cryptography/san_rsa_sha1.der | Bin 0 -> 742 bytes .../CSR Vectors/cryptography/san_rsa_sha1.pem | 18 + .../cryptography/two_basic_constraints.pem | 17 + .../cryptography/unsupported_extension.pem | 17 + .../unsupported_extension_critical.pem | 17 + Tests/X509Tests/CSRTests.swift | 499 ++++++++++++++++++ 35 files changed, 1753 insertions(+) create mode 100644 Sources/X509/CSR/CSRAttribute.swift create mode 100644 Sources/X509/CSR/CSRAttributes.swift create mode 100644 Sources/X509/CSR/CSRVersion.swift create mode 100644 Sources/X509/CSR/CertificateSigningRequest.swift create mode 100644 Sources/X509/CSR/CertificationRequestInfo.swift create mode 100644 Sources/X509/CSR/ExtensionRequest.swift create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/LICENSE.APACHE create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/bad-version.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/basic_constraints.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/challenge-invalid.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/challenge-multi-valued.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/challenge-unstructured.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/challenge.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/freeipa-bad-critical.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/invalid_signature.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/long-form-attribute.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.der create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/two_basic_constraints.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension.pem create mode 100644 Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension_critical.pem create mode 100644 Tests/X509Tests/CSRTests.swift diff --git a/NOTICE.txt b/NOTICE.txt index 3824b10..6b0bec1 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -51,3 +51,11 @@ This product contains derivations of various ASN1 types from SwiftASN1. * HOMEPAGE: * https://github.com/apple/swift-asn1 +--- + +This product contains test vectors from pyca/cryptography. + + * LICENSE (Apache License 2.0): + * https://github.com/pyca/cryptography/blob/main/LICENSE.APACHE + * HOMEPAGE: + * https://github.com/pyca/cryptography diff --git a/Package.swift b/Package.swift index 249887e..e534fc4 100644 --- a/Package.swift +++ b/Package.swift @@ -53,6 +53,7 @@ let package = Package( .copy("OCSP Test Resources/www.apple.com.ocsp-response.der"), .copy("OCSP Test Resources/www.apple.com.intermediate.ocsp-response.der"), .copy("PEMTestRSACertificate.pem"), + .copy("CSR Vectors/"), ]), ] ) diff --git a/Sources/X509/CMakeLists.txt b/Sources/X509/CMakeLists.txt index 97d53af..2825b12 100644 --- a/Sources/X509/CMakeLists.txt +++ b/Sources/X509/CMakeLists.txt @@ -13,6 +13,12 @@ ##===----------------------------------------------------------------------===## add_library(X509 + "CSR/CSRAttribute.swift" + "CSR/CSRAttributes.swift" + "CSR/CSRVersion.swift" + "CSR/CertificateSigningRequest.swift" + "CSR/CertificationRequestInfo.swift" + "CSR/ExtensionRequest.swift" "Certificate.swift" "CertificatePrivateKey.swift" "CertificatePublicKey.swift" diff --git a/Sources/X509/CSR/CSRAttribute.swift b/Sources/X509/CSR/CSRAttribute.swift new file mode 100644 index 0000000..948a81d --- /dev/null +++ b/Sources/X509/CSR/CSRAttribute.swift @@ -0,0 +1,124 @@ +//===----------------------------------------------------------------------===// +// +// 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 SwiftASN1 + +extension CertificateSigningRequest { + /// A general-purpose representation of a ``CertificateSigningRequest`` attribute. + /// + /// ``CertificateSigningRequest``s can have a number of attributes applied to them. These attributes are non-binding, but can be + /// used to encode things like extensions that should be applied to the generated certificate, or challenge material that can + /// be used to enable later revocation. + /// + /// ``Attribute``s are a general representation, keyed by an object identifier and storing a `SET` of arbitrary values. + /// This `SET` cannot be empty. Individual ``Attribute``s can be parsed into more specific values as-needed. + public struct Attribute { + /// The identifier for this attribute type. + /// + /// Common values are stored in `ASN1ObjectIdentifier.X509ExtensionID`. + public var oid: ASN1ObjectIdentifier + + /// The encoded bytes of the values of this attribute. + /// + /// This value should be decoded based on the value of ``oid``. + public var values: [ASN1Any] + + /// Construct a new attribute from its constituent parts. + /// + /// - Parameters: + /// - oid: The identifier for this extension type. + /// - values: The value of this attribute, erased to `ASN1Any` + @inlinable + public init(oid: ASN1ObjectIdentifier, values: [ASN1Any]) { + self.oid = oid + self.values = values + } + } +} + +extension CertificateSigningRequest.Attribute: Hashable { + @inlinable + public static func ==(lhs: CertificateSigningRequest.Attribute, rhs: CertificateSigningRequest.Attribute) -> Bool { + if lhs.oid != rhs.oid { return false } + if lhs.values.count != rhs.values.count { return false } + + for element in lhs.values { + if !rhs.values.contains(element) { return false } + } + + return true + } + + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.oid) + + // This achieves order-independent hashing without + // having to sort anything. That relies on the use of XOR, + // but any associative operation would do. + var hash = 0 + for element in self.values { + var newHasher = Hasher() + element.hash(into: &newHasher) + hash ^= newHasher.finalize() + } + + hasher.combine(hash) + } +} + +extension CertificateSigningRequest.Attribute: Sendable { } + +extension CertificateSigningRequest.Attribute: CustomStringConvertible { + public var description: String { + return "Attribute(oid: \(self.oid), values: \(self.values))" + } +} + +// Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { +// type ATTRIBUTE.&id({IOSet}), +// values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) +// } +extension CertificateSigningRequest.Attribute: DERImplicitlyTaggable { + @inlinable + public static var defaultIdentifier: ASN1Identifier { + .sequence + } + + @inlinable + public init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let type = try ASN1ObjectIdentifier(derEncoded: &nodes) + let values = try DER.set(of: ASN1Any.self, identifier: .set, nodes: &nodes) + + return CertificateSigningRequest.Attribute(oid: type, values: values) + } + } + + @inlinable + public func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.oid) + try coder.serializeSetOf(self.values) + } + } +} + +extension ASN1ObjectIdentifier { + /// Object Identifiers that identify attributes applied to CSRs. + public enum CSRAttributes { + /// A request to apply specific certificate extensions. + public static let extensionRequest: ASN1ObjectIdentifier = [1, 2, 840, 113549, 1, 9, 14] + } +} diff --git a/Sources/X509/CSR/CSRAttributes.swift b/Sources/X509/CSR/CSRAttributes.swift new file mode 100644 index 0000000..eaf85e2 --- /dev/null +++ b/Sources/X509/CSR/CSRAttributes.swift @@ -0,0 +1,178 @@ +//===----------------------------------------------------------------------===// +// +// 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 SwiftASN1 + +extension CertificateSigningRequest { + /// A representation of the additional attributes on a certificate signing request. + /// + /// CSR attributes are represented as an ASN.1 SET of key-value pairs, where each key + /// may have 1 or more values. Attributes are defined in a wide range of specifications. + /// + /// ### Sequence and Collection Helpers + /// + /// ``CertificateSigningRequest/Attributes-swift.struct`` is conceptually a collection of + /// ``CertificateSigningRequest/Attribute`` objects. The collection is unordered, and order + /// is not preserved across modification. + /// + /// However, ``CertificateSigningRequest/Attributes-swift.struct`` is also conceptually a dictionary + /// keyed by ``CertificateSigningRequest/Attribute/oid``. For that reason, in addition to the index-based subscript + /// this type also offers ``subscript(oid:)`` to enable finding the attribute with a specific OID. This API also + /// lets users replace the value of a specific attribute. + /// + /// ### Specific attribute helpers + /// + /// To make it easier to decode specific attributes, this type provides a number of helpers for known extension types: + /// + /// - ``extensionRequest`` + /// + /// Users who add their own attribute types (see ``CertificateSigningRequest/Attribute`` for more) are encouraged to add their + /// own helper getters for those types. + public struct Attributes { + @usableFromInline + var _attributes: [Attribute] + + /// Produce a new Attributes container from a collection of ``CertificateSigningRequest/Attribute``. + /// + /// - Parameter attributes: The base attributes. + @inlinable + public init(_ attributes: Elements) where Elements: Sequence, Elements.Element == Attribute { + self._attributes = [] + + for element in attributes { + self[oid: element.oid] = element + } + } + } +} + +extension CertificateSigningRequest.Attributes: Hashable { + @inlinable + public static func ==(lhs: CertificateSigningRequest.Attributes, rhs: CertificateSigningRequest.Attributes) -> Bool { + if lhs.count != rhs.count { return false } + + for element in lhs { + if !rhs.contains(element) { return false } + } + + return true + } + + @inlinable + public func hash(into hasher: inout Hasher) { + // This achieves order-independent hashing without + // having to sort anything. + var hash = 0 + for element in self { + var newHasher = Hasher() + element.hash(into: &newHasher) + hash ^= newHasher.finalize() + } + + hasher.combine(hash) + } +} + +extension CertificateSigningRequest.Attributes: Sendable { } + +extension CertificateSigningRequest.Attributes: RandomAccessCollection { + @inlinable + public init() { + self._attributes = [] + } + + @inlinable + public var startIndex: Int { + self._attributes.startIndex + } + + @inlinable + public var endIndex: Int { + self._attributes.endIndex + } + + @inlinable + public subscript(position: Int) -> CertificateSigningRequest.Attribute { + get { + self._attributes[position] + } + } + + /// Insert a new ``CertificateSigningRequest/Attribute`` into this set of ``CertificateSigningRequest/Attributes-swift.struct``. + /// + /// If an attribute already exists with this OID, it will be replaced by the new value. + /// + /// - Parameter attribute: The ``CertificateSigningRequest/Attribute`` to insert. + @inlinable + public mutating func insert(_ ext: CertificateSigningRequest.Attribute) { + self[oid: ext.oid] = ext + } + + /// Insert a sequence of new ``CertificateSigningRequest/Attribute``s into this set of ``CertificateSigningRequest/Attributes-swift.struct``. + /// + /// If a ``CertificateSigningRequest/Attribute`` with the same ``CertificateSigningRequest/Attribute/oid`` is already + /// present in this element, the new value will replace it. If `extensions` contains multiple attributes with the same + /// ``CertificateSigningRequest/Attribute/oid``, the last element will win. + /// + /// - Parameter extensions: The sequence of new ``Certificate/Attribute``s to insert. + @inlinable + public mutating func insert(contentsOf extensions: Extensions) where Extensions.Element == CertificateSigningRequest.Attribute { + for element in extensions { + self[oid: element.oid] = element + } + } +} + +extension CertificateSigningRequest.Attributes: CustomStringConvertible { + @inlinable + public var description: String { + return "Attributes([\(self._attributes.map { String(describing: $0) }.joined(separator: ", "))])" + } +} + +// MARK: Helpers for specific extensions +extension CertificateSigningRequest.Attributes { + /// Look up a specific attribute by its OID. + /// + /// - Parameter oid: The OID to search for. + @inlinable + public subscript(oid oid: ASN1ObjectIdentifier) -> CertificateSigningRequest.Attribute? { + get { + return self.first(where: { $0.oid == oid }) + } + set { + if let newValue = newValue { + precondition(oid == newValue.oid) + if let currentAttributeIndex = self.firstIndex(where: { $0.oid == oid }) { + self._attributes[currentAttributeIndex] = newValue + } else { + self._attributes.append(newValue) + } + } else if let currentAttributeIndex = self.firstIndex(where: { $0.oid == oid }) { + self._attributes.remove(at: currentAttributeIndex) + } + } + } + + /// Loads the ``ExtensionRequest`` + /// attribute, if it is present. + /// + /// Throws if it is not possible to decode the Extension Request attribute. + @inlinable + public var extensionRequest: ExtensionRequest? { + get throws { + try self[oid: .CSRAttributes.extensionRequest].map { try .init($0) } + } + } +} diff --git a/Sources/X509/CSR/CSRVersion.swift b/Sources/X509/CSR/CSRVersion.swift new file mode 100644 index 0000000..ae6e9e9 --- /dev/null +++ b/Sources/X509/CSR/CSRVersion.swift @@ -0,0 +1,53 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension CertificateSigningRequest { + /// The version of the CSR format. + /// + /// CSRs are conceptually capable of being evolved using version numbers. In practice, + /// ``v1`` is the only version in common use. + public struct Version { + public var rawValue: Int + + @inlinable + public init(rawValue: Int) { + self.rawValue = rawValue + } + + /// Corresponds to CSR version 1. + public static let v1 = Self(rawValue: 0) + } +} + +extension CertificateSigningRequest.Version: Hashable { } + +extension CertificateSigningRequest.Version: Sendable { } + +extension CertificateSigningRequest.Version: Comparable { + @inlinable + public static func < (lhs: CertificateSigningRequest.Version, rhs: CertificateSigningRequest.Version) -> Bool { + lhs.rawValue < rhs.rawValue + } +} + +extension CertificateSigningRequest.Version: CustomStringConvertible { + public var description: String { + switch self { + case .v1: + return "CSRv1" + case let unknown: + return "CSRv\(unknown.rawValue + 1)" + } + } +} diff --git a/Sources/X509/CSR/CertificateSigningRequest.swift b/Sources/X509/CSR/CertificateSigningRequest.swift new file mode 100644 index 0000000..f9d578f --- /dev/null +++ b/Sources/X509/CSR/CertificateSigningRequest.swift @@ -0,0 +1,217 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation +import SwiftASN1 + +/// A representation of a PKCS#10 Certificate Signing Request (CSR). +/// +/// Certificate Signing Requests are used to encapsulate information that an end-entity would like +/// encapsulated in a certificate. They are typically processed by Certificate Authorities and turned +/// into certificates signed by that CA. +public struct CertificateSigningRequest { + /// The version of this CSR. + /// + /// This project has full support for ``CertificateSigningRequest/Version-swift.struct/v1``. + @inlinable + public var version: CertificateSigningRequest.Version { + self.info.version + } + + /// The subject of this CSR. + @inlinable + public var subject: DistinguishedName { + self.info.subject + } + + /// The public key corresponding to the private key held by the subject of this CSR. + /// + /// This will be embedded in the resulting certificate. + @inlinable + public var publicKey: Certificate.PublicKey { + self.info.publicKey + } + + /// The bundled attributes for this CSR. + /// + /// Certificate Signing Requests can have arbitrary attributes attached to them. Generally these are + /// expected to be well-known attributes that will be processed by certificate authorities. + @inlinable + public var attributes: CertificateSigningRequest.Attributes { + self.info.attributes + } + + @usableFromInline + let info: CertificationRequestInfo + + /// The signature algorithm corresponding to the signature produced over this CSR. + public let signatureAlgorithm: Certificate.SignatureAlgorithm + + /// The signature attached to this CSR. + /// + /// This signature must have been produced by the private key associated with ``publicKey``. + public let signature: Certificate.Signature + + @usableFromInline + let infoBytes: ArraySlice + + @usableFromInline + let signatureAlgorithmBytes: ArraySlice + + @usableFromInline + let signatureBytes: ArraySlice + + /// Construct a Certificate Signing Request from constituent parts. + /// + /// This API is generally not recommended for use, as it makes it very easy to construct a ``CertificateSigningRequest`` + /// whose ``signature`` is not valid. However, for testing and validation purposes it is useful to be + /// able to do this. + /// + /// - Parameters: + /// - version: The CSR version. + /// - subject: The ``DistinguishedName`` of the subject of this CSR + /// - publicKey: The public key associated with this CSR. + /// - attributes: The attributes associated with this CSR + /// - signatureAlgorithm: The signature algorithm for the signature on this CSR. + /// - signature: The signature attached to this CSR. + @inlinable + public init( + version: Version, + subject: DistinguishedName, + publicKey: Certificate.PublicKey, + attributes: Attributes, + signatureAlgorithm: Certificate.SignatureAlgorithm, + signature: Certificate.Signature + ) throws { + self.info = CertificationRequestInfo( + version: version, + subject: subject, + publicKey: publicKey, + attributes: attributes + ) + self.signatureAlgorithm = signatureAlgorithm + self.signature = signature + self.infoBytes = try DER.Serializer.serialized(element: self.info)[...] + self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...] + self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...] + } + + /// Construct a CSR for a specific private key. + /// + /// This API can be used to construct a certificate signing request that can be passed to a certificate + /// authority. It will correctly generate a signature over the request. + /// + /// - Parameters: + /// - version: The CSR version. + /// - subject: The ``DistinguishedName`` of the subject of this CSR + /// - privateKey: The private key associated with this CSR. + /// - attributes: The attributes associated with this CSR + /// - signatureAlgorithm: The signature algorithm to use for the signature on this CSR. + @inlinable + public init( + version: Version, + subject: DistinguishedName, + privateKey: Certificate.PrivateKey, + attributes: Attributes, + signatureAlgorithm: Certificate.SignatureAlgorithm + ) throws { + self.info = CertificationRequestInfo( + version: version, + subject: subject, + publicKey: privateKey.publicKey, + attributes: attributes + ) + self.signatureAlgorithm = signatureAlgorithm + + let infoBytes = try DER.Serializer.serialized(element: self.info) + self.signature = try privateKey.sign(bytes: infoBytes, signatureAlgorithm: signatureAlgorithm) + self.infoBytes = infoBytes[...] + self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...] + self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...] + } + + @inlinable + internal init( + info: CertificationRequestInfo, + signatureAlgorithm: AlgorithmIdentifier, + signature: ASN1BitString, + infoBytes: ArraySlice, + signatureAlgorithmBytes: ArraySlice, + signatureBytes: ArraySlice + ) throws { + self.info = info + self.signatureAlgorithm = Certificate.SignatureAlgorithm(algorithmIdentifier: signatureAlgorithm) + self.signature = try Certificate.Signature(signatureAlgorithm: self.signatureAlgorithm, signatureBytes: signature) + self.infoBytes = infoBytes + self.signatureAlgorithmBytes = signatureAlgorithmBytes + self.signatureBytes = signatureBytes + } +} + +extension CertificateSigningRequest: Hashable { } + +extension CertificateSigningRequest: Sendable { } + +extension CertificateSigningRequest: CustomStringConvertible { + @inlinable + public var description: String { + return "CertificateSigningRequest(version: \(self.version), subject: \(self.subject), publicKey: \(self.publicKey), attributes: \(self.attributes), signatureAlgorithm: \(self.signatureAlgorithm), signature: \(self.signature)" + } +} + +extension CertificateSigningRequest: DERImplicitlyTaggable { + @inlinable + public static var defaultIdentifier: ASN1Identifier { + .sequence + } + + @inlinable + public init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + guard let infoNode = nodes.next(), + let signatureAlgorithmNode = nodes.next(), + let signatureNode = nodes.next() + else { + throw ASN1Error.invalidASN1Object(reason: "Invalid CSR object, insufficient ASN.1 nodes") + } + let info = try CertificationRequestInfo(derEncoded: infoNode) + let signatureAlgorithm = try AlgorithmIdentifier(derEncoded: signatureAlgorithmNode) + let signature = try ASN1BitString(derEncoded: signatureNode) + return try CertificateSigningRequest( + info: info, + signatureAlgorithm: signatureAlgorithm, + signature: signature, + infoBytes: infoNode.encodedBytes, + signatureAlgorithmBytes: signatureAlgorithmNode.encodedBytes, + signatureBytes: signatureNode.encodedBytes + ) + } + } + + @inlinable + public func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + coder.appendConstructedNode(identifier: identifier) { coder in + coder.serializeRawBytes(self.infoBytes) + coder.serializeRawBytes(self.signatureAlgorithmBytes) + coder.serializeRawBytes(self.signatureBytes) + } + } +} + +extension CertificateSigningRequest: PEMRepresentable { + @inlinable + public static var defaultPEMDiscriminator: String { + "CERTIFICATE REQUEST" + } +} diff --git a/Sources/X509/CSR/CertificationRequestInfo.swift b/Sources/X509/CSR/CertificationRequestInfo.swift new file mode 100644 index 0000000..92a3c9a --- /dev/null +++ b/Sources/X509/CSR/CertificationRequestInfo.swift @@ -0,0 +1,87 @@ +//===----------------------------------------------------------------------===// +// +// 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 SwiftASN1 + +@usableFromInline +struct CertificationRequestInfo { + @usableFromInline + var version: CertificateSigningRequest.Version + + @usableFromInline + var subject: DistinguishedName + + @usableFromInline + var publicKey: Certificate.PublicKey + + @usableFromInline + var attributes: CertificateSigningRequest.Attributes + + @inlinable + init( + version: CertificateSigningRequest.Version, + subject: DistinguishedName, + publicKey: Certificate.PublicKey, + attributes: CertificateSigningRequest.Attributes + ) { + self.version = version + self.subject = subject + self.publicKey = publicKey + self.attributes = attributes + } +} + +extension CertificationRequestInfo: Hashable { } + +extension CertificationRequestInfo: Sendable { } + +// CertificationRequestInfo ::= SEQUENCE { +// version INTEGER { v1(0) } (v1,...), +// subject Name, +// subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, +// attributes [0] Attributes{{ CRIAttributes }} +// } +extension CertificationRequestInfo: DERImplicitlyTaggable { + @inlinable + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + @inlinable + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let version = try CertificateSigningRequest.Version(rawValue: Int(derEncoded: &nodes)) + let subject = try DistinguishedName(derEncoded: &nodes) + let spki = try Certificate.PublicKey(spki: SubjectPublicKeyInfo(derEncoded: &nodes)) + let attributes = try CertificateSigningRequest.Attributes( + DER.set( + of: CertificateSigningRequest.Attribute.self, + identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific), + nodes: &nodes + ) + ) + + return .init(version: version, subject: subject, publicKey: spki, attributes: attributes) + } + } + + @inlinable + 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.subject) + try coder.serialize(SubjectPublicKeyInfo(self.publicKey)) + try coder.serializeSetOf(self.attributes, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific)) + } + } +} diff --git a/Sources/X509/CSR/ExtensionRequest.swift b/Sources/X509/CSR/ExtensionRequest.swift new file mode 100644 index 0000000..86491de --- /dev/null +++ b/Sources/X509/CSR/ExtensionRequest.swift @@ -0,0 +1,95 @@ +//===----------------------------------------------------------------------===// +// +// 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 SwiftASN1 + +/// A CSR Attribute that encapsulates the X.509 v3 extensions that the subscriber wishes to apply. +/// +/// X.509 certificates contain a number of extensions. This attribute includes the extensions that the +/// subscriber wishes the CA to embed into the certificate. +public struct ExtensionRequest: Hashable, Sendable { + /// The underlying extensions. + public var extensions: Certificate.Extensions + + /// Construct an ``ExtensionRequest`` from a given set of extensions. + /// + /// - parameters: + /// - extensions: The extensions to attach to this ``ExtensionRequest``. + @inlinable + public init(extensions: Certificate.Extensions) { + self.extensions = extensions + } + + /// Unwrap a ``CertificateSigningRequest/Attribute`` that contains an ``ExtensionRequest``. + /// + /// - parameters: + /// - attribute: The attribute to unwrap + /// - throws: If the attribute is ill-formed, or does not contain an ``ExtensionRequest``. + @inlinable + public init(_ attribute: CertificateSigningRequest.Attribute) throws { + guard attribute.oid == .CSRAttributes.extensionRequest else { + throw CertificateError.incorrectOIDForAttribute(reason: "Expected \(ASN1ObjectIdentifier.CSRAttributes.extensionRequest), got \(attribute.oid)") + } + + guard attribute.values.count == 1 else { + throw CertificateError.invalidCSRAttribute(reason: "Invalid number of values for extension request attribute: \(attribute.values)") + } + + let extRequest = try ExtensionRequestAttribute(asn1Any: attribute.values.first!) + self.extensions = extRequest.extensions + } +} + +extension CertificateSigningRequest.Attribute { + /// Wrap an ``ExtensionRequest`` into a ``CertificateSigningRequest/Attribute``. + /// + /// - parameters: + /// - extensionRequest: The ``ExtensionRequest`` to wrap. + @inlinable + public init(_ extensionRequest: ExtensionRequest) throws { + self.init(oid: .CSRAttributes.extensionRequest, values: [try ASN1Any(erasing: ExtensionRequestAttribute(extensionRequest))]) + } +} + +@usableFromInline +struct ExtensionRequestAttribute: Hashable, Sendable, DERImplicitlyTaggable { + @inlinable + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + @usableFromInline + var extensions: Certificate.Extensions + + @inlinable + init(_ extensionRequest: ExtensionRequest) { + self.extensions = extensionRequest.extensions + } + + @inlinable + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self.extensions = try Certificate.Extensions( + DER.sequence( + of: Certificate.Extension.self, + identifier: identifier, + rootNode: rootNode + ) + ) + } + + @inlinable + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.serializeSequenceOf(self.extensions, identifier: identifier) + } +} diff --git a/Sources/X509/CertificatePublicKey.swift b/Sources/X509/CertificatePublicKey.swift index 4ca9803..15c6288 100644 --- a/Sources/X509/CertificatePublicKey.swift +++ b/Sources/X509/CertificatePublicKey.swift @@ -102,6 +102,21 @@ extension Certificate.PublicKey { return self.isValidSignature(signature, for: certificate.tbsCertificateBytes, signatureAlgorithm: certificate.signatureAlgorithm) } + /// Confirms that `signature` is a valid signature for `csr`, created by the + /// private key associated with this public key. + /// + /// This function abstracts over the need to unwrap both the signature and public key to + /// confirm they're of matching type before we validate the signature. + /// + /// - Parameters: + /// - signature: The signature to validate against `csr`. + /// - csr: The ``CertificateSigningRequest`` to validate against `signature`. + /// - Returns: Whether the signature was produced by signing `csr` with the private key corresponding to this public key. + @inlinable + public func isValidSignature(_ signature: Certificate.Signature, for csr: CertificateSigningRequest) -> Bool { + return self.isValidSignature(signature, for: csr.infoBytes, signatureAlgorithm: csr.signatureAlgorithm) + } + @inlinable internal func isValidSignature(_ signature: Certificate.Signature, for bytes: Bytes, signatureAlgorithm: Certificate.SignatureAlgorithm) -> Bool { let digest: Digest diff --git a/Sources/X509/Error.swift b/Sources/X509/Error.swift index d135795..8d34092 100644 --- a/Sources/X509/Error.swift +++ b/Sources/X509/Error.swift @@ -141,6 +141,34 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible { ) ) } + + /// A CSR attribute has the wrong OID. + /// - Parameter reason: A detailed reason detailing the attribute and OID that didn't match. + /// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/incorrectOIDForAttribute``. + @inline(never) + public static func incorrectOIDForAttribute( + reason: String, file: String = #fileID, line: UInt = #line + ) -> CertificateError { + return CertificateError( + backing: .init( + code: .incorrectOIDForAttribute, reason: reason, file: file, line: line + ) + ) + } + + /// A CSR attribute is invalid. + /// - Parameter reason: A detailed reason detailing the attribute that is invalid. + /// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/invalidCSRAttribute``. + @inline(never) + public static func invalidCSRAttribute( + reason: String, file: String = #fileID, line: UInt = #line + ) -> CertificateError { + return CertificateError( + backing: .init( + code: .invalidCSRAttribute, reason: reason, file: file, line: line + ) + ) + } } extension CertificateError { @@ -157,6 +185,8 @@ extension CertificateError { case incorrectOIDForExtension case unsupportedDigestAlgorithm case unsupportedPrivateKey + case incorrectOIDForAttribute + case invalidCSRAttribute } fileprivate var backingCode: BackingCode @@ -183,6 +213,12 @@ extension CertificateError { /// The private key isn't supported. public static let unsupportedPrivateKey = ErrorCode(.unsupportedPrivateKey) + /// An attribute has the wrong OID. + public static let incorrectOIDForAttribute = ErrorCode(.incorrectOIDForAttribute) + + /// A CSR attribute is invalid. + public static let invalidCSRAttribute = ErrorCode(.invalidCSRAttribute) + public var description: String { return String(describing: self.backingCode) } diff --git a/Tests/X509Tests/CSR Vectors/cryptography/LICENSE.APACHE b/Tests/X509Tests/CSR Vectors/cryptography/LICENSE.APACHE new file mode 100644 index 0000000..62589ed --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/LICENSE.APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + https://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 + + https://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/Tests/X509Tests/CSR Vectors/cryptography/bad-version.pem b/Tests/X509Tests/CSR Vectors/cryptography/bad-version.pem new file mode 100644 index 0000000..32a33cc --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/bad-version.pem @@ -0,0 +1,7 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHJMHECAQEwDzENMAsGA1UEAwwEVGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEH +A0IABJjsayyAQod1J7UJYNT8AH4WWxLdKV0ozhrIz6hCzBAze7AqXWOSH8G+1EWC +pSfL3oMQNtBdJS0kpXXaUqEAgTSgADAKBggqhkjOPQQDAgNIADBFAiAUXVaEYATg +4Cc917T73KBImxh6xyhsA5pKuYpq1S4m9wIhAK+G93HR4ur7Ghel6+zUTvIAsj9e +rsn4lSYsqI4OI4ei +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/basic_constraints.pem b/Tests/X509Tests/CSR Vectors/cryptography/basic_constraints.pem new file mode 100644 index 0000000..1d5726d --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/basic_constraints.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICwTCCAakCAQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYD +VQQHDAZBdXN0aW4xDTALBgNVBAoMBFB5Q0ExGDAWBgNVBAMMD2NyeXB0b2dyYXBo +eS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKQarmOirSMKt6Lw +DlD9luEClgUHcsiWp9ap9hn9YZiayphcQWkM8vgn8sR9/m0InveZLPetRZeXw+tM +1wPhMid3vnN0O2IfZseDPERFdqjxNACE/UP4LpUALzT1ydZnROFlQkLBU198R7Jl +ptWtyJoTC1jEuULHTXbAmVedsDPs+N2jYYYf373YVq4Nv0HIsWmKKt/PKgUlijRs +Mn6Mc/pBGleQPV+J4bTGv5ZQt2L89yATbSXMsE89S4XVMUqiM/n1H+nB6AMps99l +UYAnKz7Tg7L6gBsDQ1YHJvDpWGS73H79wYjhEFROo/ZnbMlUPZyNYkO+MXfUw+45 +PLDr5asCAwEAAaAlMCMGCSqGSIb3DQEJDjEWMBQwEgYDVR0TAQH/BAgwBgEB/wIB +ATANBgkqhkiG9w0BAQUFAAOCAQEACopwmBxoZQS7awyTkAPolCEIHa/mWSonsfeA +w6oK3YsHZ37PrJnHyXDY8hMyJbkDfbc32vTWQwC+gP19bQX3oOg+aYq3REY8WIco +ch7rMVAmJTkOV4W1KKJqDfWIcPS8gdaHTvLKZBuG1QQtHtYyACMEi7CaqYxbYC2e +6ld60uO08PQMCFSvkeO0YVGRfmBPCm7bZTgaTzUH5wgNCjk+e0q/A/ZuW/RHlVMi +IbmR2w528Q9vgqUPt2XPGRKeZ05fwbKnAtfkalXeNVIyTUWrs/yCPW1lnL5sgZoQ +miL4dd6c9GHebII6X1H0e7cUaAusKxZ2Rl48uwPd3BIXcAZLPA== +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/challenge-invalid.der b/Tests/X509Tests/CSR Vectors/cryptography/challenge-invalid.der new file mode 100644 index 0000000000000000000000000000000000000000..dfea50244c31876b09ec1d781c71ab4ca5cce057 GIT binary patch literal 633 zcmXqLVk$LgVvJ>CWH8`0f@Un4gwRyCC=VfGMWMyD(V&rE4 zigPhFF)}jD{`uVGY=eZprM-cr)sk{Tb+;kWBR;c$@GtbSxs%9wiZpd z72G1n&9b$sOIRU`cklD2^-TYkrl-|ME573S?R6&B{IB(VjUeO0R&nlgeqCJMud!AB zb7|%uvACY{$kPW+_vGC%|LL;maK6vlud5c$n6or5{%zh5&Z?uIW^=A|J)0l1SKjh@ z$hHTZ_eD&foYidDShK?N$8?p>^Ld5uSNSA-?|uGl_wgqa|5^OG=Dsp?Y345ZZ>^87 zK6@h)Up;M+T@I7iK`!-24=z8bcFrtcG*2`7`l(CjP9^?-{B(Wz-r57o`;4`ov`u&S zT*=96B<0YPvod^Y$Z~%j=95g!j0}tmlnoT&VZ_O9D8eKpz<>rAk%N&N9E^+%Mj3LR z>vhiVI4@%VWAEXE>wg~<6mFGb`ZKfk#j}aEO|yQ_m3XMLAf;jUQ@6aH?9%t8-|g2= ze0g(1F!OH7)Q+OcH^*vJc>i+5W=H?qpu_h3kn*1NL!Np!o?TojAYx%){>6Fo4O^Wk zQ%6Sm-7kKeyYj0r&s1|$RCJX`K+vR)$cb5^9y#S&2l##}uqVztxotIr_xH3n=1-R& z+E`&>eb}&(mnBmoj%i76sFUF&Rn|*_7yha5T)Rh*kH1bTSN!U0<0;a{eT$33gxByc z?a;lz_aH3hQquH-RR*zp80N>yuKt(3@4-rjy&W~t42yh^DM(qCEwzod?r@oTsKixu J)8CKH9|3v}4@&?5 literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/challenge-multi-valued.der b/Tests/X509Tests/CSR Vectors/cryptography/challenge-multi-valued.der new file mode 100644 index 0000000000000000000000000000000000000000..d7d6833a18b07ea43cc662ea34af3238adec1c82 GIT binary patch literal 643 zcmXqLVyZW2VoYaZWH8`0f@Un4gwRyCC=VfGMWMyD(V&rE4 zigPhFF)}jD{`uVGY=eZprM-cr)sk{Tb+;kWBR;c$@GtbSxs%9wiZpd z72G1n&9b$sOIRU`cklD2^-TYkrl-|ME573S?R6&B{IB(VjUeO0R&nlgeqCJMud!AB zb7|%uvACY{$kPW+_vGC%|LL;maK6vlud5c$n6or5{%zh5&Z?uIW^=A|J)0l1SKjh@ z$hHTZ_eD&foYidDShK?N$8?p>^Ld5uSNSA-?|uGl_wgqa|5^OG=Dsp?Y345ZZ>^87 zK6@h)Up;M+T@I7iK`!-24=z8bcFrtcG*2`7`l(CjP9^?-{B(Wz-r57o`;4`ov`u&S zT*=96B<0YPvod^Y$Z~%j=95g!j0}tmbPcrOVZ_O9D96K_oROH5lbV;Fs*szih{i<@ zP;PL5GBOxt$a${UIlJS$i2aYfhYzm*eNa%iRf_4)%-R>vCe}91`aM_Tq0WMohS^Wu z@_MpM-fLyDajAfa zg@O4O=gl{4b)rli8Rd7s_;K#aufjZ2%}r6!RUQFBlR6?NW{G;_lxrQ}`>DX5IPc`P z)ePR>)83drU4Cd|g@yHD!$w|~Oo=$ACB30ehLcoTF9}}wr@nLT9zj0-I;mXotFMix zNE`PpE)El3!@IOY_X6L8u$W6p(+gG^#O`63A1k~1U-rHSD;f57)I>8Z@;#;?Wm&e= UHrl$wW#*w0SJh2_KQ?~^08jlG_5c6? literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/challenge-unstructured.pem b/Tests/X509Tests/CSR Vectors/cryptography/challenge-unstructured.pem new file mode 100644 index 0000000..95a92ec --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/challenge-unstructured.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICljCCAX4CAQAwFDESMBAGA1UEAwwJc29tZXRoaW5nMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEApDAVEIXi90VT6Q8sCYl0sdzZaxIW5fGtk5M8Vmoe +iQbpWJtYZwQzOjOhgo9/+f/+Heg5gUI4+zUWyZMjh90KB5WrdTGO1x0yEUGjT15/ +VARFPmhyVniClEXPj4pANYVR00jMyvlLJuigKZbYR7VBTuE8oKOn2lu3eXuPFf6s +8bLjSHLuTS7t13LDlrO1jh2RvSKeQDwQP7ZHWzjTASW3H6bZla8lSx/6Xhvk5aJQ +JSMcEIYwPp7tP6+HV8E+FNjU19UZ3TsvGm60ZdoaCyFocgRFFju2wNSegmKzm00k +bAum7RR4dcso58vrkUz5AbZchdQ3dh9rRsggxgV/F5lMkwIDAQABoD0wFQYJKoZI +hvcNAQkHMQgMBmJlYXV0eTAkBgkqhkiG9w0BCQIxFwwVYW4gdW5zdHJ1Y3R1cmVk +IGZpZWxkMA0GCSqGSIb3DQEBCwUAA4IBAQA3lwNp3HtDQjzkqxv9SvUCH6C9UEh0 +6+SWklP2ce2IWmoHHnfYW2SyPAhzR1q2gSu7IVZhM3WMEJRoiqN2ZFQed++0b91n +LdUdCnDob8EFuX0AP7I4A9LI7G2bMS6mpzQBDXoo5hAlJV8I7Zq7NIby54bQiTgn +B8cYopnmrLfCn1H8Su8oBgPNg3glOQSAkvZfqhHNTJyAnN+5+boFWpReAe8p/cfr +kZh+fS8TcP7GbSLMnDlNwCAEIYRfAW7MVXJZ0l0tuDo7XdPImQgjjHYCk0tKPbeb +LVyIAPNkMYLu7II79OOi8h1cZfU6wWwUIIhjMzjLpdZBPyhhGnUQzfuZ +-----END CERTIFICATE REQUEST----- + diff --git a/Tests/X509Tests/CSR Vectors/cryptography/challenge.pem b/Tests/X509Tests/CSR Vectors/cryptography/challenge.pem new file mode 100644 index 0000000..71ff39f --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/challenge.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICcDCCAVgCAQAwDTELMAkGA1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQCb+ec0zYAYLzk/MDdDJYvzdvEO2ZUrBYM6z1r8NedwpJfxUWqC +hvK1cpc9EbQeCwS1eooTIGoNveeCrwL+pWdmf1sh6gz7SsxdN/07nyhSM8M6Xkec ++tGrjyi1H/N1afwWXox3WcvBNbxu3Df5RKLDb0yt9aqhmJylbl/tbvgJesXymwmp +Rc1vXL0fOedUtuAJ3xQ15M0pgLF8qDn4lySJz25x76pMYPeN5/a7x+SR/jj81kep +VaVpuh/2hePV5uwUX3uWoj5sAkrBCifi4NPge0Npd6KeKVvXytLOymH/4+WvV719 +wCO+MyrkhpdHSakJDTIaQIxsqVeVVKdPLAPJAgMBAAGgHjAcBgkqhkiG9w0BCQcx +DwwNY2hhbGxlbmdlIG1lITANBgkqhkiG9w0BAQsFAAOCAQEAMmgeSa8szbjPFD/4 +vcPBr/vBEROFGgL8mX3o5pF9gpr7nRjhLKBkgJvlRm6Ma3Xvdfc/r5Hp2ZBTA7sZ +ZYhyeezGfCQN/Qhda1v+sCwG58IjvGfCSS7Y5tGlEBQ4MDf0Q7PYPSxaNUEBH7vo ++M7U+nFuNSmyWlt6SFBSkohZkWoVSGx3KsAO+SAHYZ7JtqsAS/dm7Dflp8KxeDg7 +wzGBDQRpGF4CpI1VQjGSJQXSEdD+J7mtvBEOD34abRfV6zOUGzOOo3NWE6wNpYgt +0A7gVlzSYpdwqjBdvACfXR2r/mu+4KkAvYh8WwCiTcYgGjl2pT1bO4hEmcJ0RSWy +/fGD8Q== +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.der b/Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.der new file mode 100644 index 0000000000000000000000000000000000000000..3a0cde2f6057ff9ec873d17338db77e8df0bbccd GIT binary patch literal 339 zcmXqLV)Qp?yvD@HU=VI7VIaoF9LmDX!=GGKSx}OnUX)mnQK^@iZ^&!F4U*yFVF{>o zb~NNR-~@5mgqcEv4fzasKpYMp){xYS#9~8!16~lHorle_w74WQ&!EgefQ?n! zHa+m|Hd-3U+{?+4!MyD9?}-Z+iq#!ZjM%{U>++n*)7$$&g{nc^96kM>W*1hONsj3*a;0P>ppz hG{5e7)7#RBr_z7RR=M8KojLF7kz|wlM;5x`fdFmAeZ2qx literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.pem b/Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.pem new file mode 100644 index 0000000..9497ae3 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/ec_sha256.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBTzCB1gIBADBXMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8xDTALBgNVBAoM +BFB5Q0ExCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEPMA0GA1UEBwwGQXVz +dGluMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3hm1FMCzw66bOY6j4mtegWvc+RAs +rY8S/gL55MkkhySzkpftdYLgTYsypVEDjQkIaAOm0/uRoaEWfsAhWLAO+tOck5ZG +L6zP8P+vcVWBKQnTcmvVn94AHP9LubL1r4y6oAAwCgYIKoZIzj0EAwIDaAAwZQIw +LBqffejBeHMy0jB6iGtHalnxcrmw4lAmLzI4sbRe4RK7brNbD7VqEjuSlushLf/D +AjEAlM9EDJXFKCfVVq5tdlAOMAglXUfCn37ngu11WOUb/XaqRd9tmZ7VxGM0f+I4 +LRdR +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/freeipa-bad-critical.pem b/Tests/X509Tests/CSR Vectors/cryptography/freeipa-bad-critical.pem new file mode 100644 index 0000000..ca83b53 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/freeipa-bad-critical.pem @@ -0,0 +1,23 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIDqzCCApMCAQAwLzERMA8GA1UEChMISVBBLlRFU1QxGjAYBgNVBAMTEXJlcGxp +Y2ExLmlwYS50ZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5TzQ +ZpKgWu4v4LmX44xRCgA2DcvY4D7Lw/Zyr3uch54gvAUWi2oi/PYVixJQNVHfZIck +grPRO+gtMaFsXuIHgWHjy2TdFNOV5Uav3W07fl28nngmAWd8Sq4W+i7vnBMp62sz +tE0nomTUe/52D+V3pggCzqVlvFvAg8IqxyavDQ974I13V2SuvJVJ7EnlaCnNZPRX +L1ICnszKfIhoLWH8cbBaxHCjZkHEInu87qb9OHNpevrz5OJMX2HG14Ic15I52l0Y +VTBQQr1AQFGDNpSqt+NeoCSiY9F7nhEXdkgvhk3rMV2nk2XJut9YIsEJYo4SK0pB +TxdSUYHsyZqrP/cdFwIDAQABoIIBNTAlBgkqhkiG9w0BCRQxGB4WAFMAZQByAHYA +ZQByAC0AQwBlAHIAdDCCAQoGCSqGSIb3DQEJDjGB/DCB+TCBkgYDVR0RAQEABIGH +MIGEghFyZXBsaWNhMS5pcGEudGVzdKAvBgorBgEEAYI3FAIDoCEMH2xkYXAvcmVw +bGljYTEuaXBhLnRlc3RASVBBLlRFU1SgPgYGKwYBBQICoDQwMqAKGwhJUEEuVEVT +VKEkMCKgAwIBAaEbMBkbBGxkYXAbEXJlcGxpY2ExLmlwYS50ZXN0MAwGA1UdEwEB +/wQCMAAwIAYDVR0OAQEABBYEFPtLvk2RcgKwKfIo0Cp8Pvp7Xu3wMDIGCSsGAQQB +gjcUAgEBAAQiHiAAYwBhAEkAUABBAHMAZQByAHYAaQBjAGUAQwBlAHIAdDANBgkq +hkiG9w0BAQsFAAOCAQEA1jEX9uXSAvDjP6ZRxT5Wo2DWy4yqJx5+tO21jrpRgCKu +owUhwyzEFiA/WDQ/vy9XGqvcRaRpkdbwrcmefvUCgprOBeNjR1F2aKTHngaH4WbW +d4BI0lR0Z1WZuvL2fRGDvOCQAGNVyGvtxV+15olWq7386fEe3PAHF9osXpcH97Ki +fL1+eG2Vkaqo4yylUGme/Rin4vGzxkjGYE+O/ugxtgil5VPs0nrJx0bFWaMLK9yE +rv9O1V3JSKoLn+yAKxrYQuMBl1nqpAj9P4NWdFsGl3Ubpn4vwitwaq9pkEu0K1Z+ +CP5FXOyFsgEGKncL4gub8IQC720B25A8YowGTk3BNw== +-----END CERTIFICATE REQUEST----- + diff --git a/Tests/X509Tests/CSR Vectors/cryptography/invalid_signature.pem b/Tests/X509Tests/CSR Vectors/cryptography/invalid_signature.pem new file mode 100644 index 0000000..f95bd17 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/invalid_signature.pem @@ -0,0 +1,10 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBTjCBuAIBADAPMQ0wCwYDVQQDDAR0ZXN0MIGfMA0GCSqGSIb3DQEBAQUAA4GN +ADCBiQKBgQDOdf0xwr1fUP0+wtYfwi1sqAe78WNSONLjtGYSpEFBNS9T6dW+m3vj +EaEZ0dI7B+Y5jC53JG8vSoBN/xLzw/CCDgLq8OvftOeS4+FZqznRDucgzbqctVzs +PshGcfZ3n8DIiEBbSqeMvs02spKXvYxi3M2S5aJ2GVl2wNlzRLcTuwIDAQABoAAw +DQYJKoZIhvcNAQELBQADgYEAZ7Jbqn9hhMYJ+y4ikTNG6GNu48GINyzXXX3bzv3O ++xGnKbjp99FbJKDOalnG492kZKyg2cCC5UQW8SNZOQpfnjsguB3HZoOrRlExkavY +IapdMZiK5g6ocViceV4gRybkW/Yh3p7cFzOmaABAWzeyJm3/TcTWBLvx/M7Mj1pE +8f8= +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/long-form-attribute.pem b/Tests/X509Tests/CSR Vectors/cryptography/long-form-attribute.pem new file mode 100644 index 0000000..a8bc156 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/long-form-attribute.pem @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICZDCCAUwCAQAwDTELMAkGA1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQCb+ec0zYAYLzk/MDdDJYvzdvEO2ZUrBYM6z1r8NedwpJfxUWqC +hvK1cpc9EbQeCwS1eooTIGoNveeCrwL+pWdmf1sh6gz7SsxdN/07nyhSM8M6Xkec ++tGrjyi1H/N1afwWXox3WcvBNbxu3Df5RKLDb0yt9aqhmJylbl/tbvgJesXymwmp +Rc1vXL0fOedUtuAJ3xQ15M0pgLF8qDn4lySJz25x76pMYPeN5/a7x+SR/jj81kep +VaVpuh/2hePV5uwUX3uWoj5sAkrBCifi4NPge0Npd6KeKVvXytLOymH/4+WvV719 +wCO+MyrkhpdHSakJDTIaQIxsqVeVVKdPLAPJAgMBAAGgEjAQBgkqhkiG9w0BCQcx +A38gADANBgkqhkiG9w0BAQsFAAOCAQEAMmgeSa8szbjPFD/4vcPBr/vBEROFGgL8 +mX3o5pF9gpr7nRjhLKBkgJvlRm6Ma3Xvdfc/r5Hp2ZBTA7sZZYhyeezGfCQN/Qhd +a1v+sCwG58IjvGfCSS7Y5tGlEBQ4MDf0Q7PYPSxaNUEBH7vo+M7U+nFuNSmyWlt6 +SFBSkohZkWoVSGx3KsAO+SAHYZ7JtqsAS/dm7Dflp8KxeDg7wzGBDQRpGF4CpI1V +QjGSJQXSEdD+J7mtvBEOD34abRfV6zOUGzOOo3NWE6wNpYgt0A7gVlzSYpdwqjBd +vACfXR2r/mu+4KkAvYh8WwCiTcYgGjl2pT1bO4hEmcJ0RSWy/fGD8Q== +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.der b/Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.der new file mode 100644 index 0000000000000000000000000000000000000000..e9a3e953b485c52e321b7f33e6ae9402087965e6 GIT binary patch literal 672 zcmV;R0$=?wf&!c{f&qjA0RS*pF&How1_MTzNFbf6) zRRjtQ1Wl%2^1gsBcm!jK8=`@_i-; zCeiE}{Wjny4@?JZ6GHCGj%J_4EjZ>E)!T$yoG(dPJ8$ORsDKq+?AU z2+!t=klt@;S!sD6q)@gFTMjC2F3UNxclsOK`qFx7d;0IOoMepD$C!@fxks|AK}G%? zoUrG2F_1y>k#{Tt`?p&fXQiCWNKj3PPNgN4CF1e?>7^yAuy_m3+}E8hPfcjJN~xlM z3V#5nxP4ix4PNcTJcy_CM{;d>s>D^y^ei06+k(vUv0s{d60iXad4F(A+hDe6@4FLfI z1potr0RaH1_5UIU+v0C30SA@7htyIc#>@S-IOxpZjzyXZy+!~aw-x8k^UAD2hDkQb z>a23Gm%vF-++XFg%*a`?EpJ1N7NPS8=-vBcqRnp9T|u{fMR2~pq-GI%AnmV*~u`36!EbO0_r2b6;5jfE(06A`t^>* GG=h4t{2I~# literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.pem b/Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.pem new file mode 100644 index 0000000..f62c8ef --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/rsa_md4.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICnDCCAYQCAQAwVzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMQ0wCwYDVQQK +DARQeUNBMQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxDzANBgNVBAcMBkF1 +c3RpbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMpZCKiob1IpjL+4 +S/J9Jgcm0ewZ/TbgJw9MB2sTQu7Ljmad9MttNeMyd9wa9fQIhenlpKjJWPSBekSX +P0uvbAKkY00eCM/mi5Deb2lZaXkfpFC2DlsOKm4uyzmyd/ob2/rSeml7+u+xnGSM +1MeYjuS5R7KrQUX+HJyw53cxkEHykXcsAvu3WxpnpZzLSFBNiE6lJZUl4vH86aUl +qrB4C87c150uT01ouEqpon8KfwCnuH1Zqw1e+XVoW6sMqvkoqx2uSJxlMzlWpXhI +rd3bMXHJ+mJyuDP5UVhQU0WuWXPO1JzEfVwVKigbpy8heHare/6tFHXp3V98fhEO +qJGaArUCAwEAAaAAMA0GCSqGSIb3DQEBAwUAA4IBAQCp9f8iBtvibyoBB5W+h9RS +IsbL/bY46MzfjkWaCr1GACC3FefO88qsQYZJNsnqrHKwl8BJUNxf5bLMyFmyLW9D +jBah8wfo3ftjos1u1F1Bt31FcL7UlDoDLZ1LA3cP/JodSbUVZ8ByVI1bj0MRdAx5 +16YNJvCtzXQtoRZxr940u+S10G6E8sSwfGjqJIgOTiF3oYmS1hSBsIGJzrJ4HOp/ +FAN5pxYW3C0sAM4Aq7qSRHQdFoIXovgRxB4XFedIveEidralOe1K0ShV675jmjwa +zoO/bTZGCIISD3KoIaCdkJjKoN0r2ckwhBTxsQsC6iO/FU5rBS4DG7369Y7FNIJ6 +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.der b/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.der new file mode 100644 index 0000000000000000000000000000000000000000..5bd63147d4a5e0060503d306f2d752235d49ad9c GIT binary patch literal 672 zcmV;R0$=?wf&!c{f&qjA0RS*pF$*vW1_MKtMFbf6)RRjtX1Wls6eNLV9SOOX5XU(T9mqM z@wcm;B*$UT{oKOKUOyefxH2yZoUIKTI}RM2P9 z)$@e$^76x+!?9Eq;$wwW?}P$misSDHGjAfd?8ekH94jHi2^xQTl^7TYRHjB`3t&N> zOvd%cm=Owp0}5lG=zcS_cWwOHlavm}cB@yRfvts@g?V<|Fh81CJf<0|KjoG(j*@_D zf`)_b!F8aEzo^hh(iM$8js}{bU#MF$a;ve#v_dOmX7jfWWFvR6Ma^Pa<>gq9212R%MK+n3qAg1$NVK2&pt+IzzF8az@YrXQddcvEF-8 zq2;&h>J*en0D+4dl01M<5(*7sPh$}8dFWv$Rl=|x%zs(m+s+NM@?#GeUr2I{28di40*W5u^{E|hciXB9NttfopvDVTwj0oZ zpo_Cgr}N-`k@J6Q5oBB9*kw!=aNODyUf0Z$0e^i{B3*wdKQvkFTiQX-ZP#5xXKYk7 zgE&$qx8(XM$a9|?4zC%O6InTtmzZMXVS(tx!f?Y>xAiO%jj^`|If64J$Lb_`8+*go G0AD-8rWPjv literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.pem b/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.pem new file mode 100644 index 0000000..0656c31 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha1.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICnDCCAYQCAQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgTBVRleGFzMQ8wDQYD +VQQHEwZBdXN0aW4xDTALBgNVBAoTBFB5Q0ExGDAWBgNVBAMTD2NyeXB0b2dyYXBo +eS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKhAp4Rgy4YQZt+j +BFqUumzxt6udJMdhz/3cwstePx3D5L4lPnA57xT+nW0jBPUNny4VhMUVMKt1CG81 +cTi/97hU0GfR1fOE8fLyw5zDsVQV4mOFVO+EAmSK4+8IM28it+zG1DMcKyHDCRp/ +epUYGAdUpkZkC2BBnkzG9ceYEQp/Awpjn+h+M7R3bfzZk5QOx3arV6GBrYWYhXl2 +3DA/mlc8phmrP+WWMo6SgGuChoPtwXzCVrQZSKK/qNBH0hWNPY4GmqBfqFsycqux +xLRCK2Nm87cOZCN3sUXNYlnl0+fbBI1Rkh5Qdmo3sbEw7msR9QfSCoNAAejeFqks +FPLpZKMCAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4IBAQCDZMhv+7/gv8miH4MSVmWM +qJiXQbgFdtNvCKk0YDpDsYNyRtABZ6UYq7Hee1Gh5bfr6hSUSACBixqSPIBPEgoN +Yk9jEO956GEnVcKwHcx/Wd/bzg2z8mMPGF9QS4wXr4DL02T6X9poM3FTkwlIImzU +Y4KHoK7WUk0wBohcGQKKHuL1qR1ud9uqC0mZbuCgxgtVthvQgKCLs0qn8+B+kfN/ +ahFkW+LYZUwVcNzaFF7XzJIBf31TIl1/KD80Wexb2kHPbdddQ2dsVDSDOFImt+T6 +KchznxsOrxmWE1k5kZeYYuNhgejEwnDDVLf1LBKNsbcGOYIzJMfqJHkbe8PXAF87 +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.der b/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.der new file mode 100644 index 0000000000000000000000000000000000000000..5c197754fcc2f67f710c7ae58a31f69e28f74381 GIT binary patch literal 672 zcmV;R0$=?wf&!c{f&qjA0RS*pF$*vW1_MKtMFbf6)RRjtQ1WlwXA7ibGnqzoG(DdEuC$f zP6-$UM1qU?B~HbmU0zB*PRW~4CN>!lF@(F}4@7m4N$JdwutWXMLbj@3D=4{P6(*fK zFR&KZi(~@}sQ8?`{ObEPO3n(?lQ(C?JLpsMSfOf%2IMRo5k&+*WV2t@$&T!mP!wsR z?BW$> zBzfA^<>FegZcW+Fn3Cb^5aPc!{k&PL)Gr`uPy%j~n1@4OzvK=qre>>OdT*kvOd;Zb zN_g(^dG=4E14xb-`_kL0nNbcIc`T|q-4v|)iBiMeld(J@_6 z_Op6vKk&a_X<@UIVt>XO9F1MUO%)7>nCF^|zgwZca<|}V2ufYl;{FvbZre(O$6{>F zg3(Y+t2b?xQqN&6G++tE7t&e8SeeX;HuUBdD`v8$xHMbBQ?u(nwy`jo`Lz*AI7p4# znyP?Dp&tOgm_qpPO&gkvG@xC`iDtQpFmeD5tH0)azFJd^m%VQVYhEtx1hf%XlAGv9 z*FJtDE#Im_J?<7xk;z@d%OgG9zZ+2|m)Zk=EG~Jl>B4AacDIu&y~^K2H?|SF=ct<~ GIV-%ex*5{| literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.pem b/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.pem new file mode 100644 index 0000000..06393d2 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/rsa_sha256.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICnDCCAYQCAQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYD +VQQHDAZBdXN0aW4xDTALBgNVBAoMBFB5Q0ExGDAWBgNVBAMMD2NyeXB0b2dyYXBo +eS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALWsaWBzupTPnC9A +xS2dbZtOCRgERIKL+SVOxaFdXko/TsmbUCY2GQ8xhLvhD0R1kEnpzI+wQ/3OQraq +XysouWEVJp07L7AW14tkAwuo+Jy8/Or7NUrOCtOTN2fEO+hT81ihaocG5CwbEUUE +QGSzX9XJjuyVUBRpou8muv0ZRcrJG08AP9pss4MMjkvTEfX6ldht9NWXlTz2AnOL +MR4WSLS1H/Imv9OtO+nFkLUkedrV5eJasW5N2c6YkuHrEOK/Nv28WavULyBpUAJu +k5iHQ1+/5A4spmarX3pvoqxMIeJ/Snju8Xn2T6MDSI4Y+9LbqplRDhl5LKo53RZi +z4JKq8kCAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQCgpYRnfdC9BjlohcdiUjqz +jzzQgRs8+29YFRyQHfHHT0K0YYEeiblvdNExXVD2s3ppP/C/X2lhs5Nif8YaHI1d +wU0VDIeY55qMv1uhvnK34GkISl3U4v4VLm7bSoPHYmzNgtFQTKs3bZVSz2EtNGAJ +xRfSWcRYmcyJNvTmFStmsqa4NFvCU7PrPraxMJn5tRFJOEiN25qqgEehHwC+mEL4 +700bmos0oF3IiWa5iTByAA2rv+Z8vlpTjJe9bwVrXi7tBLQRV5Kb6EfXPn4jLd+q +Qj3uFk6RyV3DyyM93L8bUSaX2gN/LC55sOnCaGR2t5MrvcrfRDe2EbrnqJsoOSu8 +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.der b/Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.der new file mode 100644 index 0000000000000000000000000000000000000000..c950e2e669130abe44886e06dd19b27ff2bf5346 GIT binary patch literal 742 zcmXqLVtQoI#CVE{k-;F^klTQhjX9KsO_(V(*ig`bAH?C{;qc7K$;`{oEH)G{-~$P< z^RPQ-WF{x3=Ns}GaDzm+cvu1|ogED&48%ZOW*+|JqRN7j{Pd#4f{aSN%zU67N(Q`a zoLX%jZQpqr85vm_n41{+8GzzkOihf84695{MD&FoPyUj$)@n)}|4&<05yuBfCey1k zibQJPzl+OX_+x7QVfo!lmR5v*db5c4YVl;RL)E3v{^^t!9Vm}Mwa$jOL>o@5mPE1-m)!VKmT~Sn1k=mIWm_| zJ-n(uwSU@sk8{^EytbH0Dg9_)qU~XD@pRlNtD{r4Zn65Cec;rsjh=U2o}bs%e@ZxI zt<&0DSDBtJUwlg}wVFLLXW^~mJ}JM}8TgBQU2(-WNoS4h%`0U*uVS4XmAV%EP3k#n zyEO1(>8HxdKPCY+bDO&R>-`;g=37_Tee%s0xPR+ul97QT6Eh#Cm1j{XJdZksbtGtJ)KQ|ohfQpLMz&Of;3qUo4m)!S(6lwa`UOP06} zgR}MgZ`}-Q-cI}K@uuKwYepc;pViiVZ%q3xb(~_~b7lI)mWqXo^u9`R>Brb_Z@4i1 z$0Dnvm3DIudi`x)oA`6nX@;j?CKU*TiMJlqDeHZr@?&mU<9c?k<2u_f8@_3u`E#cO ukLyu}4c8Y&+895J-}dcR3`0Sv*U1tsQK_rVN`5tVf2^;ZZ(q5^ybJ(~zdU{b literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.pem b/Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.pem new file mode 100644 index 0000000..1db2bc1 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/san_rsa_sha1.pem @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIC4jCCAcoCAQAwWzELMAkGA1UEBhMCVVMxETAPBgNVBAgMCElsbGlub2lzMRAw +DgYDVQQHDAdDaGljYWdvMQ0wCwYDVQQKDARQeUNBMRgwFgYDVQQDDA9jcnlwdG9n +cmFwaHkuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqNTQULxLj +k/RirTqUfg/5PSUUQeBiNJd7aHIUfe/uXm+h+JV/wx+7pKV4VfLsog3Vc5NKwnt1 +5v2HUkrT4IfcU7bBKKBYENc8R+HqqcLDUtmW+XntuwJmLr/HX1kAT1XuaGorzTkf +SMVYlHlA7QagB8/jpxZATbmcHNPK4dUnlY+W70jO12hKtDYaIviHpCtIMNHLXso6 +xZS1tDr9a8DK2rFJ3OnPnoqPyhNkrUKt2tUC5aej2hZlewdZbKHax0xk+q4wTxT1 +qNQ9YiysHdnUdgzqXUJBIoqg/WKMxT2lUdF18nl5/DRQfJ2Ci49/T0AMnzt4PvJN +bxDf2uViMjAhAgMBAAGgQjBABgkqhkiG9w0BCQ4xMzAxMC8GA1UdEQQoMCaCD2Ny +eXB0b2dyYXBoeS5pb4ITc3ViLmNyeXB0b2dyYXBoeS5pbzANBgkqhkiG9w0BAQUF +AAOCAQEAavgmRwSFd8ASj5mQl03WdI+j+U2HIUhqiNU7taqM00FPcGdGs2nLApu3 +jH1MzZJ47pZD+Aqcb/8HD6MRYBgK8tH2pPdn7Z6cQZ1+cBBvOvXn771RPk+bQufs +J3lYe2eK6NZKY7a3nqCNCDK6p4sOnIF49GoXLABDO5/2iwCs7Zb1SOxw9YVoUQT8 +qzuO7DWO0ojKB7zUl9GEeKGiLvUZCi9cP7eA0Jf4ojrFeT6cwUr9g61h+bLLAOX0 +knAQVheFwSx2jeQk+J12ga8HCscst9Mx7IeZ+blADEXFALDXoVk8M+ZftvbaXABw +VUrJdCoVGtWDIk58Pvw71M+HqbQ3dg== +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/two_basic_constraints.pem b/Tests/X509Tests/CSR Vectors/cryptography/two_basic_constraints.pem new file mode 100644 index 0000000..fdf3d3a --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/two_basic_constraints.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICyTCCAbECAQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYD +VQQHDAZBdXN0aW4xDTALBgNVBAoMBFB5Q0ExGDAWBgNVBAMMD2NyeXB0b2dyYXBo +eS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMxyVC2DvnP1mmA/ +uL14ffQ9bjE4qSZyhhkUhw30aJcZL9d8gEWtOCdZ21d2pfOxXjRfQ2PlJAoPxqs5 +adEah2iMmAI6CBwl12Uww7ap+t/KnUtMswCn+urerZnSZ1/EFQ2zcE2yCqfdNWc1 +uU+osvamIia2rujtLeeCfqXyLAXVA1ouHtBieQRVS7OZlIufal7ubrPU8NSags7j +9IFcstskhbjkHG+oPU6RJ2r+SCnyCUCeoeI0QRgpzvUkEdkiL2+UzyJOuvI4kABw +1YbUbcLObDJ0dd/xH8mgvkMrhDTbNC/TFY//hWJAedM8BKK4QzSuwj4drcBLKDTC +bX7in3UCAwEAAaAtMCsGCSqGSIb3DQEJDjEeMBwwDAYDVR0TAQH/BAIwADAMBgNV +HRMBAf8EAjAAMA0GCSqGSIb3DQEBBQUAA4IBAQC4AN48KL9WmqePUKOGowKRi5cc +uHOBwv2F12+6scMYihfZZs25mpwfyAuIM7dOl7JgQ+oTVxMXfCN9Im5lsAq83BLs +s4UvG8nvnBnzFf14iabRLbi/the43LV65ipNLNoBEDGWEhNJCBvZupdU5CG4UJKd +HzDwot6ZjtoOH4TUIir21DtDgSXKKuIX9u8v299n3A8bNqxGtDk71hcaEvtfHSjb +n2Y4ZLdDq4RJETuu8TDPeX6mUv+Ry5xTCUSJg88EezwSe49W50ia5SrzH5PsB18d +8W1Z7V72ar5jYAL0ZTT73Aobs5m1S09mVTXTeYVIfsoOBg+SACeTec73L60r +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension.pem b/Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension.pem new file mode 100644 index 0000000..64c85e1 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICuzCCAaMCAQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYD +VQQHDAZBdXN0aW4xDTALBgNVBAoMBFB5Q0ExGDAWBgNVBAMMD2NyeXB0b2dyYXBo +eS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALZkJb38ur977tqm +JXl1WVnLvNrrImaXk03wZzlFAVxYCheI5AUUyD8zOV+gyvzdKD6x0Q2HwWUiIdNK +XPC2T0mDkLGIR7V/fk80rlGl7vuSaC0Pg4bLjucduvRq8quBqvykBf39B4hZarfH +9d+S5v3s56dvrAKVtz8BOYKOlIQYzwcbJV6UVuwutzdxugnS76NG7Dg0HQ/40R9P +Eb0DnslGZfdtgC0yXkRv4yHswnYyYsKeRwMni7pJASthH217PAURhL2ovUTiMB7C +GfycYHkpuWKSl5TS9zCEtlGv8ZphgC74lCL3czIgebG/6i0gIEhRPfFRA7ECkHRG +zztO+EsCAwEAAaAfMB0GCSqGSIb3DQEJDjEQMA4wDAYDKgMEBAV2YWx1ZTANBgkq +hkiG9w0BAQUFAAOCAQEAFl+GkBP9Y+bJynRotG7mxcNGwSa8ZCv8776r64up3o1O +qPnwPrALjOT4CyhbEwxG+DtVy8zL7WpPFjpL6WUtPBqlH6gHqyLukWDxBnYMbo97 +JTZL1mAEd+Y1EE/r/CrDceXLn5S9bEQIefuyoPXywHmwxCLsgSmzl+UvH0fFGj++ +UMj0KZqUHRmp4tYGygdDbPHkfvu4cAxbQcQQhCk5SRcJ0SGJ18jlbEhmmKyLM6va +H1GpL0w5bUjZezR/tR6euIeLIRNB1FNkwRbgqMFv3L6PZ63mMHmvv37/ZJlQ2ExY +Zpza0VMGLtOC4y2zZXFuamfP4ZZP96wLLm4opN/15g== +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension_critical.pem b/Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension_critical.pem new file mode 100644 index 0000000..4c06b34 --- /dev/null +++ b/Tests/X509Tests/CSR Vectors/cryptography/unsupported_extension_critical.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICvjCCAaYCAQAwVzELMAkGA1UEBhMCVVMxDjAMBgNVBAgMBVRleGFzMQ8wDQYD +VQQHDAZBdXN0aW4xDTALBgNVBAoMBFB5Q0ExGDAWBgNVBAMMD2NyeXB0b2dyYXBo +eS5pbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM7tGCy4Y/ZlUB7s +fnuGViU+PV2GbprRVrB5t4XJFCNN/xDHaPIAtlc5pl0/7VBnzb3a+2ipD3mpDnkj +YtDRJ5by1ja5bU7WTg8yiJsLkJgxAPouyqyC48NgHI7xvg0evLb3p5tgqkuapQS1 +oKgpCyGvLEAmh3WFPAA4TaT5JY7V1xG03TwnEQwcHIZjNWbWR3NsvQADK0rQkNuM +6LSNKv+QjwvIMu2zI3/OAXQm9oTmU1RERehTIFTsAG1gEyu72v4ZgtumbHL7vibS +nQP9f3KUBk4l0xcSxSvWpeEpPHvX2tqJv6kJQatz+42LP4NL8bsrX8apA+bJCvwK +9ILhS5cCAwEAAaAiMCAGCSqGSIb3DQEJDjETMBEwDwYDKgMEAQH/BAV2YWx1ZTAN +BgkqhkiG9w0BAQUFAAOCAQEALHAPptANcCSolK1LHVBGGXzAqPsBhDs7frBva9mG +gaPUA+nXDPb/xkMAiFl7vI9tPUZNoQtAun4TTk8dAjXkWzCgqPxNSaUbERlXJVhX +AwlVVstQlFT5FaPeq5YNuJidD8cW4dYLO3qiUwfSPPeJYmakNDnJAzUrpSdplH1W +3HKMvDozFYb4wxm7wh1RPqkcXIt6YxgbeFf0FL45kDjRto3hRWMe4TJUPlLpXU3V +PGWxIeMAiPQo9zT0rAhUWU17tfSE0GbfmBCjOL0s4vqHfD/INual4bkAfcA6QGmy +3/nAr5/jxkimtmkP4p423ejuAqEQHnjmxsO0EiEtcEzAtA== +-----END CERTIFICATE REQUEST----- diff --git a/Tests/X509Tests/CSRTests.swift b/Tests/X509Tests/CSRTests.swift new file mode 100644 index 0000000..5f31f15 --- /dev/null +++ b/Tests/X509Tests/CSRTests.swift @@ -0,0 +1,499 @@ +//===----------------------------------------------------------------------===// +// +// 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 Foundation +import XCTest +import Crypto +import _CryptoExtras +import SwiftASN1 +@testable import X509 + +final class CSRTests: XCTestCase { + func testSimpleRoundTrip() throws { + let key = P256.Signing.PrivateKey() + let name = try DistinguishedName { + CommonName("Hello") + } + let extensions = try Certificate.Extensions { + SubjectAlternativeNames([.dnsName("example.com")]) + } + let extensionRequest = ExtensionRequest(extensions: extensions) + let attributes = try CertificateSigningRequest.Attributes( + [.init(extensionRequest)] + ) + let csr = try CertificateSigningRequest( + version: .v1, + subject: name, + privateKey: .init(key), + attributes: attributes, + signatureAlgorithm: .ecdsaWithSHA256 + ) + + let bytes = try DER.Serializer.serialized(element: csr) + let parsed = try CertificateSigningRequest(derEncoded: bytes) + + XCTAssertEqual(parsed, csr) + } + + func testRSASHA1CSR() throws { + let url = Bundle.module.url(forResource: "rsa_sha1", withExtension: "der", subdirectory: "CSR Vectors/cryptography")! + let bytes = try Data(contentsOf: url) + let csr = try CertificateSigningRequest(derEncoded: Array(bytes)) + + XCTAssertEqual(csr.signatureAlgorithm, .sha1WithRSAEncryption) + XCTAssertEqual( + csr.subject, + try! DistinguishedName([ + .init(type: .NameAttributes.countryName, printableString: "US"), + .init(type: .NameAttributes.stateOrProvinceName, printableString: "Texas"), + .init(type: .NameAttributes.localityName, printableString: "Austin"), + .init(type: .NameAttributes.organizationName, printableString: "PyCA"), + .init(type: .NameAttributes.commonName, printableString: "cryptography.io") + ]) + ) + XCTAssertNotNil(_RSA.Signing.PublicKey(csr.publicKey)) + XCTAssertNil(csr.attributes[oid: .CSRAttributes.extensionRequest]) + + XCTAssertTrue(csr.publicKey.isValidSignature(csr.signature, for: csr)) + + var serializer = DER.Serializer() + try serializer.serialize(csr) + XCTAssertEqual(Array(bytes), serializer.serializedBytes) + } + + func testRSASHA1CSRPEM() throws { + let url = Bundle.module.url(forResource: "rsa_sha1", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let pemDocument = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: pemDocument) + + XCTAssertEqual(csr.signatureAlgorithm, .sha1WithRSAEncryption) + XCTAssertEqual( + csr.subject, + try! DistinguishedName([ + .init(type: .NameAttributes.countryName, printableString: "US"), + .init(type: .NameAttributes.stateOrProvinceName, printableString: "Texas"), + .init(type: .NameAttributes.localityName, printableString: "Austin"), + .init(type: .NameAttributes.organizationName, printableString: "PyCA"), + .init(type: .NameAttributes.commonName, printableString: "cryptography.io") + ]) + ) + XCTAssertNotNil(_RSA.Signing.PublicKey(csr.publicKey)) + XCTAssertNil(csr.attributes[oid: .CSRAttributes.extensionRequest]) + + XCTAssertTrue(csr.publicKey.isValidSignature(csr.signature, for: csr)) + + let reEncoded = try csr.serializeAsPEM() + XCTAssertEqual( + pemDocument.trimmingCharacters(in: .whitespacesAndNewlines), + reEncoded.pemString.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } + + func testUnsupportedSignatureAlgorithmDER() throws { + let url = Bundle.module.url(forResource: "rsa_md4", withExtension: "der", subdirectory: "CSR Vectors/cryptography")! + let bytes = try Data(contentsOf: url) + XCTAssertThrowsError(try CertificateSigningRequest(derEncoded: Array(bytes))) + } + + func testUnsupportedSignatureAlgorithmPEM() throws { + let url = Bundle.module.url(forResource: "rsa_md4", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + XCTAssertThrowsError(try CertificateSigningRequest(pemEncoded: bytes)) + } + + func testBadVersion() throws { + let url = Bundle.module.url(forResource: "bad-version", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + XCTAssertEqual(csr.version, .init(rawValue: 1)) + } + + func testDuplicateExtension() throws { + let url = Bundle.module.url(forResource: "two_basic_constraints", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + #if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + XCTExpectFailure("Currently don't police extension uniqueness") + XCTAssertThrowsError(try CertificateSigningRequest(pemEncoded: bytes)) + #else + // This is temporary: when we fix this, we'll want to invert the conditional! + // Sadly, XCTExpectFailure is not available on Linux. + XCTAssertNoThrow(try CertificateSigningRequest(pemEncoded: bytes)) + #endif + } + + func testUnknownCriticalExtension() throws { + let url = Bundle.module.url(forResource: "unsupported_extension_critical", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + guard let extensionRequest = try csr.attributes.extensionRequest else { + XCTFail("No extension request") + return + } + + XCTAssertEqual( + extensionRequest.extensions, + try! Certificate.Extensions { + Certificate.Extension(oid: [1, 2, 3, 4], critical: true, value: ArraySlice("value".utf8)) + } + ) + } + + func testUnknownExtension() throws { + let url = Bundle.module.url(forResource: "unsupported_extension", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + guard let extensionRequest = try csr.attributes.extensionRequest else { + XCTFail("No extension request") + return + } + + XCTAssertEqual( + extensionRequest.extensions, + try! Certificate.Extensions { + Certificate.Extension(oid: [1, 2, 3, 4], critical: false, value: ArraySlice("value".utf8)) + } + ) + } + + func testNoExtensions() throws { + let url = Bundle.module.url(forResource: "challenge-unstructured", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + XCTAssertNil(try csr.attributes.extensionRequest) + } + + func testBasicConstraints() throws { + let url = Bundle.module.url(forResource: "basic_constraints", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + guard let extensionRequest = try csr.attributes.extensionRequest else { + XCTFail("No extension request") + return + } + + XCTAssertEqual( + extensionRequest.extensions, + try! Certificate.Extensions { + Critical( + BasicConstraints.isCertificateAuthority(maxPathLength: 1) + ) + } + ) + } + + func testSubjectAlternativeName() throws { + let url = Bundle.module.url(forResource: "san_rsa_sha1", withExtension: "der", subdirectory: "CSR Vectors/cryptography")! + let bytes = try Data(contentsOf: url) + let csr = try CertificateSigningRequest(derEncoded: Array(bytes)) + + guard let extensionRequest = try csr.attributes.extensionRequest else { + XCTFail("No extension request") + return + } + + XCTAssertEqual( + extensionRequest.extensions, + try! Certificate.Extensions { + SubjectAlternativeNames([ + .dnsName("cryptography.io"), + .dnsName("sub.cryptography.io"), + ]) + } + ) + } + + func testSubjectAlternativeNamePEM() throws { + let url = Bundle.module.url(forResource: "san_rsa_sha1", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + guard let extensionRequest = try csr.attributes.extensionRequest else { + XCTFail("No extension request") + return + } + + XCTAssertEqual( + extensionRequest.extensions, + try! Certificate.Extensions { + SubjectAlternativeNames([ + .dnsName("cryptography.io"), + .dnsName("sub.cryptography.io"), + ]) + } + ) + } + + func testFreeIPABadCritical() throws { + let url = Bundle.module.url(forResource: "freeipa-bad-critical", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + XCTAssertThrowsError(try csr.attributes.extensionRequest) + } + + func testInvalidSignature() throws { + let url = Bundle.module.url(forResource: "invalid_signature", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + XCTAssertFalse(csr.publicKey.isValidSignature(csr.signature, for: csr)) + } + + func testRSASHA256Signature() throws { + let url = Bundle.module.url(forResource: "rsa_sha256", withExtension: "der", subdirectory: "CSR Vectors/cryptography")! + let bytes = try Data(contentsOf: url) + let csr = try CertificateSigningRequest(derEncoded: Array(bytes)) + + XCTAssertTrue(csr.publicKey.isValidSignature(csr.signature, for: csr)) + } + + func testRSASHA256SignaturePEM() throws { + let url = Bundle.module.url(forResource: "rsa_sha256", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: bytes) + + XCTAssertTrue(csr.publicKey.isValidSignature(csr.signature, for: csr)) + } + + func testECDSACSR() throws { + let url = Bundle.module.url(forResource: "ec_sha256", withExtension: "der", subdirectory: "CSR Vectors/cryptography")! + let bytes = try Data(contentsOf: url) + let csr = try CertificateSigningRequest(derEncoded: Array(bytes)) + + XCTAssertEqual(csr.signatureAlgorithm, .ecdsaWithSHA256) + XCTAssertEqual( + csr.subject, + try! DistinguishedName([ + .init(type: .NameAttributes.commonName, utf8String: "cryptography.io"), + .init(type: .NameAttributes.organizationName, utf8String: "PyCA"), + .init(type: .NameAttributes.countryName, printableString: "US"), + .init(type: .NameAttributes.stateOrProvinceName, utf8String: "Texas"), + .init(type: .NameAttributes.localityName, utf8String: "Austin"), + ]) + ) + XCTAssertNotNil(P384.Signing.PublicKey(csr.publicKey)) + XCTAssertNil(csr.attributes[oid: .CSRAttributes.extensionRequest]) + + XCTAssertTrue(csr.publicKey.isValidSignature(csr.signature, for: csr)) + + var serializer = DER.Serializer() + try serializer.serialize(csr) + XCTAssertEqual(Array(bytes), serializer.serializedBytes) + } + + func testECDSACSRPEM() throws { + let url = Bundle.module.url(forResource: "ec_sha256", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")! + let pemDocument = try String(decoding: Data(contentsOf: url), as: UTF8.self) + let csr = try CertificateSigningRequest(pemEncoded: pemDocument) + + XCTAssertEqual(csr.signatureAlgorithm, .ecdsaWithSHA256) + XCTAssertEqual( + csr.subject, + try! DistinguishedName([ + .init(type: .NameAttributes.commonName, utf8String: "cryptography.io"), + .init(type: .NameAttributes.organizationName, utf8String: "PyCA"), + .init(type: .NameAttributes.countryName, printableString: "US"), + .init(type: .NameAttributes.stateOrProvinceName, utf8String: "Texas"), + .init(type: .NameAttributes.localityName, utf8String: "Austin"), + ]) + ) + XCTAssertNotNil(P384.Signing.PublicKey(csr.publicKey)) + XCTAssertNil(csr.attributes[oid: .CSRAttributes.extensionRequest]) + + XCTAssertTrue(csr.publicKey.isValidSignature(csr.signature, for: csr)) + + let reEncoded = try csr.serializeAsPEM() + XCTAssertEqual( + pemDocument.trimmingCharacters(in: .whitespacesAndNewlines), + reEncoded.pemString.trimmingCharacters(in: .whitespacesAndNewlines) + ) + } + + func testDuplicateAttributesAreRemovedOnInsertion() throws { + var elements = Array(repeating: CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: []), count: 5) + elements.append(CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 5)])) + elements.append(CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 6)])) + elements.append(CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 7)])) + + let attributes = CertificateSigningRequest.Attributes(elements) + XCTAssertEqual(attributes.count, 2) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 7)]) + ) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4, 5]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 5)]) + ) + } + + func testCanReplaceElementInAttributes() throws { + var attributes = CertificateSigningRequest.Attributes([ + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 1)]), + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 2)]) + ]) + + attributes[oid: [1, 2, 3, 4]] = CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 3)]) + attributes[oid: [1, 2, 3, 4, 5]] = nil + attributes[oid: [4, 3, 2, 1]] = CertificateSigningRequest.Attribute(oid: [4, 3, 2, 1], values: [try ASN1Any(erasing: 4)]) + + XCTAssertEqual(attributes.count, 2) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 3)]) + ) + XCTAssertEqual( + attributes[oid: [4, 3, 2, 1]], + CertificateSigningRequest.Attribute(oid: [4, 3, 2, 1], values: [try ASN1Any(erasing: 4)]) + ) + } + + func testInsertHasTheEffectOfTheSubscript() throws { + var attributes = CertificateSigningRequest.Attributes() + + attributes.insert(contentsOf: [ + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 1)]), + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 2)]), + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 3)]), + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 4)]), + ]) + + XCTAssertEqual(attributes.count, 2) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 3)]) + ) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4, 5]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 4)]) + ) + + attributes.insert(CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5)])) + XCTAssertEqual(attributes.count, 2) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5)]) + ) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4, 5]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 4)]) + ) + + attributes.insert(CertificateSigningRequest.Attribute(oid: [4, 3, 2, 1], values: [try ASN1Any(erasing: 6)])) + XCTAssertEqual(attributes.count, 3) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5)]) + ) + XCTAssertEqual( + attributes[oid: [1, 2, 3, 4, 5]], + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 4)]) + ) + XCTAssertEqual( + attributes[oid: [4, 3, 2, 1]], + CertificateSigningRequest.Attribute(oid: [4, 3, 2, 1], values: [try ASN1Any(erasing: 6)]) + ) + } + + func testCSRAttributeValuesAreOrderIndependentForEqualityAndHashing() throws { + let values: [ASN1Any] = [ + try ASN1Any(erasing: 5), + try ASN1Any(erasing: 10), + try ASN1Any(erasing: 15), + ] + + let options = values.permutations.map { CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: $0) } + + for option in options { + // Everything is equal. + XCTAssertTrue(options.allSatisfy({ $0 == option })) + } + + let setified = Set(options) + XCTAssertEqual(setified.count, 1) + + XCTAssertNotEqual( + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5)]), + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5), try ASN1Any(erasing: 10)]) + ) + } + + func testCSRAttributesAreOrderIndependentForEqualityAndHashing() throws { + let attributes: [CertificateSigningRequest.Attribute] = [ + CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5)]), + CertificateSigningRequest.Attribute(oid: [4, 3, 2, 1], values: [try ASN1Any(erasing: 10)]), + CertificateSigningRequest.Attribute(oid: [1, 1, 1, 1], values: [try ASN1Any(erasing: 5)]), + ] + + let options = attributes.permutations.map { CertificateSigningRequest.Attributes($0) } + + for option in options { + // Everything is equal. + XCTAssertTrue(options.allSatisfy({ $0 == option })) + } + + let setified = Set(options) + XCTAssertEqual(setified.count, 1) + + XCTAssertNotEqual( + CertificateSigningRequest.Attributes(attributes.prefix(1)), + CertificateSigningRequest.Attributes(attributes.prefix(2)) + ) + } +} + +extension RandomAccessCollection { + var permutations: [[Element]] { + // A more efficient implementation would be implemented as a Sequence, but for tests this isn't important + // enough. + // + // For the curious, this is an implementation of QuickPerm in Swift. + var permutations: [[Element]] = [] + var working = Array(self) + + // Trivial first permutation is the current one. + permutations.append(working) + + let n = working.count + var p = Array(0...n) + var i = 1 + + while i < n { + p[i] -= 1 + + let j: Int + if i % 2 == 1 { + j = p[i] + } else { + j = 0 + } + + working.swapAt(i, j) + permutations.append(working) + + i = 1 + + while p[i] == 0 { + p[i] = i + i += 1 + } + } + + return permutations + } +}