diff --git a/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift b/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift index f2107e6..e73380e 100644 --- a/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift +++ b/Sources/X509/CryptographicMessageSyntax/CMSSignerIdentifier.swift @@ -25,7 +25,7 @@ enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable { private static let skiIdentifier = ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific) case issuerAndSerialNumber(CMSIssuerAndSerialNumber) - case subjectKeyIdentifier(Certificate.Extensions.SubjectKeyIdentifier) + case subjectKeyIdentifier(SubjectKeyIdentifier) init(derEncoded node: ASN1Node) throws { switch node.identifier { diff --git a/Sources/X509/Docs.docc/Creating Certificates.md b/Sources/X509/Docs.docc/Creating Certificates.md index a109e39..4e15f8a 100644 --- a/Sources/X509/Docs.docc/Creating Certificates.md +++ b/Sources/X509/Docs.docc/Creating Certificates.md @@ -84,9 +84,9 @@ certificate. For self-signed certificates, the issuer and the subject are identi The bulk of the semantic information in a certificate is contained in its extensions. For our case, we care about only a small few. -We need ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` to be present, and set to -`isCertificateAuthority`. We also need ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` with the appropriate bits -set. Finally, we want to set ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` to include the domain +We need ``BasicConstraints`` to be present, and set to +`isCertificateAuthority`. We also need ``KeyUsage`` with the appropriate bits +set. Finally, we want to set ``SubjectAlternativeNames`` to include the domain name we're going to be self-signing for, which in this case we'll set to `localhost`. We can use the helpful builder syntax for this: @@ -94,12 +94,12 @@ We can use the helpful builder syntax for this: ```swift let extensions = try Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) Critical( - Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true) + KeyUsage(digitalSignature: true, keyCertSign: true) ) - Certificate.Extensions.SubjectAlternativeNames([.dNSName("localhost")]) + SubjectAlternativeNames([.dNSName("localhost")]) } ``` @@ -152,12 +152,12 @@ let now = Date() let extensions = try Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) Critical( - Certificate.Extensions.KeyUsage(keyCertSign: true) + KeyUsage(keyCertSign: true) ) - Certificate.Extensions.SubjectAlternativeNames([.dNSName("localhost")]) + SubjectAlternativeNames([.dNSName("localhost")]) } let certificate = try Certificate( diff --git a/Sources/X509/Docs.docc/Examining Certificates.md b/Sources/X509/Docs.docc/Examining Certificates.md index 44b4091..b00f108 100644 --- a/Sources/X509/Docs.docc/Examining Certificates.md +++ b/Sources/X509/Docs.docc/Examining Certificates.md @@ -99,22 +99,22 @@ bytes in an extension, as well as wrap themselves back into the opaque ``Certifi Out of the box, ``X509`` ships support for the following extension types: -- ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct`` -- ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` -- ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` -- ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` -- ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` -- ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct`` -- ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` -- ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct`` +- ``AuthorityInformationAccess`` +- ``AuthorityKeyIdentifier`` +- ``BasicConstraints`` +- ``ExtendedKeyUsage`` +- ``KeyUsage`` +- ``NameConstraints`` +- ``SubjectAlternativeNames`` +- ``SubjectKeyIdentifier`` To decode an extension usually requires examining its ``Certificate/Extension/oid`` field. For example, to search -for the ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``, the typical code would be: +for the ``SubjectAlternativeNames``, the typical code would be: ```swift let opaqueSANExtension = certificate.extensions.first(where: { $0.oid == .X509ExtensionID.subjectAlternativeName }) if let opaqueSanExtension { - let unwrappedSanExtension = try Certificate.Extensions.SubjectAlternativeName(opaqueSanExtension) + let unwrappedSanExtension = try SubjectAlternativeName(opaqueSanExtension) } ``` @@ -123,21 +123,21 @@ to search for a specific extension. The above code could be replaced by: ```swift if let opaqueSanExtension = certificate.extensions[oid: .X509ExtensionID.subjectAlternativeName] { - let unwrappedSanExtension = try Certificate.Extensions.SubjectAlternativeName(opaqueSanExtension) + let unwrappedSanExtension = try SubjectAlternativeName(opaqueSanExtension) } ``` This pattern is itself still somewhat repetitive, so ``Certificate/Extensions-swift.struct`` offers a number of helper properties that can be used to get a specific typed extension: -- ``Certificate/Extensions-swift.struct/authorityInformationAccess-swift.property`` -- ``Certificate/Extensions-swift.struct/authorityKeyIdentifier-swift.property`` -- ``Certificate/Extensions-swift.struct/basicConstraints-swift.property`` -- ``Certificate/Extensions-swift.struct/extendedKeyUsage-swift.property`` -- ``Certificate/Extensions-swift.struct/keyUsage-swift.property`` -- ``Certificate/Extensions-swift.struct/nameConstraints-swift.property`` -- ``Certificate/Extensions-swift.struct/subjectAlternativeNames-swift.property`` -- ``Certificate/Extensions-swift.struct/subjectKeyIdentifier-swift.property`` +- ``Certificate/Extensions-swift.struct/authorityInformationAccess`` +- ``Certificate/Extensions-swift.struct/authorityKeyIdentifier`` +- ``Certificate/Extensions-swift.struct/basicConstraints`` +- ``Certificate/Extensions-swift.struct/extendedKeyUsage`` +- ``Certificate/Extensions-swift.struct/keyUsage`` +- ``Certificate/Extensions-swift.struct/nameConstraints`` +- ``Certificate/Extensions-swift.struct/subjectAlternativeNames`` +- ``Certificate/Extensions-swift.struct/subjectKeyIdentifier`` This lets us reduce the above code to a single line: diff --git a/Sources/X509/Docs.docc/index.md b/Sources/X509/Docs.docc/index.md index ae0a699..c8979cc 100644 --- a/Sources/X509/Docs.docc/index.md +++ b/Sources/X509/Docs.docc/index.md @@ -47,14 +47,14 @@ certificate authorities, authenticating peers, and more. ### Supported Extension Types -- ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct`` -- ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` -- ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` -- ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` -- ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` -- ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct`` -- ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` -- ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct`` +- ``AuthorityInformationAccess`` +- ``AuthorityKeyIdentifier`` +- ``BasicConstraints`` +- ``ExtendedKeyUsage`` +- ``KeyUsage`` +- ``NameConstraints`` +- ``SubjectAlternativeNames`` +- ``SubjectKeyIdentifier`` - ``Critical`` ### Names diff --git a/Sources/X509/Extension Types/AuthorityInformationAccess.swift b/Sources/X509/Extension Types/AuthorityInformationAccess.swift index ecb83b0..944e398 100644 --- a/Sources/X509/Extension Types/AuthorityInformationAccess.swift +++ b/Sources/X509/Extension Types/AuthorityInformationAccess.swift @@ -14,55 +14,53 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Provides details on how to access information about the certificate issuer. - /// - /// This extension behaves as a collection of ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/AccessDescription`` objects. - /// - /// In practice this most commonly contains OCSP servers and links to the issuing CA certificate. - public struct AuthorityInformationAccess { - @usableFromInline - var descriptions: [AccessDescription] +/// Provides details on how to access information about the certificate issuer. +/// +/// This extension behaves as a collection of ``AuthorityInformationAccess/AccessDescription`` objects. +/// +/// In practice this most commonly contains OCSP servers and links to the issuing CA certificate. +public struct AuthorityInformationAccess { + @usableFromInline + var descriptions: [AccessDescription] - /// Create a new ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/`` object - /// containing specific access descriptions. - /// - /// - Parameter descriptions: The descriptions to include in the AIA extension. - @inlinable - public init(_ descriptions: Descriptions) where Descriptions.Element == AccessDescription { - self.descriptions = Array(descriptions) + /// Create a new ``AuthorityInformationAccess/`` object + /// containing specific access descriptions. + /// + /// - Parameter descriptions: The descriptions to include in the AIA extension. + @inlinable + public init(_ descriptions: Descriptions) where Descriptions.Element == AccessDescription { + self.descriptions = Array(descriptions) + } + + /// Create a new ``AuthorityInformationAccess`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.authorityInformationAccess else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess), got \(ext.oid)") } - /// Create a new ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.authorityInformationAccess else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess), got \(ext.oid)") - } - - let aiaSyntax = try AuthorityInfoAccessSyntax(derEncoded: ext.value) - self.descriptions = aiaSyntax.descriptions.map { AccessDescription($0) } - } + let aiaSyntax = try AuthorityInfoAccessSyntax(derEncoded: ext.value) + self.descriptions = aiaSyntax.descriptions.map { AccessDescription($0) } } } -extension Certificate.Extensions.AuthorityInformationAccess: Hashable { } +extension AuthorityInformationAccess: Hashable { } -extension Certificate.Extensions.AuthorityInformationAccess: Sendable { } +extension AuthorityInformationAccess: Sendable { } -extension Certificate.Extensions.AuthorityInformationAccess: CustomStringConvertible { +extension AuthorityInformationAccess: CustomStringConvertible { public var description: String { return self.map { String(describing: $0) }.joined(separator: ", ") } } // TODO(cory): Probably also RangeReplaceableCollection, even though it's kinda crap. -extension Certificate.Extensions.AuthorityInformationAccess: RandomAccessCollection { +extension AuthorityInformationAccess: RandomAccessCollection { @inlinable public var startIndex: Int { self.descriptions.startIndex @@ -85,7 +83,7 @@ extension Certificate.Extensions.AuthorityInformationAccess: RandomAccessCollect } } -extension Certificate.Extensions.AuthorityInformationAccess { +extension AuthorityInformationAccess { /// Describes the location and format of additional information provided /// by the issuer of a given certificate. public struct AccessDescription { @@ -95,7 +93,7 @@ extension Certificate.Extensions.AuthorityInformationAccess { /// The location where the information may be found. public var location: GeneralName - /// Construct a new ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/AccessDescription`` from constituent parts. + /// Construct a new ``AuthorityInformationAccess/AccessDescription`` from constituent parts. @inlinable public init(method: AccessMethod, location: GeneralName) { self.method = method @@ -110,19 +108,19 @@ extension Certificate.Extensions.AuthorityInformationAccess { } } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription: Hashable { } +extension AuthorityInformationAccess.AccessDescription: Hashable { } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription: Sendable { } +extension AuthorityInformationAccess.AccessDescription: Sendable { } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription: CustomStringConvertible { +extension AuthorityInformationAccess.AccessDescription: CustomStringConvertible { public var description: String { return "\(self.method): \(self.location)" } } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription { +extension AuthorityInformationAccess.AccessDescription { /// The format and meaning of the information included in a single - /// ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct/AccessDescription`` + /// ``AuthorityInformationAccess/AccessDescription`` /// object. public struct AccessMethod { @usableFromInline @@ -160,11 +158,11 @@ extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription { } } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod: Hashable { } +extension AuthorityInformationAccess.AccessDescription.AccessMethod: Hashable { } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod: Sendable { } +extension AuthorityInformationAccess.AccessDescription.AccessMethod: Sendable { } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod: CustomStringConvertible { +extension AuthorityInformationAccess.AccessDescription.AccessMethod: CustomStringConvertible { @inlinable public var description: String { switch self.backing { @@ -178,9 +176,9 @@ extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.Ac } } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Hashable { } +extension AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Hashable { } -extension Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Sendable { } +extension AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Sendable { } extension Certificate.Extension { /// Construct an opaque ``Certificate/Extension`` from this AIA extension. @@ -189,7 +187,7 @@ extension Certificate.Extension { /// - aia: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ aia: Certificate.Extensions.AuthorityInformationAccess, critical: Bool) throws { + public init(_ aia: AuthorityInformationAccess, critical: Bool) throws { let asn1Representation = AuthorityInfoAccessSyntax(aia) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -197,7 +195,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.AuthorityInformationAccess: CertificateExtensionConvertible { +extension AuthorityInformationAccess: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } @@ -222,7 +220,7 @@ struct AuthorityInfoAccessSyntax: DERImplicitlyTaggable { var descriptions: [AIAAccessDescription] @inlinable - init(_ aia: Certificate.Extensions.AuthorityInformationAccess) { + init(_ aia: AuthorityInformationAccess) { self.descriptions = aia.descriptions.map { .init($0) } } @@ -261,7 +259,7 @@ struct AIAAccessDescription: DERImplicitlyTaggable { } @inlinable - init(_ description: Certificate.Extensions.AuthorityInformationAccess.AccessDescription) { + init(_ description: AuthorityInformationAccess.AccessDescription) { self.accessMethod = ASN1ObjectIdentifier(accessMethod: description.method) self.accessLocation = description.location } @@ -295,7 +293,7 @@ extension ASN1ObjectIdentifier { } @inlinable - public init(accessMethod: Certificate.Extensions.AuthorityInformationAccess.AccessDescription.AccessMethod) { + public init(accessMethod: AuthorityInformationAccess.AccessDescription.AccessMethod) { switch accessMethod.backing { case .ocspServer: self = .AccessMethodIdentifiers.ocspServer diff --git a/Sources/X509/Extension Types/AuthorityKeyIdentifier.swift b/Sources/X509/Extension Types/AuthorityKeyIdentifier.swift index 73c17d2..c1d26fd 100644 --- a/Sources/X509/Extension Types/AuthorityKeyIdentifier.swift +++ b/Sources/X509/Extension Types/AuthorityKeyIdentifier.swift @@ -14,60 +14,58 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Provides information about the public key corresponding to the private key that was - /// used to sign a specific certificate. - public struct AuthorityKeyIdentifier { - /// An opaque sequence of bytes uniquely derived from the public key of the issuing - /// CA. - /// - /// This is commonly a hash of the subject public key info from the issuing certificate. - public var keyIdentifier: ArraySlice? +/// Provides information about the public key corresponding to the private key that was +/// used to sign a specific certificate. +public struct AuthorityKeyIdentifier { + /// An opaque sequence of bytes uniquely derived from the public key of the issuing + /// CA. + /// + /// This is commonly a hash of the subject public key info from the issuing certificate. + public var keyIdentifier: ArraySlice? - /// The name of the issuer of the issuing cert. - public var authorityCertIssuer: [GeneralName]? + /// The name of the issuer of the issuing cert. + public var authorityCertIssuer: [GeneralName]? - /// The serial number of the issuing cert. - public var authorityCertSerialNumber: Certificate.SerialNumber? + /// The serial number of the issuing cert. + public var authorityCertSerialNumber: Certificate.SerialNumber? - /// Create a new ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` extension value. - /// - /// - Parameters: - /// - keyIdentifier: An opaque sequence of bytes uniquely derived from the public key of the issuing CA. - /// - authorityCertIssuer: The name of the issuer of the issuing cert. - /// - authorityCertSerialNumber: The serial number of the issuing cert. - @inlinable - public init(keyIdentifier: ArraySlice? = nil, authorityCertIssuer: [GeneralName]? = nil, authorityCertSerialNumber: Certificate.SerialNumber? = nil) { - self.keyIdentifier = keyIdentifier - self.authorityCertIssuer = authorityCertIssuer - self.authorityCertSerialNumber = authorityCertSerialNumber + /// Create a new ``AuthorityKeyIdentifier`` extension value. + /// + /// - Parameters: + /// - keyIdentifier: An opaque sequence of bytes uniquely derived from the public key of the issuing CA. + /// - authorityCertIssuer: The name of the issuer of the issuing cert. + /// - authorityCertSerialNumber: The serial number of the issuing cert. + @inlinable + public init(keyIdentifier: ArraySlice? = nil, authorityCertIssuer: [GeneralName]? = nil, authorityCertSerialNumber: Certificate.SerialNumber? = nil) { + self.keyIdentifier = keyIdentifier + self.authorityCertIssuer = authorityCertIssuer + self.authorityCertSerialNumber = authorityCertSerialNumber + } + + /// Create a new ``AuthorityKeyIdentifier`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.authorityKeyIdentifier else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier), got \(ext.oid)") } - /// Create a new ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.authorityKeyIdentifier else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier), got \(ext.oid)") - } - - let asn1KeyIdentifier = try AuthorityKeyIdentifierValue(derEncoded: ext.value) - self.keyIdentifier = asn1KeyIdentifier.keyIdentifier.map { $0.bytes } - self.authorityCertIssuer = asn1KeyIdentifier.authorityCertIssuer - self.authorityCertSerialNumber = asn1KeyIdentifier.authorityCertSerialNumber.map { Certificate.SerialNumber(bytes: $0) } - } + let asn1KeyIdentifier = try AuthorityKeyIdentifierValue(derEncoded: ext.value) + self.keyIdentifier = asn1KeyIdentifier.keyIdentifier.map { $0.bytes } + self.authorityCertIssuer = asn1KeyIdentifier.authorityCertIssuer + self.authorityCertSerialNumber = asn1KeyIdentifier.authorityCertSerialNumber.map { Certificate.SerialNumber(bytes: $0) } } } -extension Certificate.Extensions.AuthorityKeyIdentifier: Hashable { } +extension AuthorityKeyIdentifier: Hashable { } -extension Certificate.Extensions.AuthorityKeyIdentifier: Sendable { } +extension AuthorityKeyIdentifier: Sendable { } -extension Certificate.Extensions.AuthorityKeyIdentifier: CustomStringConvertible { +extension AuthorityKeyIdentifier: CustomStringConvertible { public var description: String { var elements: [String] = [] @@ -94,7 +92,7 @@ extension Certificate.Extension { /// - aki: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ aki: Certificate.Extensions.AuthorityKeyIdentifier, critical: Bool) throws { + public init(_ aki: AuthorityKeyIdentifier, critical: Bool) throws { let asn1Representation = AuthorityKeyIdentifierValue(aki) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -102,7 +100,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.AuthorityKeyIdentifier: CertificateExtensionConvertible { +extension AuthorityKeyIdentifier: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } @@ -133,7 +131,7 @@ struct AuthorityKeyIdentifierValue: DERImplicitlyTaggable { } @inlinable - init(_ aki: Certificate.Extensions.AuthorityKeyIdentifier) { + init(_ aki: AuthorityKeyIdentifier) { self.keyIdentifier = aki.keyIdentifier.map { ASN1OctetString(contentBytes: $0) } self.authorityCertIssuer = aki.authorityCertIssuer self.authorityCertSerialNumber = aki.authorityCertSerialNumber.map { $0.bytes } diff --git a/Sources/X509/Extension Types/BasicConstraints.swift b/Sources/X509/Extension Types/BasicConstraints.swift index 2029571..299c93f 100644 --- a/Sources/X509/Extension Types/BasicConstraints.swift +++ b/Sources/X509/Extension Types/BasicConstraints.swift @@ -14,49 +14,47 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Identifies whether the subject of the certificate is a CA and the - /// maximum verification depth of valid certificate paths that include this +/// Identifies whether the subject of the certificate is a CA and the +/// maximum verification depth of valid certificate paths that include this +/// certificate. +public enum BasicConstraints { + /// This entity is a certificate authority. + /// + /// If `maxPathLength` is non-nil, this length is the maximum number of intermediate + /// certificates that may follow this one in a valid certification path. Note that this + /// excludes the leaf, so a valid (and common) `maxPathLength` is `0`. + case isCertificateAuthority(maxPathLength: Int?) + + /// This entity is not a certificate authority, and may not be a valid issuer of any /// certificate. - public enum BasicConstraints { - /// This entity is a certificate authority. - /// - /// If `maxPathLength` is non-nil, this length is the maximum number of intermediate - /// certificates that may follow this one in a valid certification path. Note that this - /// excludes the leaf, so a valid (and common) `maxPathLength` is `0`. - case isCertificateAuthority(maxPathLength: Int?) + case notCertificateAuthority - /// This entity is not a certificate authority, and may not be a valid issuer of any - /// certificate. - case notCertificateAuthority + /// Create a new ``BasicConstraints`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.basicConstraints`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.basicConstraints else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.basicConstraints), got \(ext.oid)") + } - /// Create a new ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.basicConstraints`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.basicConstraints else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.basicConstraints), got \(ext.oid)") - } - - let basicConstraintsValue = try BasicConstraintsValue(derEncoded: ext.value) - if basicConstraintsValue.isCA { - self = .isCertificateAuthority(maxPathLength: basicConstraintsValue.pathLenConstraint) - } else { - self = .notCertificateAuthority - } + let basicConstraintsValue = try BasicConstraintsValue(derEncoded: ext.value) + if basicConstraintsValue.isCA { + self = .isCertificateAuthority(maxPathLength: basicConstraintsValue.pathLenConstraint) + } else { + self = .notCertificateAuthority } } } -extension Certificate.Extensions.BasicConstraints: Hashable { } +extension BasicConstraints: Hashable { } -extension Certificate.Extensions.BasicConstraints: Sendable { } +extension BasicConstraints: Sendable { } -extension Certificate.Extensions.BasicConstraints: CustomStringConvertible { +extension BasicConstraints: CustomStringConvertible { public var description: String { switch self { case .isCertificateAuthority(maxPathLength: nil): @@ -76,7 +74,7 @@ extension Certificate.Extension { /// - basicConstraints: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ basicConstraints: Certificate.Extensions.BasicConstraints, critical: Bool) throws { + public init(_ basicConstraints: BasicConstraints, critical: Bool) throws { let asn1Representation = BasicConstraintsValue(basicConstraints) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -84,7 +82,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.BasicConstraints: CertificateExtensionConvertible { +extension BasicConstraints: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } @@ -116,7 +114,7 @@ struct BasicConstraintsValue: DERImplicitlyTaggable { } @inlinable - init(_ ext: Certificate.Extensions.BasicConstraints) { + init(_ ext: BasicConstraints) { switch ext { case .isCertificateAuthority(maxPathLength: let maxPathLen): self.isCA = true diff --git a/Sources/X509/Extension Types/ExtendedKeyUsage.swift b/Sources/X509/Extension Types/ExtendedKeyUsage.swift index a0c8284..e60a2dd 100644 --- a/Sources/X509/Extension Types/ExtendedKeyUsage.swift +++ b/Sources/X509/Extension Types/ExtendedKeyUsage.swift @@ -14,46 +14,44 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Indicates one or more purposes for which the certified public key - /// may be used, in addition to or instead of the the purposes indicated - /// in the ``KeyUsage-swift.struct`` extension. - public struct ExtendedKeyUsage { - @usableFromInline - var usages: [Usage] +/// Indicates one or more purposes for which the certified public key +/// may be used, in addition to or instead of the the purposes indicated +/// in the ``KeyUsage`` extension. +public struct ExtendedKeyUsage { + @usableFromInline + var usages: [Usage] - /// Construct an ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` extension containing the - /// given usages. - /// - /// - Parameter usages: The purposes for which the certificate may be used. - @inlinable - public init(_ usages: Usages) where Usages.Element == Usage { - self.usages = Array(usages) + /// Construct an ``ExtendedKeyUsage`` extension containing the + /// given usages. + /// + /// - Parameter usages: The purposes for which the certificate may be used. + @inlinable + public init(_ usages: Usages) where Usages.Element == Usage { + self.usages = Array(usages) + } + + /// Create a new ``ExtendedKeyUsage`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.extendedKeyUsage else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage), got \(ext.oid)") } - /// Create a new ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.extendedKeyUsage else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage), got \(ext.oid)") - } - - let asn1EKU = try ASN1ExtendedKeyUsage(derEncoded: ext.value) - self.usages = asn1EKU.usages.map { Usage(oid: $0) } - } + let asn1EKU = try ASN1ExtendedKeyUsage(derEncoded: ext.value) + self.usages = asn1EKU.usages.map { Usage(oid: $0) } } } -extension Certificate.Extensions.ExtendedKeyUsage: Hashable { } +extension ExtendedKeyUsage: Hashable { } -extension Certificate.Extensions.ExtendedKeyUsage: Sendable { } +extension ExtendedKeyUsage: Sendable { } -extension Certificate.Extensions.ExtendedKeyUsage: CustomStringConvertible { +extension ExtendedKeyUsage: CustomStringConvertible { public var description: String { return self.map { String(describing: $0) @@ -62,7 +60,7 @@ extension Certificate.Extensions.ExtendedKeyUsage: CustomStringConvertible { } // TODO(cory): Probably also RangeReplaceableCollection, even though it's kinda crap. -extension Certificate.Extensions.ExtendedKeyUsage: RandomAccessCollection { +extension ExtendedKeyUsage: RandomAccessCollection { public var startIndex: Int { self.usages.startIndex } @@ -82,9 +80,9 @@ extension Certificate.Extensions.ExtendedKeyUsage: RandomAccessCollection { } } -extension Certificate.Extensions.ExtendedKeyUsage { +extension ExtendedKeyUsage { /// An acceptable usage for a certificate as attested in an - /// ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` + /// ``ExtendedKeyUsage`` /// extension. public struct Usage { @usableFromInline @@ -108,7 +106,7 @@ extension Certificate.Extensions.ExtendedKeyUsage { self.backing = backing } - /// Constructs a ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct/Usage`` from an opaque oid. + /// Constructs a ``ExtendedKeyUsage/Usage`` from an opaque oid. /// /// - Parameter oid: The OID of the usage. @inlinable @@ -161,11 +159,11 @@ extension Certificate.Extensions.ExtendedKeyUsage { } } -extension Certificate.Extensions.ExtendedKeyUsage.Usage: Hashable { } +extension ExtendedKeyUsage.Usage: Hashable { } -extension Certificate.Extensions.ExtendedKeyUsage.Usage: Sendable { } +extension ExtendedKeyUsage.Usage: Sendable { } -extension Certificate.Extensions.ExtendedKeyUsage.Usage: CustomStringConvertible { +extension ExtendedKeyUsage.Usage: CustomStringConvertible { public var description: String { switch self.backing { case .any: @@ -190,9 +188,9 @@ extension Certificate.Extensions.ExtendedKeyUsage.Usage: CustomStringConvertible } } -extension Certificate.Extensions.ExtendedKeyUsage.Usage.Backing: Hashable { } +extension ExtendedKeyUsage.Usage.Backing: Hashable { } -extension Certificate.Extensions.ExtendedKeyUsage.Usage.Backing: Sendable { } +extension ExtendedKeyUsage.Usage.Backing: Sendable { } extension Certificate.Extension { /// Construct an opaque ``Certificate/Extension`` from this Extended Key Usage extension. @@ -201,7 +199,7 @@ extension Certificate.Extension { /// - eku: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ eku: Certificate.Extensions.ExtendedKeyUsage, critical: Bool) throws { + public init(_ eku: ExtendedKeyUsage, critical: Bool) throws { let asn1Representation = ASN1ExtendedKeyUsage(eku) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -209,7 +207,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.ExtendedKeyUsage: CertificateExtensionConvertible { +extension ExtendedKeyUsage: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } @@ -220,7 +218,7 @@ extension ASN1ObjectIdentifier { /// /// - Parameter usage: the EKU to use to construct the OID. @inlinable - public init(_ usage: Certificate.Extensions.ExtendedKeyUsage.Usage) { + public init(_ usage: X509.ExtendedKeyUsage.Usage) { switch usage.backing { case .serverAuth: self = .ExtendedKeyUsage.serverAuth @@ -244,7 +242,7 @@ extension ASN1ObjectIdentifier { } /// An acceptable usage for a certificate as attested in an - /// ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` + /// ``ExtendedKeyUsage`` /// extension. public enum ExtendedKeyUsage { /// The public key may be used for any purpose. @@ -289,7 +287,7 @@ struct ASN1ExtendedKeyUsage: DERImplicitlyTaggable { } @inlinable - init(_ eku: Certificate.Extensions.ExtendedKeyUsage) { + init(_ eku: ExtendedKeyUsage) { self.usages = eku.usages.map { ASN1ObjectIdentifier($0) } } diff --git a/Sources/X509/Extension Types/ExtensionIdentifiers.swift b/Sources/X509/Extension Types/ExtensionIdentifiers.swift index f7f22be..475acc4 100644 --- a/Sources/X509/Extension Types/ExtensionIdentifiers.swift +++ b/Sources/X509/Extension Types/ExtensionIdentifiers.swift @@ -18,35 +18,35 @@ extension ASN1ObjectIdentifier { /// OIDs that identify known X509 extensions. public enum X509ExtensionID { /// Identifies the authority key identifier extension, corresponding to - /// ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct``. + /// ``AuthorityKeyIdentifier``. public static let authorityKeyIdentifier: ASN1ObjectIdentifier = [2, 5, 29, 35] /// Identifies the subject key identifier extension, corresponding to - /// ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct``. + /// ``SubjectKeyIdentifier``. public static let subjectKeyIdentifier: ASN1ObjectIdentifier = [2, 5, 29, 14] /// Identifies the key usgae extension, corresponding to - /// ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct``. + /// ``KeyUsage``. public static let keyUsage: ASN1ObjectIdentifier = [2, 5, 29, 15] /// Identifies the subject alternative name extension, corresponding to - /// ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct``. + /// ``SubjectAlternativeNames``. public static let subjectAlternativeName: ASN1ObjectIdentifier = [2, 5, 29, 17] /// Identifies the basic constraints extension, corresponding to - /// ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum``. + /// ``BasicConstraints``. public static let basicConstraints: ASN1ObjectIdentifier = [2, 5, 29, 19] /// Identifies the name constraints extension, corresponding to - /// ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct``. + /// ``NameConstraints``. public static let nameConstraints: ASN1ObjectIdentifier = [2, 5, 29, 30] /// Identifies the extended key usage extension, corresponding to - /// ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct``. + /// ``ExtendedKeyUsage``. public static let extendedKeyUsage: ASN1ObjectIdentifier = [2, 5, 29, 37] /// Identifies the authority information access extension, corresponding to - /// ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct``. + /// ``AuthorityInformationAccess``. public static let authorityInformationAccess: ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 1, 1] } } diff --git a/Sources/X509/Extension Types/KeyUsage.swift b/Sources/X509/Extension Types/KeyUsage.swift index e0298ad..9620672 100644 --- a/Sources/X509/Extension Types/KeyUsage.swift +++ b/Sources/X509/Extension Types/KeyUsage.swift @@ -14,271 +14,269 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Defines the purpose of the key contained in the certificate. +/// Defines the purpose of the key contained in the certificate. +/// +/// This usage restriction may be employed when a key that could conceptually be used +/// for more than one operation (such as an RSA key) is to be restricted. +public struct KeyUsage { + // KeyUsage is only actually 9-bits wide, so we store it in a UInt16 in bits 0 through 8. + // To avoid the need to do bit swaps, we treat this as though the bits were encoded in ASN.1: + // bit zero is the highest bit, bit 16 is the lowest. + @usableFromInline + internal var rawValue: UInt16 + + /// Construct a ``KeyUsage`` extension with no usages set. + @inlinable + public init() { + self.rawValue = 0 + } + + /// Construct a ``KeyUsage`` extension with some usages set. /// - /// This usage restriction may be employed when a key that could conceptually be used - /// for more than one operation (such as an RSA key) is to be restricted. - public struct KeyUsage { - // KeyUsage is only actually 9-bits wide, so we store it in a UInt16 in bits 0 through 8. - // To avoid the need to do bit swaps, we treat this as though the bits were encoded in ASN.1: - // bit zero is the highest bit, bit 16 is the lowest. - @usableFromInline - internal var rawValue: UInt16 + /// - Parameters: + /// - digitalSignature: This is true when the subject public key is used for verifying digital signatures, + /// other than signatures used in certificates (covered by `keyCertSign`) or in + /// CRLs (covered by `cRLSign`). + /// - nonRepudiation: This is true when the subject public key is used to verify digital signatures used + /// to provide a non-repudiation service that protects against the signing entity denying + /// some action. This does not cover signatures used in certificates (covered by `keyCertSign`) + /// or in CRLs (`cRLSign`). + /// - keyEncipherment: This is true when the subject public key is used to encrypt private or secret keys, e.g. + /// for key transport. + /// - dataEncipherment: This is true when the subject public key is used to encrypt raw data directly, without the use + /// of an intervening symmetric cipher. + /// - keyAgreement: This is true when the subject public key is used for key agreement. + /// - keyCertSign: This is true when the subject public key is used for verifying signatures on + /// certificates. + /// - cRLSign: This is true when the subject public key is used for verifying signatures on + /// certificate revocation lists. + /// - encipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that + /// case, the subject public key may only be used for encrypting data while performing key + /// agreement. + /// - decipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that + /// case, the subject public key may only be used for decrypting data while performing key + /// agreement. + @inlinable + public init( + digitalSignature: Bool = false, + nonRepudiation: Bool = false, + keyEncipherment: Bool = false, + dataEncipherment: Bool = false, + keyAgreement: Bool = false, + keyCertSign: Bool = false, + cRLSign: Bool = false, + encipherOnly: Bool = false, + decipherOnly: Bool = false + ) { + self = Self() + self.digitalSignature = digitalSignature + self.nonRepudiation = nonRepudiation + self.keyEncipherment = keyEncipherment + self.dataEncipherment = dataEncipherment + self.keyAgreement = keyAgreement + self.keyCertSign = keyCertSign + self.cRLSign = cRLSign + self.encipherOnly = encipherOnly + self.decipherOnly = decipherOnly + } - /// Construct a ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` extension with no usages set. - @inlinable - public init() { - self.rawValue = 0 + /// Create a new ``KeyUsage`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.keyUsage`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.keyUsage else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.keyUsage), got \(ext.oid)") } - /// Construct a ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` extension with some usages set. - /// - /// - Parameters: - /// - digitalSignature: This is true when the subject public key is used for verifying digital signatures, - /// other than signatures used in certificates (covered by `keyCertSign`) or in - /// CRLs (covered by `cRLSign`). - /// - nonRepudiation: This is true when the subject public key is used to verify digital signatures used - /// to provide a non-repudiation service that protects against the signing entity denying - /// some action. This does not cover signatures used in certificates (covered by `keyCertSign`) - /// or in CRLs (`cRLSign`). - /// - keyEncipherment: This is true when the subject public key is used to encrypt private or secret keys, e.g. - /// for key transport. - /// - dataEncipherment: This is true when the subject public key is used to encrypt raw data directly, without the use - /// of an intervening symmetric cipher. - /// - keyAgreement: This is true when the subject public key is used for key agreement. - /// - keyCertSign: This is true when the subject public key is used for verifying signatures on - /// certificates. - /// - cRLSign: This is true when the subject public key is used for verifying signatures on - /// certificate revocation lists. - /// - encipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that - /// case, the subject public key may only be used for encrypting data while performing key - /// agreement. - /// - decipherOnly: This only has meaning when the `keyAgreement` field is also `true`. When `true` in that - /// case, the subject public key may only be used for decrypting data while performing key - /// agreement. - @inlinable - public init( - digitalSignature: Bool = false, - nonRepudiation: Bool = false, - keyEncipherment: Bool = false, - dataEncipherment: Bool = false, - keyAgreement: Bool = false, - keyCertSign: Bool = false, - cRLSign: Bool = false, - encipherOnly: Bool = false, - decipherOnly: Bool = false - ) { - self = Self() - self.digitalSignature = digitalSignature - self.nonRepudiation = nonRepudiation - self.keyEncipherment = keyEncipherment - self.dataEncipherment = dataEncipherment - self.keyAgreement = keyAgreement - self.keyCertSign = keyCertSign - self.cRLSign = cRLSign - self.encipherOnly = encipherOnly - self.decipherOnly = decipherOnly + let keyUsageValue = try ASN1BitString(derEncoded: ext.value) + try Self.validateBitString(keyUsageValue) + self.rawValue = UInt16(keyUsageValue) + } + + /// This is true when the subject public key is used for verifying digital signatures, + /// other than signatures used in certificates (covered by ``keyCertSign``) or in + /// CRLs (covered by ``cRLSign``). + @inlinable + public var digitalSignature: Bool { + get { + return (self.rawValue & 0x8000) == 0x8000 } - - /// Create a new ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.keyUsage`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.keyUsage else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.keyUsage), got \(ext.oid)") - } - - let keyUsageValue = try ASN1BitString(derEncoded: ext.value) - try Self.validateBitString(keyUsageValue) - self.rawValue = UInt16(keyUsageValue) - } - - /// This is true when the subject public key is used for verifying digital signatures, - /// other than signatures used in certificates (covered by ``keyCertSign``) or in - /// CRLs (covered by ``cRLSign``). - @inlinable - public var digitalSignature: Bool { - get { - return (self.rawValue & 0x8000) == 0x8000 - } - set { - if newValue { - self.rawValue |= 0x8000 - } else { - self.rawValue &= (~0x8000) - } + set { + if newValue { + self.rawValue |= 0x8000 + } else { + self.rawValue &= (~0x8000) } } + } - /// This is true when the subject public key is used to verify digital signatures used - /// to provide a non-repudiation service that protects against the signing entity denying - /// some action. This does not cover signatures used in certificates (covered by ``keyCertSign``) - /// or in CRLs (``cRLSign``). - @inlinable - public var nonRepudiation: Bool { - get { - return (self.rawValue & 0x4000) == 0x4000 - } - set { - if newValue { - self.rawValue |= 0x4000 - } else { - self.rawValue &= (~0x4000) - } + /// This is true when the subject public key is used to verify digital signatures used + /// to provide a non-repudiation service that protects against the signing entity denying + /// some action. This does not cover signatures used in certificates (covered by ``keyCertSign``) + /// or in CRLs (``cRLSign``). + @inlinable + public var nonRepudiation: Bool { + get { + return (self.rawValue & 0x4000) == 0x4000 + } + set { + if newValue { + self.rawValue |= 0x4000 + } else { + self.rawValue &= (~0x4000) } } + } - /// This is true when the subject public key is used to encrypt private or secret keys, e.g. - /// for key transport. - @inlinable - public var keyEncipherment: Bool { - get { - return (self.rawValue & 0x2000) == 0x2000 - } - set { - if newValue { - self.rawValue |= 0x2000 - } else { - self.rawValue &= (~0x2000) - } + /// This is true when the subject public key is used to encrypt private or secret keys, e.g. + /// for key transport. + @inlinable + public var keyEncipherment: Bool { + get { + return (self.rawValue & 0x2000) == 0x2000 + } + set { + if newValue { + self.rawValue |= 0x2000 + } else { + self.rawValue &= (~0x2000) } } + } - /// This is true when the subject public key is used to encrypt raw data directly, without the use - /// of an intervening symmetric cipher. - @inlinable - public var dataEncipherment: Bool { - get { - return (self.rawValue & 0x1000) == 0x1000 - } - set { - if newValue { - self.rawValue |= 0x1000 - } else { - self.rawValue &= (~0x1000) - } + /// This is true when the subject public key is used to encrypt raw data directly, without the use + /// of an intervening symmetric cipher. + @inlinable + public var dataEncipherment: Bool { + get { + return (self.rawValue & 0x1000) == 0x1000 + } + set { + if newValue { + self.rawValue |= 0x1000 + } else { + self.rawValue &= (~0x1000) } } + } - /// This is true when the subject public key is used for key agreement. - @inlinable - public var keyAgreement: Bool { - get { - return (self.rawValue & 0x0800) == 0x0800 - } - set { - if newValue { - self.rawValue |= 0x0800 - } else { - self.rawValue &= (~0x0800) - } + /// This is true when the subject public key is used for key agreement. + @inlinable + public var keyAgreement: Bool { + get { + return (self.rawValue & 0x0800) == 0x0800 + } + set { + if newValue { + self.rawValue |= 0x0800 + } else { + self.rawValue &= (~0x0800) } } + } - /// This is true when the subject public key is used for verifying signatures on - /// certificates. - @inlinable - public var keyCertSign: Bool { - get { - return (self.rawValue & 0x0400) == 0x0400 - } - set { - if newValue { - self.rawValue |= 0x0400 - } else { - self.rawValue &= (~0x0400) - } + /// This is true when the subject public key is used for verifying signatures on + /// certificates. + @inlinable + public var keyCertSign: Bool { + get { + return (self.rawValue & 0x0400) == 0x0400 + } + set { + if newValue { + self.rawValue |= 0x0400 + } else { + self.rawValue &= (~0x0400) } } + } - /// This is true when the subject public key is used for verifying signatures on - /// certificate revocation lists. - @inlinable - public var cRLSign: Bool { - get { - return (self.rawValue & 0x0200) == 0x0200 - } - set { - if newValue { - self.rawValue |= 0x0200 - } else { - self.rawValue &= (~0x0200) - } + /// This is true when the subject public key is used for verifying signatures on + /// certificate revocation lists. + @inlinable + public var cRLSign: Bool { + get { + return (self.rawValue & 0x0200) == 0x0200 + } + set { + if newValue { + self.rawValue |= 0x0200 + } else { + self.rawValue &= (~0x0200) } } + } - /// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that - /// case, the subject public key may only be used for encrypting data while performing key - /// agreement. - @inlinable - public var encipherOnly: Bool { - get { - return (self.rawValue & 0x0100) == 0x0100 - } - set { - if newValue { - self.rawValue |= 0x0100 - } else { - self.rawValue &= (~0x0100) - } + /// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that + /// case, the subject public key may only be used for encrypting data while performing key + /// agreement. + @inlinable + public var encipherOnly: Bool { + get { + return (self.rawValue & 0x0100) == 0x0100 + } + set { + if newValue { + self.rawValue |= 0x0100 + } else { + self.rawValue &= (~0x0100) } } + } - /// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that - /// case, the subject public key may only be used for decrypting data while performing key - /// agreement. - @inlinable - public var decipherOnly: Bool { - get { - return (self.rawValue & 0x0080) == 0x0080 - } - set { - if newValue { - self.rawValue |= 0x0080 - } else { - self.rawValue &= (~0x0080) - } + /// This only has meaning when the ``keyAgreement`` field is also `true`. When `true` in that + /// case, the subject public key may only be used for decrypting data while performing key + /// agreement. + @inlinable + public var decipherOnly: Bool { + get { + return (self.rawValue & 0x0080) == 0x0080 + } + set { + if newValue { + self.rawValue |= 0x0080 + } else { + self.rawValue &= (~0x0080) } } + } - @inlinable - internal static func validateBitString(_ bitstring: ASN1BitString) throws { - switch bitstring.bytes.count { - case 0: - // This is fine, no bits are set. - precondition(bitstring.paddingBits == 0) - case 1: - // This is fine, no more than 8 bits. - // We want to confirm that the bit _before_ the first padding bit isn't 0. - // We cannot have 8 padding bits. - precondition(bitstring.paddingBits < 8) - let bitMask = UInt8(0x01) << bitstring.paddingBits - if (bitstring.bytes[bitstring.bytes.startIndex] & bitMask) == 0 { - throw ASN1Error.invalidASN1Object(reason: "Invalid leading padding bit") - } - case 2 where bitstring.paddingBits == 7: - // This is fine, there are 9 valid bits: 8 from the prior byte and 1 here. - if (bitstring.bytes[bitstring.bytes.startIndex &+ 1] & 0x80) == 0 { - throw ASN1Error.invalidASN1Object(reason: "Invalid padding bit") - } - default: - // Too many bits! - throw ASN1Error.invalidASN1Object(reason: "Too many bits for Key Usage") + @inlinable + internal static func validateBitString(_ bitstring: ASN1BitString) throws { + switch bitstring.bytes.count { + case 0: + // This is fine, no bits are set. + precondition(bitstring.paddingBits == 0) + case 1: + // This is fine, no more than 8 bits. + // We want to confirm that the bit _before_ the first padding bit isn't 0. + // We cannot have 8 padding bits. + precondition(bitstring.paddingBits < 8) + let bitMask = UInt8(0x01) << bitstring.paddingBits + if (bitstring.bytes[bitstring.bytes.startIndex] & bitMask) == 0 { + throw ASN1Error.invalidASN1Object(reason: "Invalid leading padding bit") } + case 2 where bitstring.paddingBits == 7: + // This is fine, there are 9 valid bits: 8 from the prior byte and 1 here. + if (bitstring.bytes[bitstring.bytes.startIndex &+ 1] & 0x80) == 0 { + throw ASN1Error.invalidASN1Object(reason: "Invalid padding bit") + } + default: + // Too many bits! + throw ASN1Error.invalidASN1Object(reason: "Too many bits for Key Usage") } } } -extension Certificate.Extensions.KeyUsage: Hashable { } +extension KeyUsage: Hashable { } -extension Certificate.Extensions.KeyUsage: Sendable { } +extension KeyUsage: Sendable { } -extension Certificate.Extensions.KeyUsage: CustomStringConvertible { +extension KeyUsage: CustomStringConvertible { public var description: String { var enabledUsages: [String] = [] @@ -321,7 +319,7 @@ extension Certificate.Extension { /// - keyUsage: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ keyUsage: Certificate.Extensions.KeyUsage, critical: Bool) throws { + public init(_ keyUsage: KeyUsage, critical: Bool) throws { let asn1Representation = ASN1BitString(keyUsage) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -329,7 +327,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.KeyUsage: CertificateExtensionConvertible { +extension KeyUsage: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } @@ -354,7 +352,7 @@ extension UInt16 { extension ASN1BitString { @inlinable - init(_ ext: Certificate.Extensions.KeyUsage) { + init(_ ext: KeyUsage) { if ext.decipherOnly { // We need two bytes here. let bytes = [UInt8(truncatingIfNeeded: ext.rawValue >> 8), UInt8(truncatingIfNeeded: ext.rawValue)] diff --git a/Sources/X509/Extension Types/NameConstraints.swift b/Sources/X509/Extension Types/NameConstraints.swift index a63de4f..e44860b 100644 --- a/Sources/X509/Extension Types/NameConstraints.swift +++ b/Sources/X509/Extension Types/NameConstraints.swift @@ -14,284 +14,282 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Constraints the namespace within which all subject names issued by a given CA must reside. +/// Constraints the namespace within which all subject names issued by a given CA must reside. +/// +/// These constraints apply both to the ``Certificate/subject`` and also to any +/// ``SubjectAlternativeNames`` that may be present. Restrictions are applied to +/// specific name _forms_, and when the form is not present then the restriction does not apply. +/// +/// Restrictions are defined in terms of both permitted and forbidden subtrees. The forbidden trees +/// are consulted first, and if a name is matched in a forbidden tree then it does not matter whether +/// the same name is also matched in a permitted tree. +public struct NameConstraints { + /// The DNS name trees that are permitted in certificates issued by this CA. /// - /// These constraints apply both to the ``Certificate/subject`` and also to any - /// ``SubjectAlternativeNames-swift.struct`` that may be present. Restrictions are applied to - /// specific name _forms_, and when the form is not present then the restriction does not apply. + /// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be + /// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint. + public var permittedDNSDomains: [String] { + // TODO(cory): We probably want a different collection type here that can lazily construct its contents, and + // that will let us support people assigning into this collection. + get { + self.permittedSubtrees.compactMap { + if case .dNSName(let name) = $0 { + return name + } else { + return nil + } + } + } + set { + fatalError("TODO") + } + } + + /// The DNS name trees that are forbidden in certificates issued by this CA. /// - /// Restrictions are defined in terms of both permitted and forbidden subtrees. The forbidden trees - /// are consulted first, and if a name is matched in a forbidden tree then it does not matter whether - /// the same name is also matched in a permitted tree. - public struct NameConstraints { - /// The DNS name trees that are permitted in certificates issued by this CA. - /// - /// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be - /// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint. - public var permittedDNSDomains: [String] { - // TODO(cory): We probably want a different collection type here that can lazily construct its contents, and - // that will let us support people assigning into this collection. - get { - self.permittedSubtrees.compactMap { - if case .dNSName(let name) = $0 { - return name - } else { - return nil - } + /// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be + /// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint. + public var excludedDNSDomains: [String] { + get { + self.excludedSubtrees.compactMap { + if case .dNSName(let name) = $0 { + return name + } else { + return nil } } - set { - fatalError("TODO") - } } + set { + fatalError("TODO") + } + } - /// The DNS name trees that are forbidden in certificates issued by this CA. - /// - /// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be - /// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint. - public var excludedDNSDomains: [String] { - get { - self.excludedSubtrees.compactMap { - if case .dNSName(let name) = $0 { - return name - } else { - return nil - } + /// The IP ranges that are permitted in certificates issued by this CA. + /// + /// These restrictions are expressed as a subnet, represented in an ASN.1 octet string. + /// Due to the absence of a currency subnet and IP address type in Swift, these are preserved + /// as octet strings. + /// + /// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`. + /// This represents a subnet root and its mask. + /// + /// Any IP address attested that falls within one of these subnets matches the constraint. + public var permittedIPRanges: [ASN1OctetString] { + get { + self.permittedSubtrees.compactMap { + if case .iPAddress(let address) = $0 { + return address + } else { + return nil } } - set { - fatalError("TODO") - } } + set { + fatalError("TODO") + } + } - /// The IP ranges that are permitted in certificates issued by this CA. - /// - /// These restrictions are expressed as a subnet, represented in an ASN.1 octet string. - /// Due to the absence of a currency subnet and IP address type in Swift, these are preserved - /// as octet strings. - /// - /// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`. - /// This represents a subnet root and its mask. - /// - /// Any IP address attested that falls within one of these subnets matches the constraint. - public var permittedIPRanges: [ASN1OctetString] { - get { - self.permittedSubtrees.compactMap { - if case .iPAddress(let address) = $0 { - return address - } else { - return nil - } + /// The IP ranges that are forbidden in certificates issued by this CA. + /// + /// These restrictions are expressed as a subnet, represented in an ASN.1 octet string. + /// Due to the absence of a currency subnet and IP address type in Swift, these are preserved + /// as octet strings. + /// + /// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`. + /// This represents a subnet root and its mask. + /// + /// Any IP address attested that falls within one of these subnets matches the constraint. + public var excludedIPRanges: [ASN1OctetString] { + get { + self.excludedSubtrees.compactMap { + if case .iPAddress(let address) = $0 { + return address + } else { + return nil } } - set { - fatalError("TODO") - } } + set { + fatalError("TODO") + } + } - /// The IP ranges that are forbidden in certificates issued by this CA. - /// - /// These restrictions are expressed as a subnet, represented in an ASN.1 octet string. - /// Due to the absence of a currency subnet and IP address type in Swift, these are preserved - /// as octet strings. - /// - /// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`. - /// This represents a subnet root and its mask. - /// - /// Any IP address attested that falls within one of these subnets matches the constraint. - public var excludedIPRanges: [ASN1OctetString] { - get { - self.excludedSubtrees.compactMap { - if case .iPAddress(let address) = $0 { - return address - } else { - return nil - } + /// The email addresses that are permitted in certificates issued by this CA. + /// + /// This form may contain a specific mailbox (e.g. `user@example.com`), all + /// addresses on a given host (e.g. `example.com`), or all mailboxes within a + /// given domain (e.g. `.example.com`). + public var permittedEmailAddresses: [String] { + get { + self.permittedSubtrees.compactMap { + if case .rfc822Name(let name) = $0 { + return name + } else { + return nil } } - set { - fatalError("TODO") - } } + set { + fatalError("TODO") + } + } - /// The email addresses that are permitted in certificates issued by this CA. - /// - /// This form may contain a specific mailbox (e.g. `user@example.com`), all - /// addresses on a given host (e.g. `example.com`), or all mailboxes within a - /// given domain (e.g. `.example.com`). - public var permittedEmailAddresses: [String] { - get { - self.permittedSubtrees.compactMap { - if case .rfc822Name(let name) = $0 { - return name - } else { - return nil - } + /// The email addresses that are permitted in certificates issued by this CA. + /// + /// This form may contain a specific mailbox (e.g. `user@example.com`), all + /// addresses on a given host (e.g. `example.com`), or all mailboxes within a + /// given domain (e.g. `.example.com`). + public var excludedEmailAddresses: [String] { + get { + self.excludedSubtrees.compactMap { + if case .rfc822Name(let name) = $0 { + return name + } else { + return nil } } - set { - fatalError("TODO") - } } + set { + fatalError("TODO") + } + } - /// The email addresses that are permitted in certificates issued by this CA. - /// - /// This form may contain a specific mailbox (e.g. `user@example.com`), all - /// addresses on a given host (e.g. `example.com`), or all mailboxes within a - /// given domain (e.g. `.example.com`). - public var excludedEmailAddresses: [String] { - get { - self.excludedSubtrees.compactMap { - if case .rfc822Name(let name) = $0 { - return name - } else { - return nil - } + /// The URI domains permitted in certificates issued by this CA. + /// + /// This contraint applies only to the host part of the URI. The constraint + /// must be specified as a fully-qualified domain name and may specify either + /// a host or a domain. When it specifies a domain the string will begin with a + /// period, and matches any name that can be expanded with one or more labels to + /// the left. Note that expanding with zero labels does not match: that is, + /// `.example.com` matches `host.example.com`, but not `example.com`. + public var permittedURIDomains: [String] { + get { + self.permittedSubtrees.compactMap { + if case .uniformResourceIdentifier(let name) = $0 { + return name + } else { + return nil } } - set { - fatalError("TODO") - } } + set { + fatalError("TODO") + } + } - /// The URI domains permitted in certificates issued by this CA. - /// - /// This contraint applies only to the host part of the URI. The constraint - /// must be specified as a fully-qualified domain name and may specify either - /// a host or a domain. When it specifies a domain the string will begin with a - /// period, and matches any name that can be expanded with one or more labels to - /// the left. Note that expanding with zero labels does not match: that is, - /// `.example.com` matches `host.example.com`, but not `example.com`. - public var permittedURIDomains: [String] { - get { - self.permittedSubtrees.compactMap { - if case .uniformResourceIdentifier(let name) = $0 { - return name - } else { - return nil - } + /// The URI domains forbidden in certificates issued by this CA. + /// + /// This contraint applies only to the host part of the URI. The constraint + /// must be specified as a fully-qualified domain name and may specify either + /// a host or a domain. When it specifies a domain the string will begin with a + /// period, and matches any name that can be expanded with one or more labels to + /// the left. Note that expanding with zero labels does not match: that is, + /// `.example.com` matches `host.example.com`, but not `example.com`. + public var forbiddenURIDomains: [String] { + get { + self.excludedSubtrees.compactMap { + if case .uniformResourceIdentifier(let name) = $0 { + return name + } else { + return nil } } - set { - fatalError("TODO") - } + } + set { + fatalError("TODO") + } + } + + /// The complete set of permitted subtrees in ``GeneralName`` form. + /// + /// This contains the same data as the broken out forms (``permittedIPRanges``, ``permittedDNSDomains``, + /// ``permittedURIDomains``, ``permittedEmailAddresses``), but may also include other cases + /// that those helpers do not represent. + public var permittedSubtrees: [GeneralName] + + /// The complete set of forbidden subtrees in ``GeneralName`` form. + /// + /// This contains the same data as the broken out forms (``excludedIPRanges``, ``excludedDNSDomains``, + /// ``forbiddenURIDomains``, ``excludedEmailAddresses``), but may also include other cases + /// that those helpers do not represent. + public var excludedSubtrees: [GeneralName] + + /// Construct an extension constraining the names a CA may issue. + /// + /// - Parameters: + /// - permittedDNSDomains: The DNS name trees that are permitted in certificates issued by this CA. + /// - excludedDNSDomains: The DNS name trees that are forbidden in certificates issued by this CA. + /// - permittedIPRanges: The IP address ranges that are permitted in certificates issued by this CA. + /// - excludedIPRanges: The IP address ranges that are forbidden in certificates issued by this CA. + /// - permittedEmailAddresses: The email address trees that are permitted in certificates issued by this CA. + /// - excludedEmailAddress: The email address trees that are forbidden in certificates issued by this CA. + /// - permittedURIDomains: The URI domains that are permitted in certificates issued by this CA. + /// - excludedURIDomains: The URI domains that are forbidden in certificates issued by this CA. + @inlinable + public init( + permittedDNSDomains: [String] = [], + excludedDNSDomains: [String] = [], + permittedIPRanges: [ASN1OctetString] = [], + excludedIPRanges: [ASN1OctetString] = [], + permittedEmailAddresses: [String] = [], + excludedEmailAddresses: [String] = [], + permittedURIDomains: [String] = [], + forbiddenURIDomains: [String] = [] + ) { + self.permittedSubtrees = [] + self.excludedSubtrees = [] + + self.permittedDNSDomains = permittedDNSDomains + self.excludedDNSDomains = excludedDNSDomains + self.permittedIPRanges = permittedIPRanges + self.excludedIPRanges = excludedIPRanges + self.permittedEmailAddresses = permittedEmailAddresses + self.excludedEmailAddresses = excludedEmailAddresses + self.permittedURIDomains = permittedURIDomains + self.forbiddenURIDomains = forbiddenURIDomains + } + + /// Construct an extension constraining the names a CA may issue. + /// + /// - Parameters: + /// - permittedSubtrees: The complete set of permitted subtrees in ``GeneralName`` form. + /// - excludedSubtrees: The complete set of excluded subtrees in ``GeneralName`` form. + @inlinable + public init( + permittedSubtrees: [GeneralName] = [], + excludedSubtrees: [GeneralName] = [] + ) { + self.permittedSubtrees = permittedSubtrees + self.excludedSubtrees = excludedSubtrees + } + + /// Create a new ``NameConstraints`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.nameConstraints`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.nameConstraints else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.nameConstraints), got \(ext.oid)") } - /// The URI domains forbidden in certificates issued by this CA. - /// - /// This contraint applies only to the host part of the URI. The constraint - /// must be specified as a fully-qualified domain name and may specify either - /// a host or a domain. When it specifies a domain the string will begin with a - /// period, and matches any name that can be expanded with one or more labels to - /// the left. Note that expanding with zero labels does not match: that is, - /// `.example.com` matches `host.example.com`, but not `example.com`. - public var forbiddenURIDomains: [String] { - get { - self.excludedSubtrees.compactMap { - if case .uniformResourceIdentifier(let name) = $0 { - return name - } else { - return nil - } - } - } - set { - fatalError("TODO") - } + let nameConstraintsValue = try NameConstraintsValue(derEncoded: ext.value) + guard nameConstraintsValue.permittedSubtrees != nil || nameConstraintsValue.excludedSubtrees != nil else { + throw ASN1Error.invalidASN1Object(reason: "Name Constraints has no permitted or excluded subtrees") } - /// The complete set of permitted subtrees in ``GeneralName`` form. - /// - /// This contains the same data as the broken out forms (``permittedIPRanges``, ``permittedDNSDomains``, - /// ``permittedURIDomains``, ``permittedEmailAddresses``), but may also include other cases - /// that those helpers do not represent. - public var permittedSubtrees: [GeneralName] - - /// The complete set of forbidden subtrees in ``GeneralName`` form. - /// - /// This contains the same data as the broken out forms (``excludedIPRanges``, ``excludedDNSDomains``, - /// ``forbiddenURIDomains``, ``excludedEmailAddresses``), but may also include other cases - /// that those helpers do not represent. - public var excludedSubtrees: [GeneralName] - - /// Construct an extension constraining the names a CA may issue. - /// - /// - Parameters: - /// - permittedDNSDomains: The DNS name trees that are permitted in certificates issued by this CA. - /// - excludedDNSDomains: The DNS name trees that are forbidden in certificates issued by this CA. - /// - permittedIPRanges: The IP address ranges that are permitted in certificates issued by this CA. - /// - excludedIPRanges: The IP address ranges that are forbidden in certificates issued by this CA. - /// - permittedEmailAddresses: The email address trees that are permitted in certificates issued by this CA. - /// - excludedEmailAddress: The email address trees that are forbidden in certificates issued by this CA. - /// - permittedURIDomains: The URI domains that are permitted in certificates issued by this CA. - /// - excludedURIDomains: The URI domains that are forbidden in certificates issued by this CA. - @inlinable - public init( - permittedDNSDomains: [String] = [], - excludedDNSDomains: [String] = [], - permittedIPRanges: [ASN1OctetString] = [], - excludedIPRanges: [ASN1OctetString] = [], - permittedEmailAddresses: [String] = [], - excludedEmailAddresses: [String] = [], - permittedURIDomains: [String] = [], - forbiddenURIDomains: [String] = [] - ) { - self.permittedSubtrees = [] - self.excludedSubtrees = [] - - self.permittedDNSDomains = permittedDNSDomains - self.excludedDNSDomains = excludedDNSDomains - self.permittedIPRanges = permittedIPRanges - self.excludedIPRanges = excludedIPRanges - self.permittedEmailAddresses = permittedEmailAddresses - self.excludedEmailAddresses = excludedEmailAddresses - self.permittedURIDomains = permittedURIDomains - self.forbiddenURIDomains = forbiddenURIDomains - } - - /// Construct an extension constraining the names a CA may issue. - /// - /// - Parameters: - /// - permittedSubtrees: The complete set of permitted subtrees in ``GeneralName`` form. - /// - excludedSubtrees: The complete set of excluded subtrees in ``GeneralName`` form. - @inlinable - public init( - permittedSubtrees: [GeneralName] = [], - excludedSubtrees: [GeneralName] = [] - ) { - self.permittedSubtrees = permittedSubtrees - self.excludedSubtrees = excludedSubtrees - } - - /// Create a new ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.nameConstraints`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.nameConstraints else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.nameConstraints), got \(ext.oid)") - } - - let nameConstraintsValue = try NameConstraintsValue(derEncoded: ext.value) - guard nameConstraintsValue.permittedSubtrees != nil || nameConstraintsValue.excludedSubtrees != nil else { - throw ASN1Error.invalidASN1Object(reason: "Name Constraints has no permitted or excluded subtrees") - } - - self.permittedSubtrees = nameConstraintsValue.permittedSubtrees ?? [] - self.excludedSubtrees = nameConstraintsValue.excludedSubtrees ?? [] - } + self.permittedSubtrees = nameConstraintsValue.permittedSubtrees ?? [] + self.excludedSubtrees = nameConstraintsValue.excludedSubtrees ?? [] } } -extension Certificate.Extensions.NameConstraints: Hashable { } +extension NameConstraints: Hashable { } -extension Certificate.Extensions.NameConstraints: Sendable { } +extension NameConstraints: Sendable { } -extension Certificate.Extensions.NameConstraints: CustomStringConvertible { +extension NameConstraints: CustomStringConvertible { public var description: String { var elements: [String] = [] @@ -313,7 +311,7 @@ extension Certificate.Extension { /// - nameConstraints: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ nameConstraints: Certificate.Extensions.NameConstraints, critical: Bool) throws { + public init(_ nameConstraints: NameConstraints, critical: Bool) throws { let asn1Representation = NameConstraintsValue(nameConstraints) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -321,7 +319,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.NameConstraints: CertificateExtensionConvertible { +extension NameConstraints: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } @@ -348,7 +346,7 @@ struct NameConstraintsValue: DERImplicitlyTaggable { } @inlinable - init(_ ext: Certificate.Extensions.NameConstraints) { + init(_ ext: NameConstraints) { if !ext.permittedSubtrees.isEmpty { self.permittedSubtrees = ext.permittedSubtrees } diff --git a/Sources/X509/Extension Types/SubjectAlternativeName.swift b/Sources/X509/Extension Types/SubjectAlternativeName.swift index a674521..a69181b 100644 --- a/Sources/X509/Extension Types/SubjectAlternativeName.swift +++ b/Sources/X509/Extension Types/SubjectAlternativeName.swift @@ -14,60 +14,58 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Allows identities to be bound to the subject of a certificate. +/// Allows identities to be bound to the subject of a certificate. +/// +/// The identities attested in this extension belong to the subject of the certificate. +/// Users of the certificate may validate that these names correspond to a name they are +/// expecting, depending on the context. +public struct SubjectAlternativeNames { + @usableFromInline + var names: [GeneralName] + + /// Construct a Subject Alternative Name extension from a sequence of + /// ``GeneralName``s. /// - /// The identities attested in this extension belong to the subject of the certificate. - /// Users of the certificate may validate that these names correspond to a name they are - /// expecting, depending on the context. - public struct SubjectAlternativeNames { - @usableFromInline - var names: [GeneralName] + /// - Parameter names: The names to bind to the subject of the certificate. + @inlinable + public init(_ names: Names) where Names.Element == GeneralName { + self.names = Array(names) + } - /// Construct a Subject Alternative Name extension from a sequence of - /// ``GeneralName``s. - /// - /// - Parameter names: The names to bind to the subject of the certificate. - @inlinable - public init(_ names: Names) where Names.Element == GeneralName { - self.names = Array(names) + /// Construct a Subject Alternative Name extension that attests to no names. + @inlinable + public init() { + self.names = [] + } + + /// Create a new ``SubjectAlternativeNames`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.subjectAlternativeName else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName), got \(ext.oid)") } - /// Construct a Subject Alternative Name extension that attests to no names. - @inlinable - public init() { - self.names = [] - } - - /// Create a new ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.subjectAlternativeName else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName), got \(ext.oid)") - } - - let asn1SAN = try GeneralNames(derEncoded: ext.value) - self.names = asn1SAN.names - } + let asn1SAN = try GeneralNames(derEncoded: ext.value) + self.names = asn1SAN.names } } -extension Certificate.Extensions.SubjectAlternativeNames: Hashable { } +extension SubjectAlternativeNames: Hashable { } -extension Certificate.Extensions.SubjectAlternativeNames: Sendable { } +extension SubjectAlternativeNames: Sendable { } -extension Certificate.Extensions.SubjectAlternativeNames: CustomStringConvertible { +extension SubjectAlternativeNames: CustomStringConvertible { public var description: String { self.lazy.map { String(describing: $0) }.joined(separator: ", ") } } -extension Certificate.Extensions.SubjectAlternativeNames: RandomAccessCollection, MutableCollection, RangeReplaceableCollection { +extension SubjectAlternativeNames: RandomAccessCollection, MutableCollection, RangeReplaceableCollection { @inlinable public var startIndex: Int { self.names.startIndex @@ -101,7 +99,7 @@ extension Certificate.Extension { /// - san: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ san: Certificate.Extensions.SubjectAlternativeNames, critical: Bool) throws { + public init(_ san: SubjectAlternativeNames, critical: Bool) throws { let asn1Representation = GeneralNames(san.names) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -109,7 +107,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.SubjectAlternativeNames: CertificateExtensionConvertible { +extension SubjectAlternativeNames: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } diff --git a/Sources/X509/Extension Types/SubjectKeyIdentifier.swift b/Sources/X509/Extension Types/SubjectKeyIdentifier.swift index 16da975..991ce27 100644 --- a/Sources/X509/Extension Types/SubjectKeyIdentifier.swift +++ b/Sources/X509/Extension Types/SubjectKeyIdentifier.swift @@ -14,47 +14,45 @@ import SwiftASN1 -extension Certificate.Extensions { - /// Provides a means of identifying a certificate that contains a particular public key. +/// Provides a means of identifying a certificate that contains a particular public key. +/// +/// This extension contains a value derived from the public key of the certificate in which it appears. +/// That value can be used to build the ``AuthorityKeyIdentifier/keyIdentifier`` field in +/// any certificate issued by this certificate. This makes it possible to identify a certificate +/// possessing the key that issued another certificate. +public struct SubjectKeyIdentifier { + public var keyIdentifier: ArraySlice + + /// Construct a Subject Key Identifier extension with a specific key identifier. /// - /// This extension contains a value derived from the public key of the certificate in which it appears. - /// That value can be used to build the ``AuthorityKeyIdentifier-swift.struct/keyIdentifier`` field in - /// any certificate issued by this certificate. This makes it possible to identify a certificate - /// possessing the key that issued another certificate. - public struct SubjectKeyIdentifier { - public var keyIdentifier: ArraySlice + /// - Parameter keyIdentifier: The identifier to associate with this certificate. + @inlinable + public init(keyIdentifier: ArraySlice) { + self.keyIdentifier = keyIdentifier + } - /// Construct a Subject Key Identifier extension with a specific key identifier. - /// - /// - Parameter keyIdentifier: The identifier to associate with this certificate. - @inlinable - public init(keyIdentifier: ArraySlice) { - self.keyIdentifier = keyIdentifier + /// Create a new ``SubjectKeyIdentifier`` object + /// by unwrapping a ``Certificate/Extension``. + /// + /// - Parameter ext: The ``Certificate/Extension`` to unwrap + /// - Throws: if the ``Certificate/Extension/oid`` is not equal to + /// `ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier`. + @inlinable + public init(_ ext: Certificate.Extension) throws { + guard ext.oid == .X509ExtensionID.subjectKeyIdentifier else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier), got \(ext.oid)") } - /// Create a new ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct`` object - /// by unwrapping a ``Certificate/Extension``. - /// - /// - Parameter ext: The ``Certificate/Extension`` to unwrap - /// - Throws: if the ``Certificate/Extension/oid`` is not equal to - /// `ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier`. - @inlinable - public init(_ ext: Certificate.Extension) throws { - guard ext.oid == .X509ExtensionID.subjectKeyIdentifier else { - throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier), got \(ext.oid)") - } - - let asn1KeyIdentifier = try ASN1OctetString(derEncoded: ext.value) - self.keyIdentifier = asn1KeyIdentifier.bytes - } + let asn1KeyIdentifier = try ASN1OctetString(derEncoded: ext.value) + self.keyIdentifier = asn1KeyIdentifier.bytes } } -extension Certificate.Extensions.SubjectKeyIdentifier: Hashable { } +extension SubjectKeyIdentifier: Hashable { } -extension Certificate.Extensions.SubjectKeyIdentifier: Sendable { } +extension SubjectKeyIdentifier: Sendable { } -extension Certificate.Extensions.SubjectKeyIdentifier: CustomStringConvertible { +extension SubjectKeyIdentifier: CustomStringConvertible { public var description: String { return self.keyIdentifier.lazy.map { String($0, radix: 16) }.joined(separator: ":") } @@ -67,7 +65,7 @@ extension Certificate.Extension { /// - ski: The extension to wrap /// - critical: Whether this extension should have the critical bit set. @inlinable - public init(_ ski: Certificate.Extensions.SubjectKeyIdentifier, critical: Bool) throws { + public init(_ ski: SubjectKeyIdentifier, critical: Bool) throws { let asn1Representation = ASN1OctetString(contentBytes: ski.keyIdentifier) var serializer = DER.Serializer() try serializer.serialize(asn1Representation) @@ -75,7 +73,7 @@ extension Certificate.Extension { } } -extension Certificate.Extensions.SubjectKeyIdentifier: CertificateExtensionConvertible { +extension SubjectKeyIdentifier: CertificateExtensionConvertible { public func makeCertificateExtension() throws -> Certificate.Extension { return try .init(self, critical: false) } diff --git a/Sources/X509/Extension.swift b/Sources/X509/Extension.swift index 81ef507..8aa1c0d 100644 --- a/Sources/X509/Extension.swift +++ b/Sources/X509/Extension.swift @@ -24,14 +24,14 @@ extension Certificate { /// it does not understand. A number of extensions have built-in support, and can be decoded directly from an ``Extension`` /// value. These are: /// - /// - ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct`` - /// - ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` - /// - ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` - /// - ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` - /// - ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` - /// - ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct`` - /// - ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` - /// - ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct`` + /// - ``AuthorityInformationAccess`` + /// - ``AuthorityKeyIdentifier`` + /// - ``BasicConstraints`` + /// - ``ExtendedKeyUsage`` + /// - ``KeyUsage`` + /// - ``NameConstraints`` + /// - ``SubjectAlternativeNames`` + /// - ``SubjectKeyIdentifier`` /// /// Users can write their own types by using a similar approach to these types, when it is necessary to add support for /// different X.509 extension. diff --git a/Sources/X509/Extensions.swift b/Sources/X509/Extensions.swift index a548817..539759e 100644 --- a/Sources/X509/Extensions.swift +++ b/Sources/X509/Extensions.swift @@ -33,7 +33,7 @@ extension Certificate { /// is semantic and is preserved either in or from the serialized representation. /// /// However, ``Certificate/Extensions-swift.struct`` is also conceptually a dictionary keyed by ``Certificate/Extension/oid``. - /// For that reason, in addition to the index-based subscript ``Certificate/Extensions-swift.struct/subscript(_:)-5rodj``, this type also offers + /// For that reason, in addition to the index-based subscript ``subscript(_:)-5rodj``, this type also offers /// ``subscript(oid:)`` to enable finding the extension with a specific OID. This API also lets users replace /// the value of a specific extension. /// @@ -41,14 +41,14 @@ extension Certificate { /// /// To make it easier to decode specific extensions, this type provides a number of helpers for known extension types: /// - /// - ``authorityInformationAccess-swift.property`` - /// - ``subjectKeyIdentifier-swift.property`` - /// - ``authorityKeyIdentifier-swift.property`` - /// - ``extendedKeyUsage-swift.property`` - /// - ``basicConstraints-swift.property`` - /// - ``keyUsage-swift.property`` - /// - ``nameConstraints-swift.property`` - /// - ``subjectAlternativeNames-swift.property`` + /// - ``authorityInformationAccess`` + /// - ``subjectKeyIdentifier`` + /// - ``authorityKeyIdentifier`` + /// - ``extendedKeyUsage`` + /// - ``basicConstraints`` + /// - ``keyUsage`` + /// - ``nameConstraints`` + /// - ``subjectAlternativeNames`` /// /// Users who add their own extension types (see ``Certificate/Extension`` for more) are encouraged to add their /// own helper getters for those types. @@ -63,16 +63,16 @@ extension Certificate { /// ```swift /// let extensions = Certificate.Extensions { /// Critical( - /// Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) + /// KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) /// ) /// - /// Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth]) + /// ExtendedKeyUsage([.serverAuth, .clientAuth]) /// /// Critical( - /// Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0) + /// BasicConstraints.isCertificateAuthority(maxPathLength: 0) /// ) /// - /// Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) + /// AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) /// } /// ``` /// @@ -108,16 +108,16 @@ extension Certificate { /// ```swift /// let extensions = Certificate.Extensions { /// Critical( - /// Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) + /// KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) /// ) /// - /// Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth]) + /// ExtendedKeyUsage([.serverAuth, .clientAuth]) /// /// Critical( - /// Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0) + /// BasicConstraints.isCertificateAuthority(maxPathLength: 0) /// ) /// - /// Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) + /// AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) /// } /// ``` /// @@ -209,89 +209,89 @@ extension Certificate.Extensions { } } - /// Loads the ``Certificate/Extensions-swift.struct/AuthorityInformationAccess-swift.struct`` + /// Loads the ``AuthorityInformationAccess`` /// extension, if it is present. /// /// Throws if it is not possible to decode the AIA extension. @inlinable - public var authorityInformationAccess: Certificate.Extensions.AuthorityInformationAccess? { + public var authorityInformationAccess: AuthorityInformationAccess? { get throws { try self[oid: .X509ExtensionID.authorityInformationAccess].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/SubjectKeyIdentifier-swift.struct`` + /// Loads the ``SubjectKeyIdentifier`` /// extension, if it is present. /// /// Throws if it is not possible to decode the SKI extension. @inlinable - public var subjectKeyIdentifier: Certificate.Extensions.SubjectKeyIdentifier? { + public var subjectKeyIdentifier: SubjectKeyIdentifier? { get throws { try self[oid: .X509ExtensionID.subjectKeyIdentifier].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/AuthorityKeyIdentifier-swift.struct`` + /// Loads the ``AuthorityKeyIdentifier`` /// extension, if it is present. /// /// Throws if it is not possible to decode the AKI extension. @inlinable - public var authorityKeyIdentifier: Certificate.Extensions.AuthorityKeyIdentifier? { + public var authorityKeyIdentifier: AuthorityKeyIdentifier? { get throws { try self[oid: .X509ExtensionID.authorityKeyIdentifier].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/ExtendedKeyUsage-swift.struct`` + /// Loads the ``ExtendedKeyUsage`` /// extension, if it is present. /// /// Throws if it is not possible to decode the EKU extension. @inlinable - public var extendedKeyUsage: Certificate.Extensions.ExtendedKeyUsage? { + public var extendedKeyUsage: ExtendedKeyUsage? { get throws { try self[oid: .X509ExtensionID.extendedKeyUsage].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/BasicConstraints-swift.enum`` + /// Loads the ``BasicConstraints`` /// extension, if it is present. /// /// Throws if it is not possible to decode the basic constraints extension. @inlinable - public var basicConstraints: Certificate.Extensions.BasicConstraints? { + public var basicConstraints: BasicConstraints? { get throws { try self[oid: .X509ExtensionID.basicConstraints].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/KeyUsage-swift.struct`` + /// Loads the ``KeyUsage`` /// extension, if it is present. /// /// Throws if it is not possible to decode the key usage extension. @inlinable - public var keyUsage: Certificate.Extensions.KeyUsage? { + public var keyUsage: KeyUsage? { get throws { try self[oid: .X509ExtensionID.keyUsage].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/NameConstraints-swift.struct`` + /// Loads the ``NameConstraints`` /// extension, if it is present. /// /// Throws if it is not possible to decode the name constraints extension. @inlinable - public var nameConstraints: Certificate.Extensions.NameConstraints? { + public var nameConstraints: NameConstraints? { get throws { try self[oid: .X509ExtensionID.nameConstraints].map { try .init($0) } } } - /// Loads the ``Certificate/Extensions-swift.struct/SubjectAlternativeNames-swift.struct`` + /// Loads the ``SubjectAlternativeNames`` /// extension, if it is present. /// /// Throws if it is not possible to decode the SAN extension. @inlinable - public var subjectAlternativeNames: Certificate.Extensions.SubjectAlternativeNames? { + public var subjectAlternativeNames: SubjectAlternativeNames? { get throws { try self[oid: .X509ExtensionID.subjectAlternativeName].map { try .init($0) } } diff --git a/Sources/X509/ExtensionsBuilder.swift b/Sources/X509/ExtensionsBuilder.swift index 3f41190..66efac3 100644 --- a/Sources/X509/ExtensionsBuilder.swift +++ b/Sources/X509/ExtensionsBuilder.swift @@ -21,16 +21,16 @@ /// ```swift /// let extensions = Certificate.Extensions { /// Critical( -/// Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) +/// KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) /// ) /// -/// Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth]) +/// ExtendedKeyUsage([.serverAuth, .clientAuth]) /// /// Critical( -/// Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0) +/// BasicConstraints.isCertificateAuthority(maxPathLength: 0) /// ) /// -/// Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) +/// AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) /// } /// ``` /// diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 7463e5e..d92d45f 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -136,7 +136,7 @@ public struct OCSPVerifierPolicy: VerifierPolicy { private func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult { - let authorityInformationAccess: Certificate.Extensions.AuthorityInformationAccess? + let authorityInformationAccess: AuthorityInformationAccess? do { authorityInformationAccess = try certificate.extensions.authorityInformationAccess } catch { diff --git a/Sources/X509/Verifier/Verifier.swift b/Sources/X509/Verifier/Verifier.swift index 800bfc9..c2b789b 100644 --- a/Sources/X509/Verifier/Verifier.swift +++ b/Sources/X509/Verifier/Verifier.swift @@ -167,7 +167,7 @@ extension Array where Element == Certificate { } extension Certificate { - func issuerPreference(subjectAKI: Certificate.Extensions.AuthorityKeyIdentifier) -> Int { + func issuerPreference(subjectAKI: AuthorityKeyIdentifier) -> Int { guard let ski = try? self.extensions.subjectKeyIdentifier else { // Medium preference: we have no SKI. return 0 diff --git a/Tests/X509Tests/CertificateDERTests.swift b/Tests/X509Tests/CertificateDERTests.swift index fb0d4e2..eaf3cbe 100644 --- a/Tests/X509Tests/CertificateDERTests.swift +++ b/Tests/X509Tests/CertificateDERTests.swift @@ -234,21 +234,21 @@ final class CertificateDERTests: XCTestCase { let cert = try Certificate(derEncoded: binary) let expectedExtensions = try Certificate.Extensions { - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: [0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8, 0xAE, 0x1B, 0xAE]) + SubjectKeyIdentifier(keyIdentifier: [0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8, 0xAE, 0x1B, 0xAE]) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: [0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29, 0xBC, 0x4B, 0xC6]) + AuthorityKeyIdentifier(keyIdentifier: [0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29, 0xBC, 0x4B, 0xC6]) Critical( - Certificate.Extensions.KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) + KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true) ) - Certificate.Extensions.ExtendedKeyUsage([.serverAuth, .clientAuth]) + ExtendedKeyUsage([.serverAuth, .clientAuth]) Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 0) + BasicConstraints.isCertificateAuthority(maxPathLength: 0) ) - Certificate.Extensions.AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) + AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]) // CRL Distribution Points Certificate.Extension( diff --git a/Tests/X509Tests/CertificateTests.swift b/Tests/X509Tests/CertificateTests.swift index 93a7202..165c966 100644 --- a/Tests/X509Tests/CertificateTests.swift +++ b/Tests/X509Tests/CertificateTests.swift @@ -72,7 +72,7 @@ final class CertificateTests: XCTestCase { } func testPrintingAIAExtension() throws { - let ext = Certificate.Extensions.AuthorityInformationAccess([ + let ext = AuthorityInformationAccess([ .init(method: .issuingCA, location: .uniformResourceIdentifier("https://example.com/ca")), .init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp")), .init(method: .init(.unknownType([1, 2, 3, 4])), location: .rfc822Name("mail@example.com")), @@ -85,7 +85,7 @@ final class CertificateTests: XCTestCase { } func testPrintingAKIExtension() throws { - var ext = Certificate.Extensions.AuthorityKeyIdentifier( + var ext = AuthorityKeyIdentifier( keyIdentifier: [10, 20, 30, 40], authorityCertIssuer: [.uniformResourceIdentifier("https://example.com/ca")], authorityCertSerialNumber: .init(bytes: [50, 60, 70, 80]) @@ -119,13 +119,13 @@ final class CertificateTests: XCTestCase { } func testPrintingSKIExtension() throws { - let ext = Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: [10, 20, 30, 40]) + let ext = SubjectKeyIdentifier(keyIdentifier: [10, 20, 30, 40]) let s = String(describing: ext) XCTAssertEqual(s, "a:14:1e:28") } func testPrintingKeyUsageExtension() { - var ext = Certificate.Extensions.KeyUsage() + var ext = KeyUsage() var s = String(describing: ext) XCTAssertEqual(s, "") @@ -183,7 +183,7 @@ final class CertificateTests: XCTestCase { func testPrintingSANFields() throws { // This is mostly redundant with general name, so we're only checking formatting. - let san = Certificate.Extensions.SubjectAlternativeNames([ + let san = SubjectAlternativeNames([ .dNSName("example.com"), .dNSName("example.org"), .iPAddress(ASN1OctetString(contentBytes: [127, 0, 0, 1])), @@ -196,7 +196,7 @@ final class CertificateTests: XCTestCase { } func testPrintingBasicConstraints() throws { - var ext = Certificate.Extensions.BasicConstraints.notCertificateAuthority + var ext = BasicConstraints.notCertificateAuthority XCTAssertEqual( String(describing: ext), "CA=FALSE" @@ -217,7 +217,7 @@ final class CertificateTests: XCTestCase { func testPrintingNameConstraints() throws { // This test is again mostly redundant with general name, so we're just testing the composition - var ext = Certificate.Extensions.NameConstraints( + var ext = NameConstraints( permittedSubtrees: [.dNSName("example.com"), .uniformResourceIdentifier("http://example.com")], excludedSubtrees: [.dNSName("example.org"), .rfc822Name("mail@example.com")] ) @@ -240,7 +240,7 @@ final class CertificateTests: XCTestCase { } func testPrintingEKU() throws { - let eku = Certificate.Extensions.ExtendedKeyUsage([ + let eku = ExtendedKeyUsage([ .any, .certificateTransparency, .timeStamping, diff --git a/Tests/X509Tests/OCSPPolicyVerifierTests.swift b/Tests/X509Tests/OCSPPolicyVerifierTests.swift index 45bb374..9252d69 100644 --- a/Tests/X509Tests/OCSPPolicyVerifierTests.swift +++ b/Tests/X509Tests/OCSPPolicyVerifierTests.swift @@ -91,8 +91,8 @@ final class OCSPVerifierPolicyTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: .init { if let ocspServer { - Certificate.Extensions.AuthorityInformationAccess([ - Certificate.Extensions.AuthorityInformationAccess.AccessDescription( + AuthorityInformationAccess([ + AuthorityInformationAccess.AccessDescription( method: .ocspServer, location: GeneralName.uniformResourceIdentifier(ocspServer)) ]) diff --git a/Tests/X509Tests/VerifierTests.swift b/Tests/X509Tests/VerifierTests.swift index b2c4ea9..f2062b7 100644 --- a/Tests/X509Tests/VerifierTests.swift +++ b/Tests/X509Tests/VerifierTests.swift @@ -37,10 +37,10 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -57,11 +57,11 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: try! ca2.extensions.subjectKeyIdentifier!.keyIdentifier) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: try! ca2.extensions.subjectKeyIdentifier!.keyIdentifier) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca2PrivateKey) ) @@ -79,10 +79,10 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1AlternativePrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1AlternativePrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -106,10 +106,10 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca2PrivateKey) ) @@ -126,11 +126,11 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -154,11 +154,11 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 1) + BasicConstraints.isCertificateAuthority(maxPathLength: 1) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: intermediate1PrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: intermediate1PrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -175,9 +175,9 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 1) + BasicConstraints.isCertificateAuthority(maxPathLength: 1) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) + KeyUsage(keyCertSign: true) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -194,11 +194,11 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 1) + BasicConstraints.isCertificateAuthority(maxPathLength: 1) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: try! ca2.extensions.subjectKeyIdentifier!.keyIdentifier) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: try! ca2.extensions.subjectKeyIdentifier!.keyIdentifier) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -223,10 +223,10 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA256, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.notCertificateAuthority + BasicConstraints.notCertificateAuthority ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: try! intermediate1.extensions.subjectKeyIdentifier!.keyIdentifier) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: try! intermediate1.extensions.subjectKeyIdentifier!.keyIdentifier) }, issuerPrivateKey: .init(intermediate1PrivateKey) ) @@ -318,14 +318,14 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA384, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier) // Note this is the SKI for the _wrong key_. - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) - Certificate.Extensions.SubjectAlternativeNames([.dNSName("example.com")]) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) + SubjectAlternativeNames([.dNSName("example.com")]) }, issuerPrivateKey: .init(ca1PrivateKey) ) @@ -342,9 +342,9 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA256, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) + KeyUsage(keyCertSign: true) }, issuerPrivateKey: .init(xKey) ) @@ -361,10 +361,10 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA256, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: 1) + BasicConstraints.isCertificateAuthority(maxPathLength: 1) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) }, issuerPrivateKey: .init(xKey) ) @@ -381,10 +381,10 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA256, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) }, issuerPrivateKey: .init(t1t2Key) ) @@ -401,11 +401,11 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA256, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.isCertificateAuthority(maxPathLength: nil) + BasicConstraints.isCertificateAuthority(maxPathLength: nil) ) - Certificate.Extensions.KeyUsage(keyCertSign: true) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) - Certificate.Extensions.SubjectAlternativeNames([.dNSName("foo.example.com")]) + KeyUsage(keyCertSign: true) + AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) + SubjectAlternativeNames([.dNSName("foo.example.com")]) }, issuerPrivateKey: .init(t1t2Key) ) @@ -422,9 +422,9 @@ final class VerifierTests: XCTestCase { signatureAlgorithm: .ecdsaWithSHA256, extensions: Certificate.Extensions { Critical( - Certificate.Extensions.BasicConstraints.notCertificateAuthority + BasicConstraints.notCertificateAuthority ) - Certificate.Extensions.AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) + AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))) }, issuerPrivateKey: .init(t3Key) )