diff --git a/Sources/X509/CertificateSerialNumber.swift b/Sources/X509/CertificateSerialNumber.swift index b51953f..2305eca 100644 --- a/Sources/X509/CertificateSerialNumber.swift +++ b/Sources/X509/CertificateSerialNumber.swift @@ -64,13 +64,7 @@ extension Certificate { @inlinable public init() { var rng = SystemRandomNumberGenerator() - var bytes = [UInt8]() - - while bytes.count < 20 { - bytes.appendLittleEndianBytes(rng.next()) - } - - self.bytes = bytes[..<20] + self.bytes = rng.bytes(count: 20) } } } @@ -84,15 +78,3 @@ extension Certificate.SerialNumber: CustomStringConvertible { return self.bytes.lazy.map { String($0, radix: 16) }.joined(separator: ":") } } - -extension Array where Element == UInt8 { - @inlinable - mutating func appendLittleEndianBytes(_ number: UInt64) { - let number = number.littleEndian - - for byte in 0..<(MemoryLayout.size) { - let shifted = number >> (byte * 8) - self.append(UInt8(truncatingIfNeeded: shifted)) - } - } -} diff --git a/Sources/X509/OCSP/OCSPCertID.swift b/Sources/X509/OCSP/OCSPCertID.swift index 37172e2..ec1be1a 100644 --- a/Sources/X509/OCSP/OCSPCertID.swift +++ b/Sources/X509/OCSP/OCSPCertID.swift @@ -29,11 +29,13 @@ import SwiftASN1 struct OCSPCertID: DERImplicitlyTaggable, Hashable { var hashAlgorithm: AlgorithmIdentifier + /// Hash of issuer's DN var issuerNameHash: ASN1OctetString + /// Hash of issuer's public key var issuerKeyHash: ASN1OctetString - var serialNumber: ArraySlice + var serialNumber: Certificate.SerialNumber static var defaultIdentifier: ASN1Identifier { .sequence @@ -42,7 +44,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { init(hashAlgorithm: AlgorithmIdentifier, issuerNameHash: ASN1OctetString, issuerKeyHash: ASN1OctetString, - serialNumber: ArraySlice) { + serialNumber: Certificate.SerialNumber) { self.hashAlgorithm = hashAlgorithm self.issuerNameHash = issuerNameHash self.issuerKeyHash = issuerKeyHash @@ -59,7 +61,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { return .init(hashAlgorithm: hashAlgorithm, issuerNameHash: issuerNameHash, issuerKeyHash: issuerKeyHash, - serialNumber: serialNumber) + serialNumber: .init(bytes: serialNumber)) } } @@ -68,7 +70,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { try self.hashAlgorithm.serialize(into: &coder) try self.issuerNameHash.serialize(into: &coder) try self.issuerKeyHash.serialize(into: &coder) - try self.serialNumber.serialize(into: &coder) + try self.serialNumber.bytes.serialize(into: &coder) } } } diff --git a/Sources/X509/OCSP/OCSPCertStatus.swift b/Sources/X509/OCSP/OCSPCertStatus.swift index 9739a8d..7bc2839 100644 --- a/Sources/X509/OCSP/OCSPCertStatus.swift +++ b/Sources/X509/OCSP/OCSPCertStatus.swift @@ -149,3 +149,21 @@ struct CRLReason: DERImplicitlyTaggable, Hashable, RawRepresentable { static let privilegeWithdrawn = CRLReason(rawValue: 9) static let aaCompromise = CRLReason(rawValue: 10) } + +extension CRLReason: CustomStringConvertible { + var description: String { + switch rawValue { + case 0: return "unspecified" + case 1: return "keyCompromise" + case 2: return "caCompromise" + case 3: return "affiliationChanged" + case 4: return "superseded" + case 5: return "cessationOfOperation" + case 6: return "certificateHold" + case 8: return "removeFromCRL" + case 9: return "privilegeWithdrawn" + case 10: return "aaCompromise" + default: return "unknown reason \(rawValue)" + } + } +} diff --git a/Sources/X509/OCSP/OCSPExtensionID.swift b/Sources/X509/OCSP/OCSPExtensionID.swift new file mode 100644 index 0000000..5e16736 --- /dev/null +++ b/Sources/X509/OCSP/OCSPExtensionID.swift @@ -0,0 +1,20 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +extension ASN1ObjectIdentifier { + /// OIDs that identify known OCSP extensions, + enum OCSPExtensionID {} +} diff --git a/Sources/X509/OCSP/OCSPNonce.swift b/Sources/X509/OCSP/OCSPNonce.swift new file mode 100644 index 0000000..46deff5 --- /dev/null +++ b/Sources/X509/OCSP/OCSPNonce.swift @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + + +/// ``OCSPNonce`` is defined in ASN.1 as: +/// ``` +/// Nonce ::= OCTET STRING(SIZE(1..32)) +/// ``` +/// RFC: https://www.rfc-editor.org/rfc/rfc8954.html +struct OCSPNonce: DERImplicitlyTaggable, Hashable, Sendable { + static var defaultIdentifier: ASN1Identifier { + ASN1OctetString.defaultIdentifier + } + var rawValue: ASN1OctetString + + init() { + var generator = SystemRandomNumberGenerator() + self.init(generator: &generator) + } + + init(generator: inout some RandomNumberGenerator) { + self.rawValue = .init(contentBytes: generator.bytes(count: 32)) + } + + init(_ ext: Certificate.Extension) throws { + guard ext.oid == .OCSPExtensionID.nonceIdentifier else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.OCSPExtensionID.nonceIdentifier), got \(ext.oid)") + } + + try self.init(derEncoded: ext.value) + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self.rawValue = try ASN1OctetString(derEncoded: rootNode, withIdentifier: identifier) + guard (1...32).contains(self.rawValue.bytes.count) else { + throw ASN1Error.unsupportedFieldLength + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try rawValue.serialize(into: &coder, withIdentifier: identifier) + } +} + +extension ASN1ObjectIdentifier.OCSPExtensionID { + static let nonceIdentifier: ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 48, 1, 2] +} + +extension Certificate.Extension { + /// Construct an opaque ``Certificate/Extension`` from this Key Usage extension. + /// + /// - Parameters: + /// - keyUsage: The extension to wrap + /// - critical: Whether this extension should have the critical bit set. + init(_ nonce: OCSPNonce, critical: Bool) throws { + var serializer = DER.Serializer() + try serializer.serialize(nonce) + self.init(oid: .OCSPExtensionID.nonceIdentifier, critical: critical, value: serializer.serializedBytes[...]) + } +} + +extension OCSPNonce: CertificateExtensionConvertible { + func makeCertificateExtension() throws -> Certificate.Extension { + try .init(self, critical: false) + } +} + + +extension Certificate.Extensions { + var ocspNonce: OCSPNonce? { + get throws { + try self[oid: .OCSPExtensionID.nonceIdentifier].map { try .init($0) } + } + } +} diff --git a/Sources/X509/OCSP/OCSPRequest.swift b/Sources/X509/OCSP/OCSPRequest.swift new file mode 100644 index 0000000..47ed13f --- /dev/null +++ b/Sources/X509/OCSP/OCSPRequest.swift @@ -0,0 +1,58 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPRequest`` is defined in ASN.1 as: +/// ``` +/// OCSPRequest ::= SEQUENCE { +/// tbsRequest TBSRequest, +/// optionalSignature [0] EXPLICIT Signature OPTIONAL } +/// ``` +struct OCSPRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var tbsRequest: OCSPTBSRequest + + var signature: OCSPSignature? + + init(tbsRequest: OCSPTBSRequest, signature: OCSPSignature? = nil) { + self.tbsRequest = tbsRequest + self.signature = signature + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let tbsRequest = try OCSPTBSRequest(derEncoded: &nodes) + let signature = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { + try OCSPSignature(derEncoded: $0) + } + return .init(tbsRequest: tbsRequest, signature: signature) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.tbsRequest) + if let signature = self.signature { + try coder.serialize(signature, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } + } + } +} + + + diff --git a/Sources/X509/OCSP/OCSPResponse.swift b/Sources/X509/OCSP/OCSPResponse.swift index 179b483..9f166ac 100644 --- a/Sources/X509/OCSP/OCSPResponse.swift +++ b/Sources/X509/OCSP/OCSPResponse.swift @@ -23,19 +23,17 @@ import SwiftASN1 /// /// ``` /// -struct OCSPResponse: DERImplicitlyTaggable, Hashable { +enum OCSPResponse: DERImplicitlyTaggable, Hashable { static var defaultIdentifier: ASN1Identifier { .sequence } - var responseStatus: OCSPResponseStatus - - var responseBytes: OCSPResponseBytes? - - init(responseStatus: OCSPResponseStatus, responseBytes: OCSPResponseBytes?) { - self.responseStatus = responseStatus - self.responseBytes = responseBytes - } + case successful(BasicOCSPResponse) + case malformedRequest + case internalError + case tryLater + case sigRequired + case unauthorized init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { self = try DER.sequence(rootNode, identifier: identifier) { nodes in @@ -43,17 +41,72 @@ struct OCSPResponse: DERImplicitlyTaggable, Hashable { let responseBytes = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in try OCSPResponseBytes(derEncoded: node) } - - return .init(responseStatus: responseStatus, responseBytes: responseBytes) + switch responseStatus { + case .successful: + guard let responseBytes, + responseBytes.responseType == .OCSP.basicResponse + else { + throw ASN1Error.invalidASN1Object + } + return .successful(try BasicOCSPResponse(derEncoded: responseBytes.response.bytes)) + case .malformedRequest: + return try .init(unsuccessfulStatus: .malformedRequest, responseBytes: responseBytes) + case .internalError: + return try .init(unsuccessfulStatus: .internalError, responseBytes: responseBytes) + case .tryLater: + return try .init(unsuccessfulStatus: .tryLater, responseBytes: responseBytes) + case .sigRequired: + return try .init(unsuccessfulStatus: .sigRequired, responseBytes: responseBytes) + case .unauthorized: + return try .init(unsuccessfulStatus: .unauthorized, responseBytes: responseBytes) + } } } + + private init(unsuccessfulStatus: OCSPResponse, responseBytes: OCSPResponseBytes?) throws { + if case .successful = unsuccessfulStatus { + preconditionFailure("this init is not allowed to be called with a successful response status") + } + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + self = unsuccessfulStatus + } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { try coder.appendConstructedNode(identifier: identifier) { coder in - try coder.serialize(self.responseStatus) - if let responseBytes = self.responseBytes { + try coder.serialize(OCSPResponseStatus(self)) + switch self { + case .successful(let basicResponse): + var serializer = DER.Serializer() + try serializer.serialize(basicResponse) + let responseBytes = OCSPResponseBytes(responseType: .OCSP.basicResponse, response: .init(contentBytes: serializer.serializedBytes[...])) try coder.serialize(responseBytes, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + + case .malformedRequest, + .internalError, + .tryLater, + .sigRequired, + .unauthorized: + break } } } } + +extension OCSPResponseStatus { + init(_ response: OCSPResponse) { + switch response { + case .successful: + self = .successful + case .malformedRequest: + self = .malformedRequest + case .internalError: + self = .internalError + case .tryLater: + self = .tryLater + case .sigRequired: + self = .sigRequired + case .unauthorized: + self = .unauthorized + } + } +} diff --git a/Sources/X509/OCSP/OCSPResponseData.swift b/Sources/X509/OCSP/OCSPResponseData.swift index d8cb61d..45bef92 100644 --- a/Sources/X509/OCSP/OCSPResponseData.swift +++ b/Sources/X509/OCSP/OCSPResponseData.swift @@ -32,7 +32,7 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { .sequence } - var version: Int + var version: OCSPVersion var responderID: ResponderID @@ -40,13 +40,13 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { var responses: [OCSPSingleResponse] - var responseExtensions: [Certificate.Extension]? + var responseExtensions: Certificate.Extensions? - init(version: Int = 0, + init(version: OCSPVersion = .v1, responderID: ResponderID, producedAt: GeneralizedTime, responses: [OCSPSingleResponse], - responseExtensions: [Certificate.Extension]?) { + responseExtensions: Certificate.Extensions? = nil) { self.version = version self.responderID = responderID self.producedAt = producedAt @@ -67,14 +67,14 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node) } - return .init(version: version, responderID: responderID, producedAt: producedAt, responses: responses, responseExtensions: responseExtensions) + return .init(version: .init(rawValue: version), responderID: responderID, producedAt: producedAt, responses: responses, responseExtensions: responseExtensions.map { .init($0) }) } } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { try coder.appendConstructedNode(identifier: identifier) { coder in - if self.version != 0 { - try coder.serialize(self.version, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + if self.version != .v1 { + try coder.serialize(self.version.rawValue, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) } try coder.serialize(self.responderID) diff --git a/Sources/X509/OCSP/OCSPResponseStatus.swift b/Sources/X509/OCSP/OCSPResponseStatus.swift index 6981ab6..444d9bb 100644 --- a/Sources/X509/OCSP/OCSPResponseStatus.swift +++ b/Sources/X509/OCSP/OCSPResponseStatus.swift @@ -61,25 +61,32 @@ enum OCSPResponseStatus: DERImplicitlyTaggable, Hashable { throw ASN1Error.invalidASN1Object } } + + var integerValue: Int { + switch self { + case .successful: return 0 + case .malformedRequest: return 1 + case .internalError: return 2 + case .tryLater: return 3 + case .sigRequired: return 5 + case .unauthorized: return 6 + } + } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - let integerValue: Int - - switch self { - case .successful: - integerValue = 0 - case .malformedRequest: - integerValue = 1 - case .internalError: - integerValue = 2 - case .tryLater: - integerValue = 3 - case .sigRequired: - integerValue = 5 - case .unauthorized: - integerValue = 6 - } - - try integerValue.serialize(into: &coder, withIdentifier: identifier) + try self.integerValue.serialize(into: &coder, withIdentifier: identifier) + } +} + +extension OCSPResponseStatus: CustomStringConvertible { + var description: String { + switch self { + case .successful: return "successful" + case .malformedRequest: return "malformedRequest" + case .internalError: return "internalError" + case .tryLater: return "tryLater" + case .sigRequired: return "sigRequired" + case .unauthorized: return "unauthorized" + } } } diff --git a/Sources/X509/OCSP/OCSPSignature.swift b/Sources/X509/OCSP/OCSPSignature.swift new file mode 100644 index 0000000..36ebe25 --- /dev/null +++ b/Sources/X509/OCSP/OCSPSignature.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPSignature`` is defined in ASN.1 as: +/// ``` +/// Signature ::= SEQUENCE { +/// signatureAlgorithm AlgorithmIdentifier, +/// signature BIT STRING, +/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } +/// ``` +struct OCSPSignature: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var algorithmIIdentifier: AlgorithmIdentifier + + var signature: ASN1BitString + + var certs: [Certificate]? + + init(algorithmIIdentifier: AlgorithmIdentifier, signature: ASN1BitString, certs: [Certificate]? = nil) { + self.algorithmIIdentifier = algorithmIIdentifier + self.signature = signature + self.certs = certs + } + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(derEncoded, identifier: identifier) { nodes in + let algorithmIdentifier = try AlgorithmIdentifier(derEncoded: &nodes) + let signature = try ASN1BitString(derEncoded: &nodes) + let certs = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + try DER.sequence(of: Certificate.self, identifier: .sequence, rootNode: node) + } + return .init(algorithmIIdentifier: algorithmIdentifier, signature: signature, certs: certs) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try self.algorithmIIdentifier.serialize(into: &coder) + try self.signature.serialize(into: &coder) + if let certs = self.certs { + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(certs) + } + } + } + } +} diff --git a/Sources/X509/OCSP/OCSPSingleRequest.swift b/Sources/X509/OCSP/OCSPSingleRequest.swift new file mode 100644 index 0000000..f14833e --- /dev/null +++ b/Sources/X509/OCSP/OCSPSingleRequest.swift @@ -0,0 +1,60 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPSingleRequest`` is defined in ASN.1 as: +/// ``` +/// Request ::= SEQUENCE { +/// reqCert CertID, +/// singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } +/// ``` +/// - note: originally named just `Request` in RFC 6960 but prefix `Single` added to avoid naming conflicts with ``OCSPRequest`` +struct OCSPSingleRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var certID: OCSPCertID + + var singleRequestExtensions: Certificate.Extensions? + + init(certID: OCSPCertID, singleRequestExtensions: Certificate.Extensions? = nil) { + self.certID = certID + self.singleRequestExtensions = singleRequestExtensions + } + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(derEncoded, identifier: identifier) { nodes in + let certID = try OCSPCertID(derEncoded: &nodes) + let singleRequestExtensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + Certificate.Extensions( + extensions: try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node) + ) + } + return .init(certID: certID, singleRequestExtensions: singleRequestExtensions) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try self.certID.serialize(into: &coder) + if let singleRequestExtensions = self.singleRequestExtensions { + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(singleRequestExtensions) + } + } + } + } +} diff --git a/Sources/X509/OCSP/OCSPSingleResponse.swift b/Sources/X509/OCSP/OCSPSingleResponse.swift index 5282230..4d329c4 100644 --- a/Sources/X509/OCSP/OCSPSingleResponse.swift +++ b/Sources/X509/OCSP/OCSPSingleResponse.swift @@ -44,7 +44,7 @@ struct OCSPSingleResponse: DERImplicitlyTaggable, Hashable { certStatus: OCSPCertStatus, thisUpdate: GeneralizedTime, nextUpdate: GeneralizedTime?, - extensions: [Certificate.Extension]?) { + extensions: [Certificate.Extension]? = nil) { self.certID = certID self.certStatus = certStatus self.thisUpdate = thisUpdate diff --git a/Sources/X509/OCSP/OCSPTBSRequest.swift b/Sources/X509/OCSP/OCSPTBSRequest.swift new file mode 100644 index 0000000..990322c --- /dev/null +++ b/Sources/X509/OCSP/OCSPTBSRequest.swift @@ -0,0 +1,83 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPTBSRequest`` is defined in ASN.1 as: +/// ``` +/// TBSRequest ::= SEQUENCE { +/// version [0] EXPLICIT Version DEFAULT v1, +/// requestorName [1] EXPLICIT GeneralName OPTIONAL, +/// requestList SEQUENCE OF Request, +/// requestExtensions [2] EXPLICIT Extensions OPTIONAL } +/// +/// Version ::= INTEGER { v1(0) } +/// ``` +struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var version: OCSPVersion + + var requestorName: GeneralName? + + var requestList: [OCSPSingleRequest] + + var requestExtensions: Certificate.Extensions? + + init(version: OCSPVersion, requestorName: GeneralName? = nil, requestList: [OCSPSingleRequest], requestExtensions: Certificate.Extensions? = nil) { + self.version = version + self.requestorName = requestorName + self.requestList = requestList + self.requestExtensions = requestExtensions + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let version = try DER.decodeDefaultExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific, defaultValue: Int(0)) + let requestorName = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { + try GeneralName(derEncoded: $0) + } + let requestList = try DER.sequence(of: OCSPSingleRequest.self, identifier: .sequence, nodes: &nodes) + let extensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific) { + try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: $0) + } + + return .init( + version: .init(rawValue: version), + requestorName: requestorName, + requestList: requestList, + requestExtensions: extensions.map { .init(extensions: $0) } + ) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + if self.version != .v1 { + try coder.serialize(self.version.rawValue, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } + if let requestorName = self.requestorName { + try coder.serialize(requestorName, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific) + } + try coder.serializeSequenceOf(requestList) + if let requestExtensions = self.requestExtensions { + try coder.serialize(explicitlyTaggedWithTagNumber: 2, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(requestExtensions._extensions) + } + } + } + } +} diff --git a/Sources/X509/OCSP/OCSPVersion.swift b/Sources/X509/OCSP/OCSPVersion.swift new file mode 100644 index 0000000..0b23b56 --- /dev/null +++ b/Sources/X509/OCSP/OCSPVersion.swift @@ -0,0 +1,44 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +struct OCSPVersion { + var rawValue: Int + + init(rawValue: Int) { + self.rawValue = rawValue + } + + static let v1 = Self(rawValue: 0) +} + +extension OCSPVersion: Hashable { } + +extension OCSPVersion: Sendable { } + +extension OCSPVersion: Comparable { + static func < (lhs: Self, rhs: Self) -> Bool { + lhs.rawValue < rhs.rawValue + } +} + +extension OCSPVersion: CustomStringConvertible { + var description: String { + switch self { + case .v1: + return "OCSPv1" + case let unknown: + return "OCSPv\(unknown.rawValue + 1)" + } + } +} diff --git a/Sources/X509/RandomNumberGenerator+bytes.swift b/Sources/X509/RandomNumberGenerator+bytes.swift new file mode 100644 index 0000000..c0f5ab7 --- /dev/null +++ b/Sources/X509/RandomNumberGenerator+bytes.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension RandomNumberGenerator { + @inlinable + internal mutating func bytes(count: Int) -> ArraySlice { + precondition(count >= 0) + var bytes = [UInt8]() + + while bytes.count < count { + bytes.appendLittleEndianBytes(self.next()) + } + + return bytes[...size) { + let shifted = number >> (byte * 8) + self.append(UInt8(truncatingIfNeeded: shifted)) + } + } +} diff --git a/Tests/X509Tests/OCSPTests.swift b/Tests/X509Tests/OCSPTests.swift index a92c752..add25b9 100644 --- a/Tests/X509Tests/OCSPTests.swift +++ b/Tests/X509Tests/OCSPTests.swift @@ -28,17 +28,43 @@ import XCTest @testable import SwiftASN1 +@testable import X509 final class OCSPTests: XCTestCase { - // TODO: Make these work. - #if false private func assertRoundTrips(_ value: ASN1Object) throws { var serializer = DER.Serializer() try serializer.serialize(value) let parsed = try ASN1Object(derEncoded: serializer.serializedBytes) XCTAssertEqual(parsed, value) } - + + func testRequestRoundtrip() throws { + let ocspRequest = OCSPRequest( + tbsRequest: OCSPTBSRequest( + version: .v1, + requestorName: GeneralName.dNSName("swift.org"), + requestList: [OCSPSingleRequest( + certID: OCSPCertID( + hashAlgorithm: .ecdsaWithSHA256, + issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]), + issuerKeyHash: .init(contentBytes: [10, 11, 12, 13, 14, 15, 16, 17, 18]), + serialNumber: .init(bytes: [20, 21, 22, 23, 24, 25, 26, 27, 28]) + ), + singleRequestExtensions: nil + )], + requestExtensions: nil), + signature: OCSPSignature( + algorithmIIdentifier: .p256PublicKey, + signature: .init(bytes: [31, 32, 33, 34, 35, 36, 37, 38]), + certs: nil + ) + ) + + try assertRoundTrips(ocspRequest) + } + + // TODO: Make these work. + #if false func testResponderIDByNameRoundTrips() throws { let id = ASN1.ResponderID.byName( ASN1.DistinguishedName(elements: [ diff --git a/docker/docker-compose.2204.58.yaml b/docker/docker-compose.2204.58.yaml new file mode 100644 index 0000000..fa74d0a --- /dev/null +++ b/docker/docker-compose.2204.58.yaml @@ -0,0 +1,19 @@ +version: "3" + +services: + + runtime-setup: + image: swift-certificates:22.04-5.8 + build: + args: + base_image: "swiftlang/swift:nightly-5.8-jammy" + + test: + image: swift-certificates:22.04-5.8 + environment: + - WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors + - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error + # - SANITIZER_ARG=--sanitize=thread # TSan broken still + + shell: + image: swift-certificates:22.04-5.8