mirror of
https://github.com/apple/swift-certificates
synced 2026-11-30 05:08:44 +00:00
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.
This commit is contained in:
1 parent
7fff85a91e
commit
4a67b473a1
14 files changed
+638
-199
No files matched your search
@@ -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"),
|
||||
]),
|
||||
]
|
||||
)
|
||||
|
||||
@@ -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: DERSerializable>(element: Element) throws -> ArraySlice<UInt8> {
|
||||
static func serialized<Element: DERSerializable>(element: Element) throws -> [UInt8] {
|
||||
var serializer = DER.Serializer()
|
||||
try serializer.serialize(element)
|
||||
return serializer.serializedBytes[...]
|
||||
return serializer.serializedBytes
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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<UInt8>
|
||||
|
||||
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<UInt8>, 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)
|
||||
|
||||
@@ -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<UInt8>(derEncoded: &nodes)
|
||||
|
||||
@@ -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<Requester: OCSPRequester>: VerifierPolicy, Sendable {
|
||||
public struct OCSPVerifierPolicy<Requester: OCSPRequester>: VerifierPolicy {
|
||||
|
||||
private var requester: Requester
|
||||
private var requestHashAlgorithm: OCSPRequestHashAlgorithm
|
||||
@@ -94,24 +121,25 @@ public struct OCSPVerifierPolicy<Requester: OCSPRequester>: 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<Requester: OCSPRequester>: VerifierPolicy, Send
|
||||
return .meetsPolicy
|
||||
}
|
||||
|
||||
|
||||
|
||||
private func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult {
|
||||
|
||||
let authorityInformationAccess: AuthorityInformationAccess?
|
||||
@@ -177,11 +203,11 @@ public struct OCSPVerifierPolicy<Requester: OCSPRequester>: 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<Requester: OCSPRequester>: 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<UInt8>,
|
||||
signatureBytes: ArraySlice<UInt8>,
|
||||
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`
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)[...])
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A sub-policy of the ``RFC5280Policy`` that polices expiry.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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<Wrapped: OCSPRequester>: 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
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user