From 4a67b473a1a94349caee0d79225485552f52eeaa Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Tue, 21 Mar 2023 16:51:10 +0000 Subject: [PATCH] Build OCSP Response certificate chain and verify signature (#43) OCSP responses are signed and we must validate the signature. This PR adds support for that. --- Package.swift | 6 + Sources/X509/Certificate.swift | 19 +- Sources/X509/OCSP/BasicOCSPResponse.swift | 36 +- Sources/X509/OCSP/OCSPCertID.swift | 16 +- Sources/X509/OCSP/OCSPPolicy.swift | 238 ++++++-- Sources/X509/OCSP/OCSPResponse.swift | 4 +- Sources/X509/OCSP/OCSPResponseBytes.swift | 5 +- .../X509/Verifier/RFC5280/ExpiryPolicy.swift | 1 + .../OCSP Test Resources/www.apple.com.der | Bin 0 -> 2133 bytes .../www.apple.com.intermediate.der | Bin 0 -> 1334 bytes ...w.apple.com.intermediate.ocsp-response.der | Bin 0 -> 471 bytes .../www.apple.com.ocsp-response.der | Bin 0 -> 1457 bytes .../www.apple.com.root.der | Bin 0 -> 969 bytes Tests/X509Tests/OCSPPolicyVerifierTests.swift | 512 ++++++++++++++---- 14 files changed, 638 insertions(+), 199 deletions(-) create mode 100644 Tests/X509Tests/OCSP Test Resources/www.apple.com.der create mode 100644 Tests/X509Tests/OCSP Test Resources/www.apple.com.intermediate.der create mode 100644 Tests/X509Tests/OCSP Test Resources/www.apple.com.intermediate.ocsp-response.der create mode 100644 Tests/X509Tests/OCSP Test Resources/www.apple.com.ocsp-response.der create mode 100644 Tests/X509Tests/OCSP Test Resources/www.apple.com.root.der diff --git a/Package.swift b/Package.swift index bdf81fb..c4d1548 100644 --- a/Package.swift +++ b/Package.swift @@ -46,6 +46,12 @@ let package = Package( "X509", .product(name: "SwiftASN1", package: "swift-asn1"), .product(name: "Crypto", package: "swift-crypto"), + ], resources: [ + .copy("OCSP Test Resources/www.apple.com.root.der"), + .copy("OCSP Test Resources/www.apple.com.intermediate.der"), + .copy("OCSP Test Resources/www.apple.com.der"), + .copy("OCSP Test Resources/www.apple.com.ocsp-response.der"), + .copy("OCSP Test Resources/www.apple.com.intermediate.ocsp-response.der"), ]), ] ) diff --git a/Sources/X509/Certificate.swift b/Sources/X509/Certificate.swift index bc83e0a..574c6e1 100644 --- a/Sources/X509/Certificate.swift +++ b/Sources/X509/Certificate.swift @@ -190,9 +190,9 @@ public struct Certificate { // TODO: enforce that signature algorithm and signature have the same algorithm. self.signatureAlgorithm = signatureAlgorithm self.signature = signature - self.tbsCertificateBytes = try DER.Serializer.serialized(element: self.tbsCertificate) - self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm)) - self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature)) + self.tbsCertificateBytes = try DER.Serializer.serialized(element: self.tbsCertificate)[...] + self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...] + self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...] } /// Construct a certificate from constituent parts, signed by an issuer key. @@ -241,11 +241,11 @@ public struct Certificate { // TODO: validate that signature algorithm is comoatible with the signature. self.signatureAlgorithm = signatureAlgorithm - let tbsCertificateBytes = try DER.Serializer.serialized(element: self.tbsCertificate) + let tbsCertificateBytes = try DER.Serializer.serialized(element: self.tbsCertificate)[...] self.signature = try issuerPrivateKey.sign(bytes: tbsCertificateBytes, signatureAlgorithm: signatureAlgorithm) self.tbsCertificateBytes = tbsCertificateBytes - self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm)) - self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature)) + self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...] + self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...] } @inlinable @@ -272,7 +272,7 @@ extension Certificate: Sendable { } extension Certificate: CustomStringConvertible { public var description: String { - return "TODO" + return "\(self.subject) - TODO" } } @@ -317,9 +317,10 @@ extension Certificate: DERImplicitlyTaggable { extension DER.Serializer { @inlinable - static func serialized(element: Element) throws -> ArraySlice { + static func serialized(element: Element) throws -> [UInt8] { var serializer = DER.Serializer() try serializer.serialize(element) - return serializer.serializedBytes[...] + return serializer.serializedBytes } + } diff --git a/Sources/X509/OCSP/BasicOCSPResponse.swift b/Sources/X509/OCSP/BasicOCSPResponse.swift index ddb2a95..36a9a66 100644 --- a/Sources/X509/OCSP/BasicOCSPResponse.swift +++ b/Sources/X509/OCSP/BasicOCSPResponse.swift @@ -36,7 +36,8 @@ import SwiftASN1 /// byName [1] Name, /// byKey [2] KeyHash } /// -/// KeyHash ::= OCTET STRING +/// KeyHash ::= OCTET STRING -- SHA-1 hash of responder's public key +/// (excluding the tag and length fields) /// /// SingleResponse ::= SEQUENCE { /// certID CertID, @@ -82,44 +83,57 @@ struct BasicOCSPResponse: DERImplicitlyTaggable, Hashable { } var responseData: OCSPResponseData + + var responseDataBytes: ArraySlice var signatureAlgorithm: AlgorithmIdentifier var signature: ASN1BitString - // Yup, you read this right: for the moment, we don't decode certs. We need a strategy for this. - //var certs: [] + var certs: [Certificate]? - init(responseData: OCSPResponseData, signatureAlgorithm: AlgorithmIdentifier, signature: ASN1BitString) { + init(responseData: OCSPResponseData, responseDataBytes: ArraySlice, signatureAlgorithm: AlgorithmIdentifier, signature: ASN1BitString, certs: [Certificate]?) { self.responseData = responseData + self.responseDataBytes = responseDataBytes self.signatureAlgorithm = signatureAlgorithm self.signature = signature + self.certs = certs } - init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { self = try DER.sequence(rootNode, identifier: identifier) { nodes in - let responseData = try OCSPResponseData(derEncoded: &nodes) + guard let responseDataNode = nodes.next() else { + throw ASN1Error.invalidASN1Object(reason: "missing OCSP response data") + } + let responseData = try OCSPResponseData(derEncoded: responseDataNode) let signatureAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) let signature = try ASN1BitString(derEncoded: &nodes) - // We need to consume the certificate nodes, but we don't _yet_ parse it. - _ = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in } + + let certs = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + try DER.sequence(of: Certificate.self, identifier: .sequence, rootNode: node) + } - return .init(responseData: responseData, signatureAlgorithm: signatureAlgorithm, signature: signature) + return .init(responseData: responseData, responseDataBytes: responseDataNode.encodedBytes, signatureAlgorithm: signatureAlgorithm, signature: signature, certs: certs) } } - + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { try coder.appendConstructedNode(identifier: identifier) { coder in - try coder.serialize(self.responseData) + coder.serializeRawBytes(self.responseDataBytes) try coder.serialize(self.signatureAlgorithm) try coder.serialize(self.signature) + if let certs { + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(certs) + } + } } } } enum ResponderID: DERParseable, DERSerializable, Hashable { case byName(DistinguishedName) + /// SHA-1 hash of responder's public key (excluding the tag and length fields) case byKey(ASN1OctetString) private static let nameIdentifier = ASN1Identifier(tagWithNumber: 1, tagClass: .contextSpecific) diff --git a/Sources/X509/OCSP/OCSPCertID.swift b/Sources/X509/OCSP/OCSPCertID.swift index ec1be1a..4fb8a8c 100644 --- a/Sources/X509/OCSP/OCSPCertID.swift +++ b/Sources/X509/OCSP/OCSPCertID.swift @@ -53,7 +53,21 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { init(derEncoded node: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { self = try DER.sequence(node, identifier: identifier) { nodes in - let hashAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) + let hashAlgorithm: AlgorithmIdentifier = try { + let hashAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes) + switch hashAlgorithm { + case .sha1, .sha1UsingNil: + return .sha1UsingNil + case .sha256, .sha256UsingNil: + return .sha256UsingNil + case .sha384, .sha384UsingNil: + return .sha384UsingNil + case .sha512, .sha1UsingNil: + return .sha512UsingNil + default: + return hashAlgorithm + } + }() let issuerNameHash = try ASN1OctetString(derEncoded: &nodes) let issuerKeyHash = try ASN1OctetString(derEncoded: &nodes) let serialNumber = try ArraySlice(derEncoded: &nodes) diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 8c4ce74..2095529 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -14,12 +14,7 @@ import SwiftASN1 import Crypto -#if canImport(Darwin) import Foundation -#else -// swift-corelibs-foundation hasn't marked anything Sendable yet https://github.com/apple/swift-corelibs-foundation/issues/4687 -@preconcurrency import Foundation -#endif // Swift CI has implicit concurrency disabled import _Concurrency @@ -42,6 +37,38 @@ extension ASN1ObjectIdentifier { static let sha1NoSign: Self = [1, 3, 14, 3, 2, 26] } +struct OCSPResponderSigningPolicy: VerifierPolicy { + /// direct issuer of the certificate for which we check the OCSP status for + var issuer: Certificate + mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + // The root of the chain is always guaranteed to be the issuer as the root certificate store only contains the issuer + guard chain.last == issuer else { + return .failsToMeetPolicy(reason: "OCSP response must be signed by the certificate issuer or a certificate that chains up to the issuer") + } + if chain.count == 1 { + // the leaf is the issuer which does not need to have the OCSP signing extended key usage + return .meetsPolicy + } + + let leaf = chain.leaf + + // RFC 6960 Section 4.2.2.2. Authorized Responders + // OCSP signing delegation SHALL be designated by the inclusion of + // id-kp-OCSPSigning in an extended key usage certificate extension + // included in the OCSP response signer's certificate. + guard let extendedKeyUsage: ExtendedKeyUsage = try? leaf.extensions.extendedKeyUsage else { + return .failsToMeetPolicy(reason: "OCSP response certificate has no extended key usages") + } + + guard extendedKeyUsage.usages.contains(.init(oid: .ExtendedKeyUsage.ocspSigning)) else { + return .failsToMeetPolicy(reason: "OCSP response certificate does not have OCSP signing extended key usage set") + } + + + return .meetsPolicy + } +} + enum OCSPRequestHashAlgorithm { case insecureSha1 // we can't yet enable sha256 by default but we want in the future @@ -83,7 +110,7 @@ enum OCSPRequestHashAlgorithm { } } -public struct OCSPVerifierPolicy: VerifierPolicy, Sendable { +public struct OCSPVerifierPolicy: VerifierPolicy { private var requester: Requester private var requestHashAlgorithm: OCSPRequestHashAlgorithm @@ -94,24 +121,25 @@ public struct OCSPVerifierPolicy: VerifierPolicy, Send private var maxDuration: TimeInterval /// the time used to decide if the request is relatively recent - /// if nil, the current system time is used - /// note that this is only used for testing purposes - private var now: Date? + private var validationTime: Date - public init(requester: Requester) { - self.init(requester: requester, now: nil) - } + /// If true, a nonce is generated per OCSP request and attached to the request. + /// If the response contains a nonce, it must match with the initially send nonce. + /// currently only set to false for testing + var nonceExtensionEnabled: Bool = true - internal init(requester: Requester, now: Date?) { + public init(requester: Requester, validationTime: Date) { self.requester = requester self.requestHashAlgorithm = .insecureSha1 self.maxDuration = 10 - self.now = now + self.validationTime = validationTime } - public func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { - await withTimeout(maxDuration) { - await chainMeetsPolicyRequirementsWithoutDeadline(chain: chain) + // this method currently doesn't need to be mutating. However, we want to reserve the right to change our mind + // in the future and therefore still declare this method as mutating in the public API. + public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + await withTimeout(maxDuration) { [self] in + await self.chainMeetsPolicyRequirementsWithoutDeadline(chain: chain) } } @@ -138,8 +166,6 @@ public struct OCSPVerifierPolicy: VerifierPolicy, Send return .meetsPolicy } - - private func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult { let authorityInformationAccess: AuthorityInformationAccess? @@ -177,11 +203,11 @@ public struct OCSPVerifierPolicy: VerifierPolicy, Send return .failsToMeetPolicy(reason: "failed to create OCSPCertID \(error)") } - return await self.queryAndVerifyCertificateStatus(for: certID, responderURI: responderURI) + return await self.queryAndVerifyCertificateStatus(for: certID, responderURI: responderURI, issuer: issuer) } - private func queryAndVerifyCertificateStatus(for certID: OCSPCertID, responderURI: String) async -> PolicyEvaluationResult { - let requestNonce = OCSPNonce() + private func queryAndVerifyCertificateStatus(for certID: OCSPCertID, responderURI: String, issuer: Certificate) async -> PolicyEvaluationResult { + let requestNonce = nonceExtensionEnabled ? OCSPNonce() : nil let requestBytes: [UInt8] do { let request = try OCSPRequest(certID: certID, nonce: requestNonce) @@ -206,46 +232,132 @@ public struct OCSPVerifierPolicy: VerifierPolicy, Send return .failsToMeetPolicy(reason: "OCSP deserialisation failed \(error)") } - return self.verifyResponse(response, requestedCertID: certID, requestNonce: requestNonce) + return await self.verifyResponse(response, requestedCertID: certID, requestNonce: requestNonce, issuer: issuer) } - private func verifyResponse(_ response: OCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce) -> PolicyEvaluationResult { + private func verifyResponse(_ response: OCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce?, issuer: Certificate) async -> PolicyEvaluationResult { switch response { case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: return .failsToMeetPolicy(reason: "OCSP request failed \(OCSPResponseStatus(response))") case .successful(let basicResponse): - guard basicResponse.responseData.version == .v1 else { - return .failsToMeetPolicy(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") - } - do { + return await self.verifySuccessfulResponse(basicResponse, requestedCertID: requestedCertID, requestNonce: requestNonce, issuer: issuer) + } + } + + private func verifySuccessfulResponse(_ basicResponse: BasicOCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce?, issuer: Certificate) async -> PolicyEvaluationResult { + guard basicResponse.responseData.version == .v1 else { + return .failsToMeetPolicy(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") + } + + do { + // if requestNonce is nil, `nonceExtensionEnabled` is set to false and we therefore skip nonce verification + if let requestNonce { // OCSP responders are allowed to not include the nonce, but if they do it needs to match if let responseNonce = try basicResponse.responseData.responseExtensions?.ocspNonce, requestNonce != responseNonce { return .failsToMeetPolicy(reason: "OCSP response nonce does not match request nonce") } - } catch { - return .failsToMeetPolicy(reason: "failed to decode nonce response \(error)") - } - guard let response = basicResponse.responseData.responses.first(where: { $0.certID == requestedCertID }) else { - return .failsToMeetPolicy(reason: "OCSP response does not include a response for the queried certificate \(requestedCertID) - responses: \(basicResponse.responseData.responses)") - } - - switch response.certStatus { - case .good: - switch response.verifyTime(now: self.now ?? Date()) { - case .meetsPolicy: - break - case .failsToMeetPolicy(let reason): - return .failsToMeetPolicy(reason: reason) - } - - // TODO: verify signature: rdar://104687979 - return .meetsPolicy - case .revoked(let info): - return .failsToMeetPolicy(reason: "revoked through OCSP, reason: \(info.revocationReason?.description ?? "nil")") - case .unknown: - return .failsToMeetPolicy(reason: "OCSP response returned as status unknown") + } else { + precondition(nonceExtensionEnabled == false) } + } catch { + return .failsToMeetPolicy(reason: "failed to decode nonce response \(error)") + } + guard let response = basicResponse.responseData.responses.first(where: { $0.certID == requestedCertID }) else { + return .failsToMeetPolicy(reason: "OCSP response does not include a response for the queried certificate \(requestedCertID) - responses: \(basicResponse.responseData.responses)") + } + + switch await self.validateResponseSignature(basicResponse, issuer: issuer) { + case .meetsPolicy: + break + case .failsToMeetPolicy(let reason): + return .failsToMeetPolicy(reason: reason) + } + + switch response.verifyTime(validationTime: self.validationTime) { + case .meetsPolicy: + break + case .failsToMeetPolicy(let reason): + return .failsToMeetPolicy(reason: reason) + } + + switch response.certStatus { + case .revoked(let info): + return .failsToMeetPolicy(reason: "revoked through OCSP, reason: \(info.revocationReason?.description ?? "nil")") + case .unknown: + return .failsToMeetPolicy(reason: "OCSP response returned as status unknown") + case .good: + return .meetsPolicy + } + } + + private func validateResponseSignature( + _ basicResponse: BasicOCSPResponse, + issuer: Certificate + ) async -> PolicyEvaluationResult { + let responderID = basicResponse.responseData.responderID + + let leafCertificate: Certificate? + if issuer.matches(responderID) { + leafCertificate = issuer + } else { + leafCertificate = basicResponse.certs?.first(where: { $0.matches(responderID) }) + } + + guard let leafCertificate else { + return .failsToMeetPolicy(reason: "could not find OCSP responder certificate for id \(responderID)") + } + + let signatureValidationResult = self.validateSignature( + certificate: leafCertificate, + tbsResponse: basicResponse.responseDataBytes, + signatureBytes: basicResponse.signature.bytes, + signatureAlgorithmIdentifier: basicResponse.signatureAlgorithm + ) + + switch signatureValidationResult { + case .meetsPolicy: + break + case .failsToMeetPolicy(let reason): + return .failsToMeetPolicy(reason: reason) + } + + var verifier = Verifier( + rootCertificates: CertificateStore([issuer]), + policy: PolicySet(policies: [ + OCSPResponderSigningPolicy(issuer: issuer), + RFC5280Policy(validationTime: validationTime), + ]) + ) + + let validationResult = await verifier.validate(leafCertificate: leafCertificate, intermediates: CertificateStore()) + + switch validationResult { + case .couldNotValidate(let failures): + return .failsToMeetPolicy(reason: "could not validate OCSP responder certificates \(failures)") + case .validCertificate: + return .meetsPolicy + } + } + + private func validateSignature( + certificate: Certificate, + tbsResponse: ArraySlice, + signatureBytes: ArraySlice, + signatureAlgorithmIdentifier: AlgorithmIdentifier + ) -> PolicyEvaluationResult { + let signatureAlgorithm = Certificate.SignatureAlgorithm(algorithmIdentifier: signatureAlgorithmIdentifier) + let signature: Certificate.Signature + do { + signature = try Certificate.Signature(signatureAlgorithm: signatureAlgorithm, signatureBytes: .init(bytes: signatureBytes)) + } catch { + return .failsToMeetPolicy(reason: "could not create signature for OCSP response \(error)") + } + + if certificate.publicKey.isValidSignature(signature, for: tbsResponse, signatureAlgorithm: signatureAlgorithm) { + return .meetsPolicy + } else { + return .failsToMeetPolicy(reason: "OCSP response signature is not valid") } } } @@ -262,21 +374,23 @@ extension OCSPCertID { } extension OCSPRequest { - init(certID: OCSPCertID, nonce: OCSPNonce) throws { + init(certID: OCSPCertID, nonce: OCSPNonce?) throws { self.init(tbsRequest: OCSPTBSRequest( version: .v1, requestList: [ OCSPSingleRequest(certID: certID) ], requestExtensions: try .init(builder: { - nonce + if let nonce { + nonce + } }) )) } } extension OCSPSingleResponse { - fileprivate func verifyTime(now: Date) -> PolicyEvaluationResult { + fileprivate func verifyTime(validationTime: Date) -> PolicyEvaluationResult { /// Clients MUST check for the existence of the nextUpdate field and MUST /// ensure the current time, expressed in GMT time as described in /// Section 2.2.4, falls between the thisUpdate and nextUpdate times. Ifhttps://www.rfc-editor.org/rfc/rfc5019#section-4 @@ -287,16 +401,16 @@ extension OCSPSingleResponse { } guard - let thisUpdate = Date(self.thisUpdate), + let thisUpdate = Date.init(self.thisUpdate), let nextUpdate = Date(nextUpdateGeneralizedTime) else { return .failsToMeetPolicy(reason: "could not convert time specified in certificate to a `Date`") } - guard thisUpdate <= now else { + guard thisUpdate <= validationTime else { return .failsToMeetPolicy(reason: "OCSP response `thisUpdate` (\(self.thisUpdate) is in the future but should be in the past") } - guard nextUpdate >= now else { + guard nextUpdate >= validationTime else { return .failsToMeetPolicy(reason: "OCSP response `nextUpdate` (\(nextUpdateGeneralizedTime) is in the past but should be in the future") } @@ -304,6 +418,18 @@ extension OCSPSingleResponse { } } +extension Certificate { + fileprivate func matches(_ responderID: ResponderID) -> Bool { + switch responderID { + case .byName(let subject): + return self.subject == subject + case .byKey(let responderPublicKeyHash): + let publicKeyHash = Insecure.SHA1.hash(data: SubjectPublicKeyInfo(self.publicKey).key.bytes) + return publicKeyHash == responderPublicKeyHash.bytes + } + } +} + /// Executes the given `operation` up to `maxDuration` seconds and cancels it if it exceeds the timeout. /// - Parameters: /// - maxDuration: max execution duration in seconds of `operation` diff --git a/Sources/X509/OCSP/OCSPResponse.swift b/Sources/X509/OCSP/OCSPResponse.swift index 2c948dd..26e2c82 100644 --- a/Sources/X509/OCSP/OCSPResponse.swift +++ b/Sources/X509/OCSP/OCSPResponse.swift @@ -78,9 +78,7 @@ enum OCSPResponse: DERImplicitlyTaggable, Hashable { 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[...])) + let responseBytes = try OCSPResponseBytes(encoding: basicResponse) try coder.serialize(responseBytes, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) case .malformedRequest, diff --git a/Sources/X509/OCSP/OCSPResponseBytes.swift b/Sources/X509/OCSP/OCSPResponseBytes.swift index d015ac2..f7f553e 100644 --- a/Sources/X509/OCSP/OCSPResponseBytes.swift +++ b/Sources/X509/OCSP/OCSPResponseBytes.swift @@ -70,9 +70,6 @@ extension BasicOCSPResponse { extension OCSPResponseBytes { init(encoding original: BasicOCSPResponse) throws { self.responseType = .OCSP.basicResponse - - var serializer = DER.Serializer() - try serializer.serialize(original) - self.response = ASN1OctetString(contentBytes: serializer.serializedBytes[...]) + self.response = ASN1OctetString(contentBytes: try DER.Serializer.serialized(element: original)[...]) } } diff --git a/Sources/X509/Verifier/RFC5280/ExpiryPolicy.swift b/Sources/X509/Verifier/RFC5280/ExpiryPolicy.swift index 6e7c144..160c004 100644 --- a/Sources/X509/Verifier/RFC5280/ExpiryPolicy.swift +++ b/Sources/X509/Verifier/RFC5280/ExpiryPolicy.swift @@ -11,6 +11,7 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// + import Foundation /// A sub-policy of the ``RFC5280Policy`` that polices expiry. diff --git a/Tests/X509Tests/OCSP Test Resources/www.apple.com.der b/Tests/X509Tests/OCSP Test Resources/www.apple.com.der new file mode 100644 index 0000000000000000000000000000000000000000..c79f1ccbdf2d619189f076422b7c18b747981c98 GIT binary patch literal 2133 zcmb7Fc~leU7N406VTVW%7nY0`6+yz6#2}04gUF(^tRj{o62cG$vXKO6z_J7gMU>-G zK_Ij!eQuC~eNd}dELG83mjkZ~m8Xc>0#bce&Qn1wZwAo^=k%ZV$DA|w&i&orz4v#& zZ-CY$5@?OR>uCs#APjSdnnzbEeUFN7SS<+N-x>`p>87r_5Zwz)7&bS8KqSW;n9^x6 zD4mJKM01#69%Yy@&HNP#365=)iP#)>;6^!VOy@Vwh|DAjA;JQ;V9~fT3s+)M(f*jg zALC-~STF}TEwJQr!D@~-htCH9#E~Ws@F{b(H{UxB6#kpz2<)kh)=b+7C6Ogm<5;*- zER+#BLNy_mO;=&=Mu$;YyJjr{)22(a2aD*loCwoQAe0a(a;1zAa^?YRDxne6L;$>i zC*Pafdi&dz2FsR^=0aw*WlOJ~m=HiBqc*cu}JW{4JsAp@WLv@L!6 zwULsSTW%=`2YhovsQ9~QZ^E|&csJNdQjQvOM) zYC~B+cTv5K{T_PbC%q}-LC(;T3Byw;0wBPmtoP7`z^=eHBBoJrsQGw^TU_Vi(lYd6j@6ahAct;3u8NV7 zF$|+JAOYOBHb8XCQ`KsPkB5hdR9E#sK|F*CJWHii3AthpI~i93&vzJD=Q@Lti&TnP z5XuBR_gP550c)w^=AnGR(=z5r&KAkEbC*ENAf)8#%&LNv--g0ts1`OQ4I^MoHxd_G zz%VErr<*3~LSWr%2|`+Nl7a5`$x84h;bdJsNuzXDw91coVrUO2rdZN9m|6tlm-QZKx7GYFKD3bqZ690rqH(1t#ykhPfzU? z4OdO2{l4s{1Ec2WIuI=Bd{xbtqM}QUhkte-WF}ze=#wtzo4B?7lffsTRI8;V?~~B) zPGw$CJTn+Tuo?$HPie5u+uow=D}pZMmgO9K{nHF@;yYgKZ>)lj?KySkFM^yCSC_CB zHih22&@<#K{Y5>rH+THo&&kSa7*k(8*Ie5@k+sb4_N|SU_SrhO`75Cf&8t58hjBMz z2W3M!++CadPPu=BJ@UF2-33jh#HNW;r(=)Hv|NcS$j^aj6TTc zg~0dM>IXY_G$_jw#NMgf_j)@&pjLYS9etM^M3)5P~E4SS^Y2kdOM7MhMU)r5>8h%5ppUCG- z4m}DU=MPT|)$j!=!}mKM2SyGAh{p#XGFM1Q;){u}?}YbX4U)4YLTMQkfb|fxEH9(N;h!W4)mk%KY#ANeu>`D9OW7Q%5dFvGS{Z>S#xdPgc3ct#i{*^jPd^D zB_A7}f`0p0ML9ELlhvwAX^$hWTCTY3HAQ@r&FHK+&p5ripX03U$_#KRE_DnFkA3D< YY_H$n?>dHjDK=Of%ayhyCDV2P1y`>CY5)KL literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/OCSP Test Resources/www.apple.com.intermediate.der b/Tests/X509Tests/OCSP Test Resources/www.apple.com.intermediate.der new file mode 100644 index 0000000000000000000000000000000000000000..03de1b4d5215144b4aaecad68de4a322ebf28644 GIT binary patch literal 1334 zcmXqLVl^^oVv$V(_(zpKZfCvL#HcqWJkGAi;jEvl@3k4t8HrgLghiGpWdvZ17bI7paVSfISTTrUMEl?;^9 zOU}`5W#@bq@2uT zkS)QfMP;c)3PHh+K)V!-6m%8b4Go$Ym5}|+$jZRn#K_M86z5`UVq|1^#PE0N{rH_0 zg`Tf>O}=s1*Z5A1$g2YVgRg?EPtOZH5V9$SZP|3gC*m!qD)iG2U+R4LMWXQ3Tgl^j zOo!UF)Nj?-!S5PhtKQywA!~r1_}Z?fpGppE>B9`oI{VnDkNa zM4ZoIB?~_VR4UEI&-R*`onbM3lcUpnquHqK|3>5W>tQC%x} zb+qu0M{o46^YeWOn#_K32~SA!xpztN-ToKyRQaPh52<`(Sn(^LHR2wdtkhnIwv4|s zw@x=xt2X66QCqpm?dRNE2X8R0WWK?lWLK|$i|yuRE01)R*-4*l60chLhOZ0ysy!$5 zITJG@1LNW*#+Seld1@dF3|d(}7BLo)fY8;>3)ipo(2hE|sJ)ZrNfqCzTL$tVX=N4( z1F;5?jdq7KnSbneXS^~)O^So*eR7KSVFNyp0)9ru|12!P^w$P4PnAW?K!lA$n~jl` zm7SRp&SEkU0x1^;Dd#X?15!+k3g93WJJym zz#;&c9T*vw#pMKSOO4U?vtReB;KiM{=GFcW{t4H;^h;vi`nN=InX~MnH#hlBSW9Ml zNll8Dsc7(U{&wiy>)2+_OPZF?o|K1nO%OV*meO>5VzBqW^|IjHi zVV6&pq-f@SS1~VJJ9n#{=58IQ(B$GdZrKqgWj+6*mnX|cI=_`ayz$PH`5)bPKXudI zWdHo+x957i-7EEYzu&Rg>Aopa@#po&>2u;8?p|h++Y#|aM&kI(vpYq-^#6qIOtbnD V^5fYo<|?}?9;U65F_r?=#Q?UH(Y^ox literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/OCSP Test Resources/www.apple.com.intermediate.ocsp-response.der b/Tests/X509Tests/OCSP Test Resources/www.apple.com.intermediate.ocsp-response.der new file mode 100644 index 0000000000000000000000000000000000000000..870f93ec4b75390a1b5e6c0690ea8383d52845aa GIT binary patch literal 471 zcmXqLV!X`7$grS^@r*$e;|VrSZ8k<$R(1nMMwTYVoj{?j295I;iLr=mv^$*1{A0g6 zR7#SNF8yXv0m>3!wMHv(u6dHIMaI&##^D#3?u`;lT++QX1 zSYson@5qwPB{BO^B}19KB2BSS}*?x&zuMyW;d29FobIq80-jb({N$YnN%Yo8{c&YiX7 z+^sHysl_Kv6R&^xD}U}i?{!b_ul*$}P36}J>q@=2_;lg?`ycI1CwSR-7Rzeif9HGM z_KN82gVh^6|9|qFynH$no6WsF!gV^@i|;bX)s@KaJv-f_=>^xkcvDHA-P*dgcCYsx z+gE@4pXxgewhxb|ng7@{h0j0j^ot0#AGsgqygL^d^uCWv@80H&+()|~9XF_AuRS9+ z;nSr0E+VzO*zq?vHwJQ~*y?z#jkr literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/OCSP Test Resources/www.apple.com.ocsp-response.der b/Tests/X509Tests/OCSP Test Resources/www.apple.com.ocsp-response.der new file mode 100644 index 0000000000000000000000000000000000000000..49e5e58b4ab0ecf16c8d1ce55c1c20db0557beea GIT binary patch literal 1457 zcmXqLVqMF{$grS^b(ujE>moKzZ8k<$R(1nMMwTYl$v~lggT^_F#8^b;CI7f7bE|pN z;e_-gF>BjE>7&`_B>0UCjEoJ84NVPAjZICAq6`WR@(tV#*x6XM`IwocSVYb}II;cz zd%cRziVB%sfin-49r*W~MI<0}we!ODD?PNM4lZi%WO-7>cj^|C0JqGnSEr^~FHb+u zC+u@i^mr;?<{9>syK=Y`H}2 z)%#;VvIaNZ)j7cIryS4`bMo5ZYA37t{cnx0KT*kNv~Kr0TJ&Bd^i|2)R>{tjf#)?} zUUv%O|Ejd$L+?eClx_bm36ySe30?T9P$l~KoU-+twhVWEo^WmmnRa~IB)3y*)Q)KC z9@I(7Dn5Qx=eu)F>yz>;$0xFWOTYQmLg~=+qOiCLt6TS0t4qB6D9-gFdw*k%P3OG@ zP0Tk8nwYNu@dbk>rX35InHZUX0et1Jg82h$&p?OGIaj8AYC{V;gFr)W15P&PP!={} zrqEzRVFN)BhfA2tv7jI)RlzeaS3{5~>L(3?GTtiO-cZh)w#2BdH?;ISU z5R_V6ke`KZaV{oM!ddJ8e|4DK!$M9) z3DM~swQK+UQZZjTfuXdV(Ikg)!ks7A?rcf@Rm=15kKD=AFY9ccG|!0U`!C$)qOyna zb!^g?F5S{KZh4c~ByK3Zj^VlGq$_c?dArHo8-}|Ne9O4_=xy=)n#Ho8l~+mj$6N2u zE=fyY{434wx5|ZwLi)M2+xH7^$hhioS$nna+<3LQk8?6FZfQ23`X}LOl!k5h%7T@D zw)3j*;0`R0|6_Rnw7&m%6(diVYlS=PHZ*KK2!*!20uiE|7U(4Y+ z6EhV{3NtePXJIm6FpvlFlvyMU#2T<>Uju$b(ZR~X#L8eG4AP;> z!ehY2#sMi*m^lq(L4tfNILZ?PK9Dp&$W9h!CiVv8xPs;FGiu_6HJpzUE6T3>Kjc35 zEyg3eaNP>Gx(LNjhP!m)?uytrY_`$5wnQqYG*ygCSe$8Rw@vgE=J|p*{{>kWYJ|IS zpU|Aw;P&YD?(a{JZuxfUGLyw0wN=|+W-UpSQ!i}kyE!8&X@W>K|+7wg15F;OG0?38@)U@|Gxz10RS7pEKmRd literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/OCSP Test Resources/www.apple.com.root.der b/Tests/X509Tests/OCSP Test Resources/www.apple.com.root.der new file mode 100644 index 0000000000000000000000000000000000000000..dae0196507d9166bbf9de6ed93ed5bd91d2a6f7c GIT binary patch literal 969 zcmXqLVm@ln#I$w+GZP~dlK|727_}^JhuQtym7mtRsg@h?vTHrk&& ztLnL}Q0ws3DJJQQxMViOXD)Ntcx3yg{tGjftaOaDx_oEKHJjTd7E8R&_^LL2_gWe( zWby8^XKvxdy5w!Em&G4m((=PUDRAG9qi=3oOnS`rlw%^#5e>)C->0KGMe7P*nC|y2 z;KS3U1MC5c*hY*|CU8utq&? zd&l;QPp7z6SghtsIkZ15c52JPg{pGxu~Grt3PNWbcjs{jTI}#X&BV;ez_>WsAklyi z7{#*ujEw(TSb)i@&43@o7Y6ZJ4VZzHfh)yU1V#fRgNzj0^gGw*%(v-CW8(-{yshZ|Lo0pNehH&82Z8W| zU7xFN3a0j%{+jp4b?dyFK8D^qCcbdi>Dyd!?)Ky0%ED_;6{j%X3T>aIlJc!9?aaM7 z=4V%!Y|Nakd}3aOl6Haf<4||QM9KFNM_cv%48AQe6jMI&{86fy@#+0i(hF>VoQmr< z>`vh5)a7A|3EF<-C)bRNqVe;E_SKjrTkLgNQvXCvo9oE*Ox~A0j}8cg?>JE=G%@s( zN9K(^T1?UWE>{!`Z-3cUpcXqJVcs5ZaZdd$r{$b8PO_^XycF~OmEz6}p*c2l_Rss% i5HmaZ>>Kx0s_N+r%s(?U)rMSO`QxRY@Z$0p@?HQubYDLJ literal 0 HcmV?d00001 diff --git a/Tests/X509Tests/OCSPPolicyVerifierTests.swift b/Tests/X509Tests/OCSPPolicyVerifierTests.swift index 0347ae6..e9613dc 100644 --- a/Tests/X509Tests/OCSPPolicyVerifierTests.swift +++ b/Tests/X509Tests/OCSPPolicyVerifierTests.swift @@ -59,41 +59,64 @@ actor TestRequester: OCSPRequester { } } -extension TestRequester { +extension OCSPRequester { + func assertNoThrow( + file: StaticString = #file, + line: UInt = #line + ) -> some OCSPRequester { + AssertNoThrowRequester(wrapped: self, file: file, line: line) + } +} + +extension OCSPRequester where Self == TestRequester { /// makes sure that the given ``query`` closure does **not** throw by failing the test if it does throw. static func noThrow( query: @escaping @Sendable (OCSPRequest, String) async throws -> OCSPResponse, file: StaticString = #file, line: UInt = #line - ) -> Self { - .init(query: { request, uri in - do { - return try await query(request, uri) - } catch { - XCTFail("test query closure throw error \(error)", file: file, line: line) - throw error - } - }, file: file, line: line) + ) -> some OCSPRequester { + TestRequester(query: query).assertNoThrow(file: file, line: line) + } +} + +struct AssertNoThrowRequester: OCSPRequester { + var wrapped: Wrapped + var file: StaticString + var line: UInt + func query(request: [UInt8], uri: String) async throws -> [UInt8] { + do { + return try await wrapped.query(request: request, uri: uri) + } catch { + XCTFail("test query closure throw error \(error)", file: file, line: line) + throw error + } } } final class OCSPVerifierPolicyTests: XCTestCase { - private static let privateKey = P384.Signing.PrivateKey() - private static func certificate( - subject: DistinguishedName, - issuer: DistinguishedName, - ocspServer: String? = nil - ) -> Certificate { + private static let ca1Name = try! DistinguishedName { + CountryName("US") + OrganizationName("Apple") + CommonName("Swift Certificate Test CA 1") + } + private static let ca1PrivateKey = P384.Signing.PrivateKey() + + private static func ca(ocspServer: String? = nil) -> Certificate { try! Certificate( version: .v3, serialNumber: .init(), - publicKey: .init(privateKey.publicKey), + publicKey: .init(ca1PrivateKey.publicKey), notValidBefore: Date() - .days(365), notValidAfter: Date() + .days(3650), issuer: ca1Name, subject: ca1Name, signatureAlgorithm: .ecdsaWithSHA384, - extensions: .init { + extensions: Certificate.Extensions { + Critical( + BasicConstraints.isCertificateAuthority(maxPathLength: nil) + ) + KeyUsage(keyCertSign: true) + SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))) if let ocspServer { AuthorityInformationAccess([ AuthorityInformationAccess.AccessDescription( @@ -102,15 +125,49 @@ final class OCSPVerifierPolicyTests: XCTestCase { ]) } }, - issuerPrivateKey: .init(privateKey) + issuerPrivateKey: .init(ca1PrivateKey) ) } - private static let ca1Name = try! DistinguishedName { - CountryName("US") - OrganizationName("Apple") - CommonName("Swift Certificate Test CA 1") + private static let ca1: Certificate = ca() + + fileprivate static let intermediatePrivateKey = P384.Signing.PrivateKey() + private static let leafPrivateKey = P384.Signing.PrivateKey() + private static func certificate( + subject: DistinguishedName, + publicKey: P384.Signing.PublicKey, + issuer: DistinguishedName, + issuerPrivateKey: P384.Signing.PrivateKey, + isIntermediate: Bool, + ocspServer: String? = nil + ) -> Certificate { + try! Certificate( + version: .v3, + serialNumber: .init(), + publicKey: .init(publicKey), + notValidBefore: Date() - .days(365), + notValidAfter: Date() + .days(3650), + issuer: issuer, + subject: subject, + signatureAlgorithm: .ecdsaWithSHA384, + extensions: .init { + if isIntermediate { + Critical( + BasicConstraints.isCertificateAuthority(maxPathLength: 0) + ) + } + if let ocspServer { + AuthorityInformationAccess([ + AuthorityInformationAccess.AccessDescription( + method: .ocspServer, + location: GeneralName.uniformResourceIdentifier(ocspServer)) + ]) + } + }, + issuerPrivateKey: .init(issuerPrivateKey) + ) } - private static let intermediate1Name = try! DistinguishedName { + + fileprivate static let intermediate1Name = try! DistinguishedName { CountryName("US") OrganizationName("Apple") CommonName("Swift Certificate Test Intermediate CA 1") @@ -121,27 +178,70 @@ final class OCSPVerifierPolicyTests: XCTestCase { CommonName("localhost") } + private static func intermediate(ocspServer: String? = nil) -> Certificate { + certificate( + subject: intermediate1Name, + publicKey: intermediatePrivateKey.publicKey, + issuer: ca1Name, + issuerPrivateKey: ca1PrivateKey, + isIntermediate: true, + ocspServer: ocspServer + ) + } + + private static func leaf(ocspServer: String? = nil) -> Certificate { + certificate( + subject: localhostLeafName, + publicKey: leafPrivateKey.publicKey, + issuer: intermediate1Name, + issuerPrivateKey: intermediatePrivateKey, + isIntermediate: false, + ocspServer: ocspServer + ) + } + + private static let chainWithSingleCertWithOCSP = [ + leaf(ocspServer: responderURI), + intermediate(), + ] + private static let responderURI = "http://ocsp.apple.com/path" fileprivate static let responderId = ResponderID.byName(try! DistinguishedName { CommonName("Swift OCSP Test Responder") }) - private static let chainWithSingleCertWithOCSP = [ - certificate(subject: localhostLeafName, issuer: intermediate1Name, ocspServer: responderURI), - certificate(subject: intermediate1Name, issuer: intermediate1Name), - ] - private let now = Date() + private static let responderIntermediate1Name = try! DistinguishedName { + CountryName("US") + OrganizationName("Apple") + CommonName("Swift Certificate Test Responder Intermediate 1") + } + private static let responderIntermediate1PrivateKey = P384.Signing.PrivateKey() + private static let invalidResponderIntermediate1 = try! Certificate( + version: .v3, + serialNumber: .init(), + publicKey: .init(responderIntermediate1PrivateKey.publicKey), + notValidBefore: Date() - .days(365), + notValidAfter: Date() + .days(3650), + issuer: ca1.subject, + subject: responderIntermediate1Name, + signatureAlgorithm: .ecdsaWithSHA384, + extensions: Certificate.Extensions {}, + issuerPrivateKey: .init(ca1PrivateKey) + ) + + private let validationTime = Date() func assertChainMeetsPolicy( chain: [Certificate], - requester: TestRequester, + requester: some OCSPRequester, expectedQueryCount: Int = 1, + validationTime: Date? = nil, file: StaticString = #file, line: UInt = #line ) async { - let policy = OCSPVerifierPolicy( + var policy = OCSPVerifierPolicy( requester: requester, - now: self.now + validationTime: validationTime ?? self.validationTime ) let result = await policy.chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain(chain)) guard case .meetsPolicy = result else { @@ -149,8 +249,10 @@ final class OCSPVerifierPolicyTests: XCTestCase { printChainForDebugging(chain) return } - let queryCount = await requester.queryCount - XCTAssertEqual(queryCount, expectedQueryCount, "unexpected requester query count", file: file, line: line) + if let testRequest = requester as? TestRequester { + let queryCount = await testRequest.queryCount + XCTAssertEqual(queryCount, expectedQueryCount, "unexpected requester query count", file: file, line: line) + } } func printChainForDebugging(_ chain: [Certificate]) { @@ -167,15 +269,15 @@ final class OCSPVerifierPolicyTests: XCTestCase { func assertChainFailsToMeetPolicy( chain: [Certificate], - requester: TestRequester, + requester: some OCSPRequester, expectedQueryCount: Int = 1, expectedReason: String? = nil, file: StaticString = #file, line: UInt = #line ) async { - let policy = OCSPVerifierPolicy( + var policy = OCSPVerifierPolicy( requester: requester, - now: self.now + validationTime: self.validationTime ) let result = await policy.chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain(chain)) guard case .failsToMeetPolicy(let actualReason) = result else { @@ -186,103 +288,193 @@ final class OCSPVerifierPolicyTests: XCTestCase { if let expectedReason { XCTAssertEqual(actualReason, expectedReason, "unexpected policy failure reason", file: file, line: line) } - let actualQueryCount = await requester.queryCount - XCTAssertEqual(actualQueryCount, expectedQueryCount, "unexpected requester query count", file: file, line: line) + if let testRequest = requester as? TestRequester { + let actualQueryCount = await testRequest.queryCount + XCTAssertEqual(actualQueryCount, expectedQueryCount, "unexpected requester query count", file: file, line: line) + } } func testSingleCertWithOCSP() async { - let now = self.now + let now = self.validationTime await self.assertChainMeetsPolicy( chain: Self.chainWithSingleCertWithOCSP, - requester: .noThrow { request, uri -> OCSPResponse in + requester: TestRequester.noThrow { request, uri -> OCSPResponse in XCTAssertEqual(uri, Self.responderURI) XCTAssertNil(request.signature) let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) XCTAssertEqual(request.tbsRequest.requestList.count, 1) let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) - return .successful(.signed(responses: [OCSPSingleResponse( - certID: singleRequest.certID, - certStatus: .good, - thisUpdate: try .init(now - .days(1)), - nextUpdate: try .init(now + .days(1)) - )], responseExtensions: { nonce })) + return .successful(try .signed( + responses: [OCSPSingleResponse( + certID: singleRequest.certID, + certStatus: .good, + thisUpdate: try .init(now - .days(1)), + nextUpdate: try .init(now + .days(1)) + )]) { + nonce + } + ) } ) } func testWrongNonce() async { - let now = self.now + let now = self.validationTime await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, - requester: .noThrow { request, uri -> OCSPResponse in + requester: TestRequester.noThrow { request, uri -> OCSPResponse in XCTAssertEqual(uri, Self.responderURI) XCTAssertNil(request.signature) XCTAssertNotNil(try request.tbsRequest.requestExtensions?.ocspNonce) XCTAssertEqual(request.tbsRequest.requestList.count, 1) let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) - return .successful(.signed(responses: [OCSPSingleResponse( + return .successful(try .signed( + responses: [OCSPSingleResponse( certID: singleRequest.certID, certStatus: .good, thisUpdate: try .init(now - .days(1)), nextUpdate: try .init(now + .days(1)) - )], responseExtensions: { OCSPNonce() })) + )]) { + OCSPNonce() + } + ) } ) } func testRevokedCert() async { - let now = self.now + let now = self.validationTime await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, - requester: .noThrow { request, uri -> OCSPResponse in + requester: TestRequester.noThrow { request, uri -> OCSPResponse in XCTAssertEqual(uri, Self.responderURI) XCTAssertNil(request.signature) let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) XCTAssertEqual(request.tbsRequest.requestList.count, 1) let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) - return .successful(.signed(responses: [OCSPSingleResponse( - certID: singleRequest.certID, - certStatus: .revoked(.init( - revocationTime: try .init(now), - revocationReason: .unspecified - )), - thisUpdate: try .init(now - .days(1)), - nextUpdate: try .init(now + .days(1)) - )], responseExtensions: { nonce })) + return .successful(try .signed( + responses: [OCSPSingleResponse( + certID: singleRequest.certID, + certStatus: .revoked(.init( + revocationTime: try .init(now), + revocationReason: .unspecified + )), + thisUpdate: try .init(now - .days(1)), + nextUpdate: try .init(now + .days(1)) + )]) { + nonce + } + ) + } + ) + } + + func testInvalidResponderCertChain() async { + let now = self.validationTime + await self.assertChainFailsToMeetPolicy( + chain: Self.chainWithSingleCertWithOCSP, + requester: TestRequester.noThrow { request, uri -> OCSPResponse in + XCTAssertEqual(uri, Self.responderURI) + XCTAssertNil(request.signature) + let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) + XCTAssertEqual(request.tbsRequest.requestList.count, 1) + let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) + return .successful(try .signed( + responderID: .byName(Self.invalidResponderIntermediate1.subject), + responses: [OCSPSingleResponse( + certID: singleRequest.certID, + certStatus: .good, + thisUpdate: try .init(now - .days(1)), + nextUpdate: try .init(now + .days(1)) + )], + privateKey: Self.responderIntermediate1PrivateKey, + certs: [Self.invalidResponderIntermediate1]) { + nonce + } + ) + } + ) + } + + func testResponderSignatureAlgorithmIdentifierMismatch() async { + let now = self.validationTime + await self.assertChainFailsToMeetPolicy( + chain: Self.chainWithSingleCertWithOCSP, + requester: TestRequester.noThrow { request, uri -> OCSPResponse in + XCTAssertEqual(uri, Self.responderURI) + XCTAssertNil(request.signature) + let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) + XCTAssertEqual(request.tbsRequest.requestList.count, 1) + let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) + + let responseData = OCSPResponseData( + version: .v1, + responderID: Self.responderId, + producedAt: try .init(Date()), + responses: [OCSPSingleResponse( + certID: singleRequest.certID, + certStatus: .good, + thisUpdate: try .init(now - .days(1)), + nextUpdate: try .init(now + .days(1)) + )], + responseExtensions: try .init { + nonce + } + ) + + var serializer = DER.Serializer() + try serializer.serialize(responseData) + let tbsCertificateBytes = serializer.serializedBytes[...] + + let digest = SHA384.hash(data: tbsCertificateBytes) + let signature = try Self.intermediatePrivateKey.signature(for: digest) + + let response = try BasicOCSPResponse( + responseData: responseData, + // signature digest was creating using SHA384 but we specify the wrong identifier SHA256 + signatureAlgorithm: .ecdsaWithSHA256, + signature: .init(bytes: Array(signature.derRepresentation)[...]), + certs: [] + ) + return .successful(response) } ) } func testResponseDoesNotIncludeResponseForRequestedCert() async { - let now = self.now + let now = self.validationTime await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, - requester: .noThrow { request, uri -> OCSPResponse in + requester: TestRequester.noThrow { request, uri -> OCSPResponse in XCTAssertEqual(uri, Self.responderURI) XCTAssertNil(request.signature) let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) XCTAssertEqual(request.tbsRequest.requestList.count, 1) - return .successful(.signed(responses: [OCSPSingleResponse( - certID: .init( - hashAlgorithm: .init(algorithm: .sha1NoSign, parameters: nil), - issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4][...]), - issuerKeyHash: .init(contentBytes: [6, 7, 8, 9, 10][...]), - serialNumber: .init() - ), - certStatus: .good, - thisUpdate: try .init(now - .days(1)), - nextUpdate: try .init(now + .days(1)) - )], responseExtensions: { nonce })) + return .successful(try .signed( + responses: [OCSPSingleResponse( + certID: .init( + hashAlgorithm: .init(algorithm: .sha1NoSign, parameters: nil), + issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4][...]), + issuerKeyHash: .init(contentBytes: [6, 7, 8, 9, 10][...]), + serialNumber: .init() + ), + certStatus: .good, + thisUpdate: try .init(now - .days(1)), + nextUpdate: try .init(now + .days(1)) + )]) { + nonce + } + ) } ) } func testShouldNotQueryResponderIfNoOCSPServerIsDefined() async { await self.assertChainMeetsPolicy(chain: [ - Self.certificate(subject: Self.localhostLeafName, issuer: Self.intermediate1Name), - Self.certificate(subject: Self.intermediate1Name, issuer: Self.ca1Name), - Self.certificate(subject: Self.ca1Name, issuer: Self.ca1Name), - ], requester: .noThrow { request, uri -> OCSPResponse in + Self.leaf(), + Self.intermediate(), + Self.ca1, + ], requester: TestRequester.noThrow { request, uri -> OCSPResponse in struct ShouldNotQueryResponderError: Error {} throw ShouldNotQueryResponderError() }, expectedQueryCount: 0) @@ -290,10 +482,10 @@ final class OCSPVerifierPolicyTests: XCTestCase { func testLastCertificateIsNotAllowedToHaveOCSP() async { await self.assertChainFailsToMeetPolicy(chain: [ - Self.certificate(subject: Self.localhostLeafName, issuer: Self.intermediate1Name), - Self.certificate(subject: Self.intermediate1Name, issuer: Self.ca1Name), - Self.certificate(subject: Self.ca1Name, issuer: Self.ca1Name, ocspServer: Self.responderURI), - ], requester: .noThrow { request, uri -> OCSPResponse in + Self.leaf(), + Self.intermediate(), + Self.ca(ocspServer: Self.responderURI), + ], requester: TestRequester.noThrow { request, uri -> OCSPResponse in struct ShouldNotQueryResponderError: Error {} throw ShouldNotQueryResponderError() }, expectedQueryCount: 0) @@ -302,7 +494,7 @@ final class OCSPVerifierPolicyTests: XCTestCase { func testQueryIsAllowedToFail() async { await self.assertChainMeetsPolicy( chain: Self.chainWithSingleCertWithOCSP, - requester: .init { request, uri -> OCSPResponse in + requester: TestRequester { request, uri -> OCSPResponse in struct QueryErrorsAreAcceptable: Error {} throw QueryErrorsAreAcceptable() } @@ -313,19 +505,23 @@ final class OCSPVerifierPolicyTests: XCTestCase { func responseWithCertStatusGood( thisUpdate: Date, nextUpdate: Date? - ) -> TestRequester { - .noThrow { request, uri -> OCSPResponse in + ) -> some OCSPRequester { + TestRequester.noThrow { request, uri -> OCSPResponse in XCTAssertEqual(uri, Self.responderURI) XCTAssertNil(request.signature) let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce) XCTAssertEqual(request.tbsRequest.requestList.count, 1) let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first) - return .successful(.signed(responses: [OCSPSingleResponse( - certID: singleRequest.certID, - certStatus: .good, - thisUpdate: try .init(thisUpdate), - nextUpdate: try nextUpdate.map { try .init($0) } - )], responseExtensions: { nonce })) + return .successful(try .signed( + responses: [OCSPSingleResponse( + certID: singleRequest.certID, + certStatus: .good, + thisUpdate: try .init(thisUpdate), + nextUpdate: try nextUpdate.map { try .init($0) } + )]) { + nonce + } + ) } } @@ -333,8 +529,8 @@ final class OCSPVerifierPolicyTests: XCTestCase { await self.assertChainMeetsPolicy( chain: Self.chainWithSingleCertWithOCSP, requester: responseWithCertStatusGood( - thisUpdate: self.now, - nextUpdate: self.now + 1 + thisUpdate: self.validationTime, + nextUpdate: self.validationTime + 1 ) ) @@ -342,7 +538,7 @@ final class OCSPVerifierPolicyTests: XCTestCase { await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, requester: responseWithCertStatusGood( - thisUpdate: self.now, + thisUpdate: self.validationTime, nextUpdate: nil ) ) @@ -350,8 +546,8 @@ final class OCSPVerifierPolicyTests: XCTestCase { await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, requester: responseWithCertStatusGood( - thisUpdate: self.now + 1, - nextUpdate: self.now + 2 + thisUpdate: self.validationTime + 1, + nextUpdate: self.validationTime + 2 ) ) @@ -359,19 +555,73 @@ final class OCSPVerifierPolicyTests: XCTestCase { await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, requester: responseWithCertStatusGood( - thisUpdate: self.now + 1, - nextUpdate: self.now - 1 + thisUpdate: self.validationTime + 1, + nextUpdate: self.validationTime - 1 ) ) /// this update and next update is in the past await self.assertChainFailsToMeetPolicy( chain: Self.chainWithSingleCertWithOCSP, requester: responseWithCertStatusGood( - thisUpdate: self.now - 2, - nextUpdate: self.now - 1 + thisUpdate: self.validationTime - 2, + nextUpdate: self.validationTime - 1 ) ) } + + func testWWWDotAppleDotComResponder() async throws { + actor StaticOCSPRequester: OCSPRequester { + var responses: [OCSPResponse] + init(responses: [OCSPResponse]) { + self.responses = responses + } + var nextIndex: Int = 0 + func query(request: [UInt8], uri: String) async throws -> [UInt8] { + let responseIndex = nextIndex + nextIndex += 1 + guard responses.indices.contains(responseIndex) else { + struct StaticOCSPRequesterRunOutOfResponses: Error {} + throw StaticOCSPRequesterRunOutOfResponses() + } + let response = responses[responseIndex] + return try DER.Serializer.serialized(element: response) + } + } + + func load(_ filePath: String, extension: String) throws -> [UInt8] { + guard let url = Bundle.module.url(forResource: filePath, withExtension: `extension`) else { + struct CouldNotGetURLFromBundle: Error { + var filePath: String + var `extension`: String + } + throw CouldNotGetURLFromBundle(filePath: filePath, extension: `extension`) + } + + return Array(try Data(contentsOf: url)) + } + func loadCertificate(_ filePath: String, extension: String) throws -> Certificate { + try Certificate(derEncoded: load(filePath, extension: `extension`)) + } + func loadOCSPResponse(_ filePath: String, extension: String) throws -> OCSPResponse { + try OCSPResponse(derEncoded: load(filePath, extension: `extension`)) + } + + let root = try loadCertificate("www.apple.com.root", extension: "der") + let intermediate = try loadCertificate("www.apple.com.intermediate", extension: "der") + let leaf = try loadCertificate("www.apple.com", extension: "der") + let ocspResponseLeaf = try loadOCSPResponse("www.apple.com.ocsp-response", extension: "der") + let ocspResponseIntermediate = try loadOCSPResponse("www.apple.com.intermediate.ocsp-response", extension: "der") + let timeOfOCSPRequest = try Date(GeneralizedTime(year: 2023, month: 3, day: 15, hours: 15, minutes: 36, seconds: 0, fractionalSeconds: 0.0))! + + await self.assertChainMeetsPolicy( + chain: [leaf, intermediate, root], + requester: StaticOCSPRequester(responses: [ + ocspResponseLeaf, + ocspResponseIntermediate, + ]).assertNoThrow(), + validationTime: timeOfOCSPRequest + ) + } } extension GeneralizedTime { @@ -391,27 +641,59 @@ extension GeneralizedTime { extension BasicOCSPResponse { - static func signed(responseData: OCSPResponseData) -> Self { - // TODO: actually sign the response once we validate the signature - .init( + static func signed( + responseData: OCSPResponseData, + privateKey: P384.Signing.PrivateKey, + certs: [Certificate]? + ) throws -> Self { + var serializer = DER.Serializer() + try serializer.serialize(responseData) + let tbsCertificateBytes = serializer.serializedBytes[...] + + let digest = SHA384.hash(data: tbsCertificateBytes) + let signature = try privateKey.signature(for: digest) + + return try .init( responseData: responseData, - signatureAlgorithm: .ecdsaWithSHA256, - signature: .init(bytes: [][...]) + signatureAlgorithm: .ecdsaWithSHA384, + signature: .init(bytes: Array(signature.derRepresentation)[...]), + certs: certs ) } static func signed( version: OCSPVersion = .v1, - responderID: ResponderID = OCSPVerifierPolicyTests.responderId, + responderID: ResponderID = .byName(OCSPVerifierPolicyTests.intermediate1Name), producedAt: GeneralizedTime = try! .init(Date()), responses: [OCSPSingleResponse], + privateKey: P384.Signing.PrivateKey = OCSPVerifierPolicyTests.intermediatePrivateKey, + certs: [Certificate]? = [], @ExtensionsBuilder responseExtensions: () -> Certificate.Extensions = { .init() } - ) -> Self { - .signed(responseData: .init( - version: version, - responderID: responderID, - producedAt: producedAt, - responses: responses, - responseExtensions: responseExtensions() - )) + ) throws -> Self { + try .signed( + responseData: .init( + version: version, + responderID: responderID, + producedAt: producedAt, + responses: responses, + responseExtensions: responseExtensions() + ), + privateKey: privateKey, + certs: certs + ) + } + + init( + responseData: OCSPResponseData, + signatureAlgorithm: AlgorithmIdentifier, + signature: ASN1BitString, + certs: [Certificate]? + ) throws { + self.init( + responseData: responseData, + responseDataBytes: try DER.Serializer.serialized(element: responseData)[...], + signatureAlgorithm: signatureAlgorithm, + signature: signature, + certs: certs + ) } }