From 54aa3a0d96ed00b13a95f33596a5e7354bde0788 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Tue, 13 Dec 2022 11:48:42 +0100 Subject: [PATCH 01/12] OCSPRequest --- Sources/X509/OCSP/OCSPRequest.swift | 120 ++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 Sources/X509/OCSP/OCSPRequest.swift diff --git a/Sources/X509/OCSP/OCSPRequest.swift b/Sources/X509/OCSP/OCSPRequest.swift new file mode 100644 index 0000000..6c677f6 --- /dev/null +++ b/Sources/X509/OCSP/OCSPRequest.swift @@ -0,0 +1,120 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.md for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPRequest`` is defined in ASN.1 as: +/// ``` +/// OCSPRequest ::= SEQUENCE { +/// tbsRequest TBSRequest, +/// optionalSignature [0] EXPLICIT Signature OPTIONAL } +/// ``` +struct OCSPRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var tbsRequest: OCSPTBSRequest + + var signature: OCSPSignature? + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } +} + +/// ``OCSPTBSRequest`` is defined in ASN.1 as: +/// ``` +/// TBSRequest ::= SEQUENCE { +/// version [0] EXPLICIT Version DEFAULT v1, +/// requestorName [1] EXPLICIT GeneralName OPTIONAL, +/// requestList SEQUENCE OF Request, +/// requestExtensions [2] EXPLICIT Extensions OPTIONAL } +/// +/// Version ::= INTEGER { v1(0) } +/// ``` +struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var version: Int + + var requestorName: GeneralName? + + var requestList: [OCSPSingleRequest] + + var requestExtensions: Certificate.Extensions? + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } +} + +/// ``OCSPSingleRequest`` is defined in ASN.1 as: +/// ``` +/// SingleRequest ::= SEQUENCE { +/// reqCert CertID, +/// singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } +/// ``` +/// - note: originally named just `Request` in RFC 6960 but prefix `Single` added to avoid naming conflicts with ``OCSPRequest`` +struct OCSPSingleRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var certID: OCSPCertID + + var singleRequestExtensions: Certificate.Extensions? + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } +} + + +/// ``OCSPSignature`` is defined in ASN.1 as: +/// ``` +/// Signature ::= SEQUENCE { +/// signatureAlgorithm AlgorithmIdentifier, +/// signature BIT STRING, +/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } +/// ``` +struct OCSPSignature: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var algortihmIdentifier: AlgorithmIdentifier + + var signature: ASN1BitString + + var certs: [Certificate]? + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + fatalError() + } +} From eef0736e81de42de396337ebd1759fdafc4dcd71 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Wed, 14 Dec 2022 12:55:44 +0100 Subject: [PATCH 02/12] Implement de/encoding --- Sources/X509/OCSP/OCSPRequest.swift | 106 +++++----------------- Sources/X509/OCSP/OCSPSignature.swift | 63 +++++++++++++ Sources/X509/OCSP/OCSPSingleRequest.swift | 60 ++++++++++++ Sources/X509/OCSP/OCSPTBSRequest.swift | 83 +++++++++++++++++ Sources/X509/OCSP/OCSPVersion.swift | 44 +++++++++ 5 files changed, 272 insertions(+), 84 deletions(-) create mode 100644 Sources/X509/OCSP/OCSPSignature.swift create mode 100644 Sources/X509/OCSP/OCSPSingleRequest.swift create mode 100644 Sources/X509/OCSP/OCSPTBSRequest.swift create mode 100644 Sources/X509/OCSP/OCSPVersion.swift diff --git a/Sources/X509/OCSP/OCSPRequest.swift b/Sources/X509/OCSP/OCSPRequest.swift index 6c677f6..47ed13f 100644 --- a/Sources/X509/OCSP/OCSPRequest.swift +++ b/Sources/X509/OCSP/OCSPRequest.swift @@ -6,7 +6,7 @@ // Licensed under Apache License v2.0 // // See LICENSE.txt for license information -// See CONTRIBUTORS.md for the list of SwiftCertificates project authors +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors // // SPDX-License-Identifier: Apache-2.0 // @@ -29,92 +29,30 @@ struct OCSPRequest: DERImplicitlyTaggable, Hashable { var signature: OCSPSignature? - init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { - fatalError() + init(tbsRequest: OCSPTBSRequest, signature: OCSPSignature? = nil) { + self.tbsRequest = tbsRequest + self.signature = signature } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let tbsRequest = try OCSPTBSRequest(derEncoded: &nodes) + let signature = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { + try OCSPSignature(derEncoded: $0) + } + return .init(tbsRequest: tbsRequest, signature: signature) + } + } + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - fatalError() - } -} - -/// ``OCSPTBSRequest`` is defined in ASN.1 as: -/// ``` -/// TBSRequest ::= SEQUENCE { -/// version [0] EXPLICIT Version DEFAULT v1, -/// requestorName [1] EXPLICIT GeneralName OPTIONAL, -/// requestList SEQUENCE OF Request, -/// requestExtensions [2] EXPLICIT Extensions OPTIONAL } -/// -/// Version ::= INTEGER { v1(0) } -/// ``` -struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable { - static var defaultIdentifier: ASN1Identifier { - .sequence - } - - var version: Int - - var requestorName: GeneralName? - - var requestList: [OCSPSingleRequest] - - var requestExtensions: Certificate.Extensions? - - init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { - fatalError() - } - func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - fatalError() - } -} - -/// ``OCSPSingleRequest`` is defined in ASN.1 as: -/// ``` -/// SingleRequest ::= SEQUENCE { -/// reqCert CertID, -/// singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } -/// ``` -/// - note: originally named just `Request` in RFC 6960 but prefix `Single` added to avoid naming conflicts with ``OCSPRequest`` -struct OCSPSingleRequest: DERImplicitlyTaggable, Hashable { - static var defaultIdentifier: ASN1Identifier { - .sequence - } - - var certID: OCSPCertID - - var singleRequestExtensions: Certificate.Extensions? - - init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { - fatalError() - } - func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - fatalError() + try coder.appendConstructedNode(identifier: identifier) { coder in + try coder.serialize(self.tbsRequest) + if let signature = self.signature { + try coder.serialize(signature, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } + } } } -/// ``OCSPSignature`` is defined in ASN.1 as: -/// ``` -/// Signature ::= SEQUENCE { -/// signatureAlgorithm AlgorithmIdentifier, -/// signature BIT STRING, -/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } -/// ``` -struct OCSPSignature: DERImplicitlyTaggable, Hashable { - static var defaultIdentifier: ASN1Identifier { - .sequence - } - - var algortihmIdentifier: AlgorithmIdentifier - - var signature: ASN1BitString - - var certs: [Certificate]? - - init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { - fatalError() - } - func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - fatalError() - } -} + diff --git a/Sources/X509/OCSP/OCSPSignature.swift b/Sources/X509/OCSP/OCSPSignature.swift new file mode 100644 index 0000000..b96f70f --- /dev/null +++ b/Sources/X509/OCSP/OCSPSignature.swift @@ -0,0 +1,63 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPSignature`` is defined in ASN.1 as: +/// ``` +/// Signature ::= SEQUENCE { +/// signatureAlgorithm AlgorithmIdentifier, +/// signature BIT STRING, +/// certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } +/// ``` +struct OCSPSignature: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var algorithmIIdentifier: AlgorithmIdentifier + + var signature: ASN1BitString + + var certs: [Certificate]? + + init(algorithmIIdentifier: AlgorithmIdentifier, signature: ASN1BitString, certs: [Certificate]? = nil) { + self.algorithmIIdentifier = algorithmIIdentifier + self.signature = signature + self.certs = certs + } + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(derEncoded, identifier: identifier) { nodes in + let algorithmIIdentifier = try AlgorithmIdentifier(derEncoded: &nodes) + let signature = try ASN1BitString(derEncoded: &nodes) + let certs = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + try DER.sequence(of: Certificate.self, identifier: .sequence, rootNode: node) + } + return .init(algorithmIIdentifier: algorithmIIdentifier, signature: signature, certs: certs) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try self.algorithmIIdentifier.serialize(into: &coder) + try self.signature.serialize(into: &coder) + if let certs = self.certs { + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(certs) + } + } + } + } +} diff --git a/Sources/X509/OCSP/OCSPSingleRequest.swift b/Sources/X509/OCSP/OCSPSingleRequest.swift new file mode 100644 index 0000000..f14833e --- /dev/null +++ b/Sources/X509/OCSP/OCSPSingleRequest.swift @@ -0,0 +1,60 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPSingleRequest`` is defined in ASN.1 as: +/// ``` +/// Request ::= SEQUENCE { +/// reqCert CertID, +/// singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } +/// ``` +/// - note: originally named just `Request` in RFC 6960 but prefix `Single` added to avoid naming conflicts with ``OCSPRequest`` +struct OCSPSingleRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var certID: OCSPCertID + + var singleRequestExtensions: Certificate.Extensions? + + init(certID: OCSPCertID, singleRequestExtensions: Certificate.Extensions? = nil) { + self.certID = certID + self.singleRequestExtensions = singleRequestExtensions + } + + init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(derEncoded, identifier: identifier) { nodes in + let certID = try OCSPCertID(derEncoded: &nodes) + let singleRequestExtensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in + Certificate.Extensions( + extensions: try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node) + ) + } + return .init(certID: certID, singleRequestExtensions: singleRequestExtensions) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + try self.certID.serialize(into: &coder) + if let singleRequestExtensions = self.singleRequestExtensions { + try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(singleRequestExtensions) + } + } + } + } +} diff --git a/Sources/X509/OCSP/OCSPTBSRequest.swift b/Sources/X509/OCSP/OCSPTBSRequest.swift new file mode 100644 index 0000000..a00758b --- /dev/null +++ b/Sources/X509/OCSP/OCSPTBSRequest.swift @@ -0,0 +1,83 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +/// ``OCSPTBSRequest`` is defined in ASN.1 as: +/// ``` +/// TBSRequest ::= SEQUENCE { +/// version [0] EXPLICIT Version DEFAULT v1, +/// requestorName [1] EXPLICIT GeneralName OPTIONAL, +/// requestList SEQUENCE OF Request, +/// requestExtensions [2] EXPLICIT Extensions OPTIONAL } +/// +/// Version ::= INTEGER { v1(0) } +/// ``` +struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable { + static var defaultIdentifier: ASN1Identifier { + .sequence + } + + var version: OCSPVersion + + var requestorName: GeneralName? + + var requestList: [OCSPSingleRequest] + + var requestExtensions: Certificate.Extensions? + + init(version: OCSPVersion, requestorName: GeneralName? = nil, requestList: [OCSPSingleRequest], requestExtensions: Certificate.Extensions? = nil) { + self.version = version + self.requestorName = requestorName + self.requestList = requestList + self.requestExtensions = requestExtensions + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self = try DER.sequence(rootNode, identifier: identifier) { nodes in + let version = try DER.decodeDefaultExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific, defaultValue: Int(0)) + let requestorName = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { + try GeneralName(derEncoded: $0) + } + let requestList = try DER.sequence(of: OCSPSingleRequest.self,identifier: .sequence, nodes: &nodes) + let extensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific) { + try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: $0) + } + + return .init( + version: .init(rawValue: version), + requestorName: requestorName, + requestList: requestList, + requestExtensions: extensions.map { .init(extensions: $0) } + ) + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try coder.appendConstructedNode(identifier: identifier) { coder in + if self.version != .v1 { + try coder.serialize(self.version.rawValue, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + } + if let requestorName = self.requestorName { + try coder.serialize(requestorName, explicitlyTaggedWithTagNumber: 1, tagClass: .contextSpecific) + } + try coder.serializeSequenceOf(requestList) + if let requestExtensions = self.requestExtensions { + try coder.serialize(explicitlyTaggedWithTagNumber: 2, tagClass: .contextSpecific) { coder in + try coder.serializeSequenceOf(requestExtensions._extensions) + } + } + } + } +} diff --git a/Sources/X509/OCSP/OCSPVersion.swift b/Sources/X509/OCSP/OCSPVersion.swift new file mode 100644 index 0000000..0b23b56 --- /dev/null +++ b/Sources/X509/OCSP/OCSPVersion.swift @@ -0,0 +1,44 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +struct OCSPVersion { + var rawValue: Int + + init(rawValue: Int) { + self.rawValue = rawValue + } + + static let v1 = Self(rawValue: 0) +} + +extension OCSPVersion: Hashable { } + +extension OCSPVersion: Sendable { } + +extension OCSPVersion: Comparable { + static func < (lhs: Self, rhs: Self) -> Bool { + lhs.rawValue < rhs.rawValue + } +} + +extension OCSPVersion: CustomStringConvertible { + var description: String { + switch self { + case .v1: + return "OCSPv1" + case let unknown: + return "OCSPv\(unknown.rawValue + 1)" + } + } +} From 5f8154ecb14f755a1e7c5ec89cd2956381fb1454 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 15 Dec 2022 12:03:52 +0100 Subject: [PATCH 03/12] Add tests --- Tests/X509Tests/OCSPTests.swift | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/Tests/X509Tests/OCSPTests.swift b/Tests/X509Tests/OCSPTests.swift index a92c752..b0e2285 100644 --- a/Tests/X509Tests/OCSPTests.swift +++ b/Tests/X509Tests/OCSPTests.swift @@ -28,17 +28,43 @@ import XCTest @testable import SwiftASN1 +@testable import X509 final class OCSPTests: XCTestCase { - // TODO: Make these work. - #if false private func assertRoundTrips(_ value: ASN1Object) throws { var serializer = DER.Serializer() try serializer.serialize(value) let parsed = try ASN1Object(derEncoded: serializer.serializedBytes) XCTAssertEqual(parsed, value) } - + + func testRequestRoundtrip() throws { + let ocspRequest = OCSPRequest( + tbsRequest: OCSPTBSRequest( + version: .v1, + requestorName: GeneralName.dNSName("swift.org"), + requestList: [OCSPSingleRequest( + certID: OCSPCertID( + hashAlgorithm: .ecdsaWithSHA256, + issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]), + issuerKeyHash: .init(contentBytes: [10, 11, 12, 13, 14, 15, 16, 17, 18]), + serialNumber: [20, 21, 22, 23, 24, 25, 26, 27, 28] + ), + singleRequestExtensions: nil + )], + requestExtensions: nil), + signature: OCSPSignature( + algorithmIIdentifier: .p256PublicKey, + signature: .init(bytes: [31, 32, 33, 34, 35, 36, 37, 38]), + certs: nil + ) + ) + + try assertRoundTrips(ocspRequest) + } + + // TODO: Make these work. + #if false func testResponderIDByNameRoundTrips() throws { let id = ASN1.ResponderID.byName( ASN1.DistinguishedName(elements: [ From 533f40c5ddb29cc3c22b379186dbb8d0ef21f08a Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 29 Dec 2022 12:55:54 +0100 Subject: [PATCH 04/12] Prototype of OCSPPolicy --- Package.swift | 2 + Sources/X509/OCSP/OCSPCertID.swift | 2 + Sources/X509/OCSP/OCSPPolicy.swift | 172 +++++++++++++++++++++++++++ Sources/X509/OCSP/OCSPResponse.swift | 76 ++++++++++-- 4 files changed, 239 insertions(+), 13 deletions(-) create mode 100644 Sources/X509/OCSP/OCSPPolicy.swift diff --git a/Package.swift b/Package.swift index f6dc568..bcbe9b5 100644 --- a/Package.swift +++ b/Package.swift @@ -30,6 +30,7 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/apple/swift-crypto.git", from: "2.2.1"), + .package(url: "https://github.com/apple/swift-algorithms.git", from: "1.0.0"), // swift-asn1 repo is private, so we can't access it anonymously yet // .package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.3.0")), .package(url: "git@github.com:apple/swift-asn1.git", .upToNextMinor(from: "0.3.0")), @@ -42,6 +43,7 @@ let package = Package( .product(name: "SwiftASN1", package: "swift-asn1"), .product(name: "Crypto", package: "swift-crypto"), .product(name: "_CryptoExtras", package: "swift-crypto"), + .product(name: "Algorithms", package: "swift-algorithms"), ]), .testTarget( name: "X509Tests", diff --git a/Sources/X509/OCSP/OCSPCertID.swift b/Sources/X509/OCSP/OCSPCertID.swift index 37172e2..421c4b2 100644 --- a/Sources/X509/OCSP/OCSPCertID.swift +++ b/Sources/X509/OCSP/OCSPCertID.swift @@ -29,8 +29,10 @@ import SwiftASN1 struct OCSPCertID: DERImplicitlyTaggable, Hashable { var hashAlgorithm: AlgorithmIdentifier + /// Hash of issuer's DN var issuerNameHash: ASN1OctetString + /// Hash of issuer's public key var issuerKeyHash: ASN1OctetString var serialNumber: ArraySlice diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift new file mode 100644 index 0000000..e892dff --- /dev/null +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -0,0 +1,172 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 +import CryptoKit +import Algorithms +import protocol Foundation.DataProtocol + +public protocol OCSPRequester: Sendable { + /// Called with a OCSP Request + /// - Parameters: + /// - request: DER-encoded request bytes + /// - uri: uri of the + /// - Returns: DER-encoded response bytes + func query(request: [UInt8], uri: String) async throws -> [UInt8] + // TODO: Do we need to handle a request timeout gracefully? + // TODO: If yes, how should this method signal a timeout? throw an error or return an enum with a success and timeout case? +} + + +// TODO: define verify modes and enforce them +public struct OCSPVerifierMode { + public static let required = Self(backing: .required) + public static let soft = Self(backing: .soft) + enum Backing { + case required + case soft + } + var backing: Backing +} + +extension ASN1ObjectIdentifier { + static let sha256NoSign: Self = [2, 16, 840, 1, 101, 3, 4, 2, 1] + static let sha1NoSign: Self = [1, 3, 14, 3, 2, 26] +} + +public struct OCSPVerifierPolicy: VerifierPolicy { + enum RequestHashAlgorithm { + case insecureSha1 + // TODO: can we somehow automatically figure out that a responder will support sha256? + case sha256 + + var oid: ASN1ObjectIdentifier { + switch self { + case .insecureSha1: return .sha1NoSign + case .sha256: return .sha256NoSign + } + } + private func hashed(_ value: some DataProtocol) -> ArraySlice { + switch self { + case .insecureSha1: + var hashAlgorithm = Insecure.SHA1() + hashAlgorithm.update(data: value) + return Array(hashAlgorithm.finalize())[...] + case .sha256: + var hashAlgorithm = SHA256() + hashAlgorithm.update(data: value) + return Array(hashAlgorithm.finalize())[...] + } + } + + fileprivate func issuerNameHashed(_ certificate: Certificate) throws -> ArraySlice { + /// issuerNameHash is the hash of the issuer's distinguished name + /// (DN). The hash shall be calculated over the DER encoding of the + /// issuer's name field in the certificate being checked. + var serializer = DER.Serializer() + try serializer.serialize(certificate.subject) + return hashed(serializer.serializedBytes) + } + + fileprivate func issuerPublicKeyHashed(_ certificate: Certificate) -> ArraySlice { + /// issuerKeyHash is the hash of the issuer's public key. The hash + /// shall be calculated over the value (excluding tag and length) of + /// the subject public key field in the issuer's certificate. + hashed(SubjectPublicKeyInfo(certificate.publicKey).key.bytes) + } + } + var requester: Requester + var mode: OCSPVerifierMode + var requestHashAlgorithm: RequestHashAlgorithm + + public init(requester: Requester, mode: OCSPVerifierMode) { + self.requester = requester + self.mode = mode + self.requestHashAlgorithm = .insecureSha1 + } + + public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + for (certificate, issuer) in chain.adjacentPairs() { + switch await certificateMeetsPolicyRequirements(certificate, issuer: issuer) { + case .meetsPolicy: + continue + case .failsToMeetPolicy(let reason): + return .failsToMeetPolicy(reason: reason) + } + } + return .meetsPolicy + // TODO: should we verify that the last certificate doesn't have an OCSP extension set? + } + + public mutating func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult { + guard let description = certificate.extensions[oid: .X509ExtensionID.authorityInformationAccess] else { + // OCSP not necessary for certificate + return .meetsPolicy + } + do { + let authorityInformationAccess = try Certificate.Extensions.AuthorityInformationAccess(description) + + guard let ocspAccessDescription = authorityInformationAccess.first(where: { $0.method == .ocspServer }) else { + return .meetsPolicy + } + + guard case .uniformResourceIdentifier(let uri) = ocspAccessDescription.location else { + return .failsToMeetPolicy(reason: "expected OCSP location to be a URI but got \(ocspAccessDescription.location)") + } + + let request = try request(certificate: certificate, issuer: issuer) + + var serializer = DER.Serializer() + try serializer.serialize(request) + + let responseDer = try await requester.query(request: serializer.serializedBytes, uri: uri) + + let response = try OCSPResponse(derEncoded: responseDer[...]) + switch response { + case .successful(let basicResponse): + guard let response = basicResponse.responseData.responses.first else { + return .failsToMeetPolicy(reason: "empty response") + } + switch response.certStatus { + case .good: + // TODO: verify signature + // TODO: verify time + return .meetsPolicy + case .revoked, .unknown: + return .failsToMeetPolicy(reason: "bad OCSP response: \(response)") + } + case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: + return .failsToMeetPolicy(reason: "OCSP request failed \(response)") + } + + } catch { + return .failsToMeetPolicy(reason: "OCSP failed: \(error)") + } + } + + func request(certificate: Certificate, issuer: Certificate) throws -> OCSPRequest { + // TODO: add nonce + OCSPRequest(tbsRequest: OCSPTBSRequest( + version: .v1, + requestList: [ + OCSPSingleRequest(certID: OCSPCertID( + hashAlgorithm: .init(algorithm: requestHashAlgorithm.oid, parameters: nil), + issuerNameHash: .init(contentBytes: try requestHashAlgorithm.issuerNameHashed(issuer)), + issuerKeyHash: .init(contentBytes: requestHashAlgorithm.issuerPublicKeyHashed(issuer)), + serialNumber: certificate.serialNumber.bytes + )) + ] + )) + } +} diff --git a/Sources/X509/OCSP/OCSPResponse.swift b/Sources/X509/OCSP/OCSPResponse.swift index 179b483..a1372ac 100644 --- a/Sources/X509/OCSP/OCSPResponse.swift +++ b/Sources/X509/OCSP/OCSPResponse.swift @@ -23,19 +23,17 @@ import SwiftASN1 /// /// ``` /// -struct OCSPResponse: DERImplicitlyTaggable, Hashable { +enum OCSPResponse: DERImplicitlyTaggable, Hashable { static var defaultIdentifier: ASN1Identifier { .sequence } - var responseStatus: OCSPResponseStatus - - var responseBytes: OCSPResponseBytes? - - init(responseStatus: OCSPResponseStatus, responseBytes: OCSPResponseBytes?) { - self.responseStatus = responseStatus - self.responseBytes = responseBytes - } + case successful(BasicOCSPResponse) + case malformedRequest + case internalError + case tryLater + case sigRequired + case unauthorized init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { self = try DER.sequence(rootNode, identifier: identifier) { nodes in @@ -43,17 +41,69 @@ struct OCSPResponse: DERImplicitlyTaggable, Hashable { let responseBytes = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in try OCSPResponseBytes(derEncoded: node) } - - return .init(responseStatus: responseStatus, responseBytes: responseBytes) + switch responseStatus { + case .successful: + guard let responseBytes, + responseBytes.responseType == .OCSP.basicResponse + else { + throw ASN1Error.invalidASN1Object + } + return .successful(try BasicOCSPResponse(derEncoded: responseBytes.response.bytes)) + case .malformedRequest: + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + return .malformedRequest + case .internalError: + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + return .internalError + case .tryLater: + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + return .tryLater + case .sigRequired: + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + return .sigRequired + case .unauthorized: + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + return .unauthorized + } } } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { try coder.appendConstructedNode(identifier: identifier) { coder in - try coder.serialize(self.responseStatus) - if let responseBytes = self.responseBytes { + try coder.serialize(OCSPResponseStatus(self)) + switch self { + case .successful(let basicResponse): + var serializer = DER.Serializer() + try serializer.serialize(basicResponse) + let responseBytes = OCSPResponseBytes(responseType: .OCSP.basicResponse, response: .init(contentBytes: serializer.serializedBytes[...])) try coder.serialize(responseBytes, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + + case .malformedRequest, + .internalError, + .tryLater, + .sigRequired, + .unauthorized: + break } } } } + +extension OCSPResponseStatus { + init(_ response: OCSPResponse) { + switch response { + case .successful: + self = .successful + case .malformedRequest: + self = .malformedRequest + case .internalError: + self = .internalError + case .tryLater: + self = .tryLater + case .sigRequired: + self = .sigRequired + case .unauthorized: + self = .unauthorized + } + } +} From 4be8c203f9505e4a4250f10daef5e22d3536563a Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Wed, 11 Jan 2023 14:31:00 +0100 Subject: [PATCH 05/12] Add nonce extensions and some general refactoring --- Sources/X509/OCSP/OCSPCertID.swift | 8 +- Sources/X509/OCSP/OCSPCertStatus.swift | 18 +++++ Sources/X509/OCSP/OCSPExtensionID.swift | 20 +++++ Sources/X509/OCSP/OCSPNonce.swift | 88 ++++++++++++++++++++++ Sources/X509/OCSP/OCSPPolicy.swift | 46 +++++------ Sources/X509/OCSP/OCSPResponseData.swift | 14 ++-- Sources/X509/OCSP/OCSPResponseStatus.swift | 41 +++++----- 7 files changed, 184 insertions(+), 51 deletions(-) create mode 100644 Sources/X509/OCSP/OCSPExtensionID.swift create mode 100644 Sources/X509/OCSP/OCSPNonce.swift diff --git a/Sources/X509/OCSP/OCSPCertID.swift b/Sources/X509/OCSP/OCSPCertID.swift index 421c4b2..ec1be1a 100644 --- a/Sources/X509/OCSP/OCSPCertID.swift +++ b/Sources/X509/OCSP/OCSPCertID.swift @@ -35,7 +35,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { /// Hash of issuer's public key var issuerKeyHash: ASN1OctetString - var serialNumber: ArraySlice + var serialNumber: Certificate.SerialNumber static var defaultIdentifier: ASN1Identifier { .sequence @@ -44,7 +44,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { init(hashAlgorithm: AlgorithmIdentifier, issuerNameHash: ASN1OctetString, issuerKeyHash: ASN1OctetString, - serialNumber: ArraySlice) { + serialNumber: Certificate.SerialNumber) { self.hashAlgorithm = hashAlgorithm self.issuerNameHash = issuerNameHash self.issuerKeyHash = issuerKeyHash @@ -61,7 +61,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { return .init(hashAlgorithm: hashAlgorithm, issuerNameHash: issuerNameHash, issuerKeyHash: issuerKeyHash, - serialNumber: serialNumber) + serialNumber: .init(bytes: serialNumber)) } } @@ -70,7 +70,7 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable { try self.hashAlgorithm.serialize(into: &coder) try self.issuerNameHash.serialize(into: &coder) try self.issuerKeyHash.serialize(into: &coder) - try self.serialNumber.serialize(into: &coder) + try self.serialNumber.bytes.serialize(into: &coder) } } } diff --git a/Sources/X509/OCSP/OCSPCertStatus.swift b/Sources/X509/OCSP/OCSPCertStatus.swift index 9739a8d..7bc2839 100644 --- a/Sources/X509/OCSP/OCSPCertStatus.swift +++ b/Sources/X509/OCSP/OCSPCertStatus.swift @@ -149,3 +149,21 @@ struct CRLReason: DERImplicitlyTaggable, Hashable, RawRepresentable { static let privilegeWithdrawn = CRLReason(rawValue: 9) static let aaCompromise = CRLReason(rawValue: 10) } + +extension CRLReason: CustomStringConvertible { + var description: String { + switch rawValue { + case 0: return "unspecified" + case 1: return "keyCompromise" + case 2: return "caCompromise" + case 3: return "affiliationChanged" + case 4: return "superseded" + case 5: return "cessationOfOperation" + case 6: return "certificateHold" + case 8: return "removeFromCRL" + case 9: return "privilegeWithdrawn" + case 10: return "aaCompromise" + default: return "unknown reason \(rawValue)" + } + } +} diff --git a/Sources/X509/OCSP/OCSPExtensionID.swift b/Sources/X509/OCSP/OCSPExtensionID.swift new file mode 100644 index 0000000..5e16736 --- /dev/null +++ b/Sources/X509/OCSP/OCSPExtensionID.swift @@ -0,0 +1,20 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + +extension ASN1ObjectIdentifier { + /// OIDs that identify known OCSP extensions, + enum OCSPExtensionID {} +} diff --git a/Sources/X509/OCSP/OCSPNonce.swift b/Sources/X509/OCSP/OCSPNonce.swift new file mode 100644 index 0000000..872ecaf --- /dev/null +++ b/Sources/X509/OCSP/OCSPNonce.swift @@ -0,0 +1,88 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import SwiftASN1 + + +/// ``OCSPNonce`` is defined in ASN.1 as: +/// ``` +/// Nonce ::= OCTET STRING(SIZE(1..32)) +/// ``` +/// RFC: https://www.rfc-editor.org/rfc/rfc8954.html +struct OCSPNonce: DERImplicitlyTaggable, Hashable, Sendable { + static var defaultIdentifier: ASN1Identifier { + ASN1OctetString.defaultIdentifier + } + var rawValue: ASN1OctetString + + init() { + var generator = SystemRandomNumberGenerator() + self.init(generator: &generator) + } + + init(generator: inout some RandomNumberGenerator) { + self.rawValue = .init(contentBytes: (0..<32).map { _ in UInt8.random(in: 0...255, using: &generator) }[...] ) + } + + init(_ ext: Certificate.Extension) throws { + guard ext.oid == .OCSPExtensionID.nonceIdentifier else { + throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.OCSPExtensionID.nonceIdentifier), got \(ext.oid)") + } + + try self.init(derEncoded: ext.value) + } + + init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { + self.rawValue = try ASN1OctetString(derEncoded: rootNode, withIdentifier: identifier) + guard (1...32).contains(self.rawValue.bytes.count) else { + throw ASN1Error.unsupportedFieldLength + } + } + + func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { + try rawValue.serialize(into: &coder, withIdentifier: identifier) + } +} + +extension ASN1ObjectIdentifier.OCSPExtensionID { + static let nonceIdentifier: ASN1ObjectIdentifier = [1, 3, 6, 1, 5, 5, 7, 48, 1, 2] +} + +extension Certificate.Extension { + /// Construct an opaque ``Certificate/Extension`` from this Key Usage extension. + /// + /// - Parameters: + /// - keyUsage: The extension to wrap + /// - critical: Whether this extension should have the critical bit set. + init(_ nonce: OCSPNonce, critical: Bool) throws { + var serializer = DER.Serializer() + try serializer.serialize(nonce) + self.init(oid: .OCSPExtensionID.nonceIdentifier, critical: critical, value: serializer.serializedBytes[...]) + } +} + +extension OCSPNonce: CertificateExtensionConvertible { + func makeCertificateExtension() throws -> Certificate.Extension { + try .init(self, critical: false) + } +} + + +extension Certificate.Extensions { + var ocspNonce: OCSPNonce? { + get throws { + try self[oid: .OCSPExtensionID.nonceIdentifier].map { try .init($0) } + } + } +} diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index e892dff..133b61b 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -28,18 +28,6 @@ public protocol OCSPRequester: Sendable { // TODO: If yes, how should this method signal a timeout? throw an error or return an enum with a success and timeout case? } - -// TODO: define verify modes and enforce them -public struct OCSPVerifierMode { - public static let required = Self(backing: .required) - public static let soft = Self(backing: .soft) - enum Backing { - case required - case soft - } - var backing: Backing -} - extension ASN1ObjectIdentifier { static let sha256NoSign: Self = [2, 16, 840, 1, 101, 3, 4, 2, 1] static let sha1NoSign: Self = [1, 3, 14, 3, 2, 26] @@ -87,12 +75,10 @@ public struct OCSPVerifierPolicy: VerifierPolicy { } } var requester: Requester - var mode: OCSPVerifierMode var requestHashAlgorithm: RequestHashAlgorithm - public init(requester: Requester, mode: OCSPVerifierMode) { + public init(requester: Requester) { self.requester = requester - self.mode = mode self.requestHashAlgorithm = .insecureSha1 } @@ -125,7 +111,8 @@ public struct OCSPVerifierPolicy: VerifierPolicy { return .failsToMeetPolicy(reason: "expected OCSP location to be a URI but got \(ocspAccessDescription.location)") } - let request = try request(certificate: certificate, issuer: issuer) + let requestNonce = OCSPNonce() + let request = try request(certificate: certificate, issuer: issuer, nonce: requestNonce) var serializer = DER.Serializer() try serializer.serialize(request) @@ -135,16 +122,27 @@ public struct OCSPVerifierPolicy: VerifierPolicy { let response = try OCSPResponse(derEncoded: responseDer[...]) switch response { case .successful(let basicResponse): + guard basicResponse.responseData.version == .v1 else { + return .failsToMeetPolicy(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") + } + // 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 { + guard requestNonce == responseNonce else { + return .failsToMeetPolicy(reason: "OCSP response nonce does not match request nonce") + } + } guard let response = basicResponse.responseData.responses.first else { - return .failsToMeetPolicy(reason: "empty response") + return .failsToMeetPolicy(reason: "empty OCSP response") } switch response.certStatus { case .good: // TODO: verify signature // TODO: verify time return .meetsPolicy - case .revoked, .unknown: - return .failsToMeetPolicy(reason: "bad OCSP response: \(response)") + 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 .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: return .failsToMeetPolicy(reason: "OCSP request failed \(response)") @@ -155,8 +153,7 @@ public struct OCSPVerifierPolicy: VerifierPolicy { } } - func request(certificate: Certificate, issuer: Certificate) throws -> OCSPRequest { - // TODO: add nonce + func request(certificate: Certificate, issuer: Certificate, nonce: OCSPNonce) throws -> OCSPRequest { OCSPRequest(tbsRequest: OCSPTBSRequest( version: .v1, requestList: [ @@ -164,9 +161,12 @@ public struct OCSPVerifierPolicy: VerifierPolicy { hashAlgorithm: .init(algorithm: requestHashAlgorithm.oid, parameters: nil), issuerNameHash: .init(contentBytes: try requestHashAlgorithm.issuerNameHashed(issuer)), issuerKeyHash: .init(contentBytes: requestHashAlgorithm.issuerPublicKeyHashed(issuer)), - serialNumber: certificate.serialNumber.bytes + serialNumber: certificate.serialNumber )) - ] + ], + requestExtensions: try .init(builder: { + nonce + }) )) } } diff --git a/Sources/X509/OCSP/OCSPResponseData.swift b/Sources/X509/OCSP/OCSPResponseData.swift index d8cb61d..42a9779 100644 --- a/Sources/X509/OCSP/OCSPResponseData.swift +++ b/Sources/X509/OCSP/OCSPResponseData.swift @@ -32,7 +32,7 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { .sequence } - var version: Int + var version: OCSPVersion var responderID: ResponderID @@ -40,13 +40,13 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { var responses: [OCSPSingleResponse] - var responseExtensions: [Certificate.Extension]? + var responseExtensions: Certificate.Extensions? - init(version: Int = 0, + init(version: OCSPVersion = .v1, responderID: ResponderID, producedAt: GeneralizedTime, responses: [OCSPSingleResponse], - responseExtensions: [Certificate.Extension]?) { + responseExtensions: Certificate.Extensions?) { self.version = version self.responderID = responderID self.producedAt = producedAt @@ -67,14 +67,14 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node) } - return .init(version: version, responderID: responderID, producedAt: producedAt, responses: responses, responseExtensions: responseExtensions) + return .init(version: .init(rawValue: version), responderID: responderID, producedAt: producedAt, responses: responses, responseExtensions: responseExtensions.map { .init($0) }) } } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { try coder.appendConstructedNode(identifier: identifier) { coder in - if self.version != 0 { - try coder.serialize(self.version, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) + if self.version != .v1 { + try coder.serialize(self.version.rawValue, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) } try coder.serialize(self.responderID) diff --git a/Sources/X509/OCSP/OCSPResponseStatus.swift b/Sources/X509/OCSP/OCSPResponseStatus.swift index 6981ab6..26fbbfc 100644 --- a/Sources/X509/OCSP/OCSPResponseStatus.swift +++ b/Sources/X509/OCSP/OCSPResponseStatus.swift @@ -61,25 +61,32 @@ enum OCSPResponseStatus: DERImplicitlyTaggable, Hashable { throw ASN1Error.invalidASN1Object } } + + var integerValue: Int { + switch self { + case .successful: return 0 + case .malformedRequest: return 1 + case .internalError: return 2 + case .tryLater: return 3 + case .sigRequired: return 5 + case .unauthorized: return 6 + } + } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - let integerValue: Int - - switch self { - case .successful: - integerValue = 0 - case .malformedRequest: - integerValue = 1 - case .internalError: - integerValue = 2 - case .tryLater: - integerValue = 3 - case .sigRequired: - integerValue = 5 - case .unauthorized: - integerValue = 6 - } - try integerValue.serialize(into: &coder, withIdentifier: identifier) } } + +extension OCSPResponseStatus: CustomStringConvertible { + var description: String { + switch self { + case .successful: return "successful" + case .malformedRequest: return "malformedRequest" + case .internalError: return "internalError" + case .tryLater: return "tryLater" + case .sigRequired: return "sigRequired" + case .unauthorized: return "unauthorized" + } + } +} From f5ee274d374ab82b4f486949f4c17f04305acb2b Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 12 Jan 2023 11:38:59 +0100 Subject: [PATCH 06/12] Fix test compilation --- Tests/X509Tests/OCSPTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/X509Tests/OCSPTests.swift b/Tests/X509Tests/OCSPTests.swift index b0e2285..add25b9 100644 --- a/Tests/X509Tests/OCSPTests.swift +++ b/Tests/X509Tests/OCSPTests.swift @@ -48,7 +48,7 @@ final class OCSPTests: XCTestCase { hashAlgorithm: .ecdsaWithSHA256, issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]), issuerKeyHash: .init(contentBytes: [10, 11, 12, 13, 14, 15, 16, 17, 18]), - serialNumber: [20, 21, 22, 23, 24, 25, 26, 27, 28] + serialNumber: .init(bytes: [20, 21, 22, 23, 24, 25, 26, 27, 28]) ), singleRequestExtensions: nil )], From 6fe7e0dde5042de6a310de08b8e5aa840d6164cd Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 12 Jan 2023 11:54:57 +0100 Subject: [PATCH 07/12] import Crypto instead of CryptoKit --- Sources/X509/OCSP/OCSPPolicy.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 133b61b..1b45ed1 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import SwiftASN1 -import CryptoKit +import Crypto import Algorithms import protocol Foundation.DataProtocol From 0c8489079854c50335fe0b7338c0eb9da681cbef Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 12 Jan 2023 11:58:22 +0100 Subject: [PATCH 08/12] Drop dependency on swift-algorithms --- Package.swift | 2 -- Sources/X509/OCSP/OCSPPolicy.swift | 5 +++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Package.swift b/Package.swift index bcbe9b5..f6dc568 100644 --- a/Package.swift +++ b/Package.swift @@ -30,7 +30,6 @@ let package = Package( ], dependencies: [ .package(url: "https://github.com/apple/swift-crypto.git", from: "2.2.1"), - .package(url: "https://github.com/apple/swift-algorithms.git", from: "1.0.0"), // swift-asn1 repo is private, so we can't access it anonymously yet // .package(url: "https://github.com/apple/swift-asn1.git", .upToNextMinor(from: "0.3.0")), .package(url: "git@github.com:apple/swift-asn1.git", .upToNextMinor(from: "0.3.0")), @@ -43,7 +42,6 @@ let package = Package( .product(name: "SwiftASN1", package: "swift-asn1"), .product(name: "Crypto", package: "swift-crypto"), .product(name: "_CryptoExtras", package: "swift-crypto"), - .product(name: "Algorithms", package: "swift-algorithms"), ]), .testTarget( name: "X509Tests", diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 1b45ed1..ca01af4 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -14,7 +14,6 @@ import SwiftASN1 import Crypto -import Algorithms import protocol Foundation.DataProtocol public protocol OCSPRequester: Sendable { @@ -83,7 +82,9 @@ public struct OCSPVerifierPolicy: VerifierPolicy { } public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { - for (certificate, issuer) in chain.adjacentPairs() { + for index in chain.dropLast().indices { + let certificate = chain[index] + let issuer = chain[chain.index(after: index)] switch await certificateMeetsPolicyRequirements(certificate, issuer: issuer) { case .meetsPolicy: continue From f0477362d59d5732bcb947db33e083bad8a8e58f Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 12 Jan 2023 22:50:21 +0100 Subject: [PATCH 09/12] Fix TODOs --- Sources/X509/OCSP/OCSPPolicy.swift | 184 ++++++++++++++++++++++------- 1 file changed, 139 insertions(+), 45 deletions(-) diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index ca01af4..5ffe09a 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -15,18 +15,22 @@ import SwiftASN1 import Crypto import protocol Foundation.DataProtocol +import struct Foundation.Date +import typealias Foundation.TimeInterval public protocol OCSPRequester: Sendable { - /// Called with a OCSP Request + /// Called with a OCSP Request. + /// + /// The ``OCSPVerifierPolicy`` will call this method for each certificate witch contains a OCSP URI and will cancel the call if it reaches a deadline. + /// Therefore the implementation of this method should **not** set a deadline on the HTTP request. /// - Parameters: /// - request: DER-encoded request bytes - /// - uri: uri of the + /// - uri: uri of the OCSP responder /// - Returns: DER-encoded response bytes func query(request: [UInt8], uri: String) async throws -> [UInt8] - // TODO: Do we need to handle a request timeout gracefully? - // TODO: If yes, how should this method signal a timeout? throw an error or return an enum with a success and timeout case? } + extension ASN1ObjectIdentifier { static let sha256NoSign: Self = [2, 16, 840, 1, 101, 3, 4, 2, 1] static let sha1NoSign: Self = [1, 3, 14, 3, 2, 26] @@ -35,7 +39,7 @@ extension ASN1ObjectIdentifier { public struct OCSPVerifierPolicy: VerifierPolicy { enum RequestHashAlgorithm { case insecureSha1 - // TODO: can we somehow automatically figure out that a responder will support sha256? + // we can't yet enable sha256 by default but we want in the future case sha256 var oid: ASN1ObjectIdentifier { @@ -76,27 +80,49 @@ public struct OCSPVerifierPolicy: VerifierPolicy { var requester: Requester var requestHashAlgorithm: RequestHashAlgorithm + /// max duration the policy verification is allowed in total + /// + /// This is not the duration for a single OCSP request but the total duration of all OCSP requests. + var maxDuration: TimeInterval + public init(requester: Requester) { self.requester = requester self.requestHashAlgorithm = .insecureSha1 + self.maxDuration = 10 } - public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + public func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + await withDeadline(maxDuration) { + await verifyWithoutDeadline(chain: chain) + } + } + + private func verifyWithoutDeadline(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { for index in chain.dropLast().indices { let certificate = chain[index] let issuer = chain[chain.index(after: index)] - switch await certificateMeetsPolicyRequirements(certificate, issuer: issuer) { + switch await self.certificateMeetsPolicyRequirements(certificate, issuer: issuer) { case .meetsPolicy: continue case .failsToMeetPolicy(let reason): return .failsToMeetPolicy(reason: reason) } } + + do { + let hasRootCertificateOCSPURI = try chain.last?.extensions.authorityInformationAccess?.contains(where: { $0.method == .ocspServer }) ?? false + guard !hasRootCertificateOCSPURI else { + return .failsToMeetPolicy(reason: "root certificate is not allowed to have an OCSP URI") + } + } catch { + return .failsToMeetPolicy(reason: "failed to parse AuthorityInformationAccess extension") + } return .meetsPolicy - // TODO: should we verify that the last certificate doesn't have an OCSP extension set? } - public mutating func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult { + + + private func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult { guard let description = certificate.extensions[oid: .X509ExtensionID.authorityInformationAccess] else { // OCSP not necessary for certificate return .meetsPolicy @@ -105,55 +131,70 @@ public struct OCSPVerifierPolicy: VerifierPolicy { let authorityInformationAccess = try Certificate.Extensions.AuthorityInformationAccess(description) guard let ocspAccessDescription = authorityInformationAccess.first(where: { $0.method == .ocspServer }) else { + // OCSP not necessary for certificate return .meetsPolicy } guard case .uniformResourceIdentifier(let uri) = ocspAccessDescription.location else { return .failsToMeetPolicy(reason: "expected OCSP location to be a URI but got \(ocspAccessDescription.location)") } - - let requestNonce = OCSPNonce() - let request = try request(certificate: certificate, issuer: issuer, nonce: requestNonce) - - var serializer = DER.Serializer() - try serializer.serialize(request) - - let responseDer = try await requester.query(request: serializer.serializedBytes, uri: uri) - - let response = try OCSPResponse(derEncoded: responseDer[...]) - switch response { - case .successful(let basicResponse): - guard basicResponse.responseData.version == .v1 else { - return .failsToMeetPolicy(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") - } - // 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 { - guard requestNonce == responseNonce else { - return .failsToMeetPolicy(reason: "OCSP response nonce does not match request nonce") + do { + let requestNonce = OCSPNonce() + let request = try request(certificate: certificate, issuer: issuer, nonce: requestNonce) + + var serializer = DER.Serializer() + try serializer.serialize(request) + do { + let responseDer = try await requester.query(request: serializer.serializedBytes, uri: uri) + do { + let response = try OCSPResponse(derEncoded: responseDer[...]) + switch response { + case .successful(let basicResponse): + guard basicResponse.responseData.version == .v1 else { + return .failsToMeetPolicy(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") + } + // 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 { + guard requestNonce == responseNonce else { + return .failsToMeetPolicy(reason: "OCSP response nonce does not match request nonce") + } + } + guard let response = basicResponse.responseData.responses.first else { + return .failsToMeetPolicy(reason: "empty OCSP response") + } + switch response.certStatus { + case .good: + switch response.verifyTime() { + case .meetsPolicy: + break + case .failsToMeetPolicy(let reason): + return .failsToMeetPolicy(reason: reason) + } + + // TODO: verify signature + 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") + } + case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: + return .failsToMeetPolicy(reason: "OCSP request failed \(response)") + } + } catch { + return .failsToMeetPolicy(reason: "OCSP deserialisation failed \(error)") } - } - guard let response = basicResponse.responseData.responses.first else { - return .failsToMeetPolicy(reason: "empty OCSP response") - } - switch response.certStatus { - case .good: - // TODO: verify signature - // TODO: verify time + } catch { + // the request can fail for various reasons and we need to tolerate this 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") } - case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: - return .failsToMeetPolicy(reason: "OCSP request failed \(response)") + } catch { + return .failsToMeetPolicy(reason: "OCSP serialisation failed \(error)") } - } catch { - return .failsToMeetPolicy(reason: "OCSP failed: \(error)") + return .failsToMeetPolicy(reason: "failed to decode AuthorityInformationAccess \(error)") } } - func request(certificate: Certificate, issuer: Certificate, nonce: OCSPNonce) throws -> OCSPRequest { OCSPRequest(tbsRequest: OCSPTBSRequest( version: .v1, @@ -170,4 +211,57 @@ public struct OCSPVerifierPolicy: VerifierPolicy { }) )) } + +} + +extension OCSPSingleResponse { + func verifyTime(now: Date = Date()) -> PolicyEvaluationResult { + guard let nextUpdateGeneralizedTime = self.nextUpdate else { + return .failsToMeetPolicy(reason: "OCSP response `nextUpdate` is nil") + } + + guard + let thisUpdate = Date(self.thisUpdate), + let nextUpdate = Date(nextUpdateGeneralizedTime) + else { + return .failsToMeetPolicy(reason: "could not convert time specified in certificate to a `Date`") + } + guard thisUpdate <= now else { + return .failsToMeetPolicy(reason: "OCSP response `thisUpdate` (\(self.thisUpdate) is in the future but should be in the past") + } + + guard nextUpdate >= now else { + return .failsToMeetPolicy(reason: "OCSP response `nextUpdate` (\(nextUpdateGeneralizedTime) is in the past but should be in the future") + } + + return .meetsPolicy + } +} + + +/// Executes the given `task` up to `maxDuration` seconds and cancel it it exceeds this deadline. +/// - Parameters: +/// - maxDuration: max execution duration of +/// - task: the async task to execute and cancel after `maxDuration` seconds +/// - Returns: the result of `task` +private func withDeadline( + _ maxDuration: TimeInterval, + task: @escaping () async -> Result +) async -> Result { + let resultTask = Task { + await task() + } + + let cancelationTask = Task { + // seconds -> milliseconds -> microseconds -> nanoseconds + try await Task.sleep(nanoseconds: UInt64(maxDuration * 1000 * 1000 * 1000)) + resultTask.cancel() + } + defer { cancelationTask.cancel() } + + return await withTaskCancellationHandler { + await resultTask.value + } onCancel: { + resultTask.cancel() + } } From a6e6d63f3c4ef48d0ece2efc4726c1c355d379e8 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Fri, 13 Jan 2023 11:35:01 +0100 Subject: [PATCH 10/12] Get rid of do catch hell and split into multiple functions --- Sources/X509/OCSP/OCSPPolicy.swift | 178 +++++++++++++++++------------ 1 file changed, 104 insertions(+), 74 deletions(-) diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 5ffe09a..13204aa 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -93,11 +93,11 @@ public struct OCSPVerifierPolicy: VerifierPolicy { public func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { await withDeadline(maxDuration) { - await verifyWithoutDeadline(chain: chain) + await chainMeetsPolicyRequirementsWithoutDeadline(chain: chain) } } - private func verifyWithoutDeadline(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + private func chainMeetsPolicyRequirementsWithoutDeadline(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { for index in chain.dropLast().indices { let certificate = chain[index] let issuer = chain[chain.index(after: index)] @@ -110,7 +110,7 @@ public struct OCSPVerifierPolicy: VerifierPolicy { } do { - let hasRootCertificateOCSPURI = try chain.last?.extensions.authorityInformationAccess?.contains(where: { $0.method == .ocspServer }) ?? false + let hasRootCertificateOCSPURI = try chain.last?.extensions.authorityInformationAccess?.contains { $0.method == .ocspServer } ?? false guard !hasRootCertificateOCSPURI else { return .failsToMeetPolicy(reason: "root certificate is not allowed to have an OCSP URI") } @@ -127,91 +127,121 @@ public struct OCSPVerifierPolicy: VerifierPolicy { // OCSP not necessary for certificate return .meetsPolicy } + let authorityInformationAccess: Certificate.Extensions.AuthorityInformationAccess do { - let authorityInformationAccess = try Certificate.Extensions.AuthorityInformationAccess(description) - - guard let ocspAccessDescription = authorityInformationAccess.first(where: { $0.method == .ocspServer }) else { - // OCSP not necessary for certificate - return .meetsPolicy - } - - guard case .uniformResourceIdentifier(let uri) = ocspAccessDescription.location else { - return .failsToMeetPolicy(reason: "expected OCSP location to be a URI but got \(ocspAccessDescription.location)") - } - do { - let requestNonce = OCSPNonce() - let request = try request(certificate: certificate, issuer: issuer, nonce: requestNonce) - - var serializer = DER.Serializer() - try serializer.serialize(request) - do { - let responseDer = try await requester.query(request: serializer.serializedBytes, uri: uri) - do { - let response = try OCSPResponse(derEncoded: responseDer[...]) - switch response { - case .successful(let basicResponse): - guard basicResponse.responseData.version == .v1 else { - return .failsToMeetPolicy(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") - } - // 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 { - guard requestNonce == responseNonce else { - return .failsToMeetPolicy(reason: "OCSP response nonce does not match request nonce") - } - } - guard let response = basicResponse.responseData.responses.first else { - return .failsToMeetPolicy(reason: "empty OCSP response") - } - switch response.certStatus { - case .good: - switch response.verifyTime() { - case .meetsPolicy: - break - case .failsToMeetPolicy(let reason): - return .failsToMeetPolicy(reason: reason) - } - - // TODO: verify signature - 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") - } - case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: - return .failsToMeetPolicy(reason: "OCSP request failed \(response)") - } - } catch { - return .failsToMeetPolicy(reason: "OCSP deserialisation failed \(error)") - } - } catch { - // the request can fail for various reasons and we need to tolerate this - return .meetsPolicy - } - } catch { - return .failsToMeetPolicy(reason: "OCSP serialisation failed \(error)") - } + authorityInformationAccess = try .init(description) } catch { return .failsToMeetPolicy(reason: "failed to decode AuthorityInformationAccess \(error)") } + guard let ocspAccessDescription = authorityInformationAccess.first(where: { $0.method == .ocspServer }) else { + // OCSP not necessary for certificate + return .meetsPolicy + } + + guard case .uniformResourceIdentifier(let responderURI) = ocspAccessDescription.location else { + return .failsToMeetPolicy(reason: "expected OCSP location to be a URI but got \(ocspAccessDescription.location)") + } + + let certID: OCSPCertID + do { + certID = try self.certID(certificate: certificate, issuer: issuer) + } catch { + return .failsToMeetPolicy(reason: "failed to create OCSPCertID \(error)") + } + + return await queryAndVerifyCertificateStatus(for: certID, responderURI: responderURI) } - func request(certificate: Certificate, issuer: Certificate, nonce: OCSPNonce) throws -> OCSPRequest { + + private func queryAndVerifyCertificateStatus(for certID: OCSPCertID, responderURI: String) async -> PolicyEvaluationResult { + let requestNonce = OCSPNonce() + let requestBytes: [UInt8] + do { + let request = try request(certID: certID, nonce: requestNonce) + var serializer = DER.Serializer() + try serializer.serialize(request) + requestBytes = serializer.serializedBytes + } catch { + return .failsToMeetPolicy(reason: "failed to create OCSPRequest \(error)") + } + + let responseDerEncoded: [UInt8] + do { + responseDerEncoded = try await requester.query(request: requestBytes, uri: responderURI) + } catch { + // the request can fail for various reasons and we need to tolerate this + return .meetsPolicy + } + let response: OCSPResponse + do { + response = try OCSPResponse(derEncoded: responseDerEncoded[...]) + } catch { + return .failsToMeetPolicy(reason: "OCSP deserialisation failed \(error)") + } + + return verifyResponse(response, requestedCertID: certID, requestNonce: requestNonce) + } + + private func verifyResponse(_ response: OCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce) -> 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 { + // 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 { + guard requestNonce == responseNonce else { + 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") + } + + switch response.certStatus { + case .good: + switch response.verifyTime() { + case .meetsPolicy: + break + case .failsToMeetPolicy(let reason): + return .failsToMeetPolicy(reason: reason) + } + + // TODO: verify signature + 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") + } + } + } + + func certID(certificate: Certificate, issuer: Certificate) throws -> OCSPCertID { + OCSPCertID( + hashAlgorithm: .init(algorithm: requestHashAlgorithm.oid, parameters: nil), + issuerNameHash: .init(contentBytes: try requestHashAlgorithm.issuerNameHashed(issuer)), + issuerKeyHash: .init(contentBytes: requestHashAlgorithm.issuerPublicKeyHashed(issuer)), + serialNumber: certificate.serialNumber + ) + } + + func request(certID: OCSPCertID, nonce: OCSPNonce) throws -> OCSPRequest { OCSPRequest(tbsRequest: OCSPTBSRequest( version: .v1, requestList: [ - OCSPSingleRequest(certID: OCSPCertID( - hashAlgorithm: .init(algorithm: requestHashAlgorithm.oid, parameters: nil), - issuerNameHash: .init(contentBytes: try requestHashAlgorithm.issuerNameHashed(issuer)), - issuerKeyHash: .init(contentBytes: requestHashAlgorithm.issuerPublicKeyHashed(issuer)), - serialNumber: certificate.serialNumber - )) + OCSPSingleRequest(certID: certID) ], requestExtensions: try .init(builder: { nonce }) )) } - } extension OCSPSingleResponse { From 14b953a64e33c0d4c29d8b96b45df9e139c81321 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Fri, 13 Jan 2023 11:53:57 +0100 Subject: [PATCH 11/12] Remove policy for now and push that to another PR --- Sources/X509/OCSP/OCSPPolicy.swift | 297 ----------------------------- 1 file changed, 297 deletions(-) delete mode 100644 Sources/X509/OCSP/OCSPPolicy.swift diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift deleted file mode 100644 index 13204aa..0000000 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ /dev/null @@ -1,297 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCertificates open source project -// -// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import SwiftASN1 -import Crypto -import protocol Foundation.DataProtocol -import struct Foundation.Date -import typealias Foundation.TimeInterval - -public protocol OCSPRequester: Sendable { - /// Called with a OCSP Request. - /// - /// The ``OCSPVerifierPolicy`` will call this method for each certificate witch contains a OCSP URI and will cancel the call if it reaches a deadline. - /// Therefore the implementation of this method should **not** set a deadline on the HTTP request. - /// - Parameters: - /// - request: DER-encoded request bytes - /// - uri: uri of the OCSP responder - /// - Returns: DER-encoded response bytes - func query(request: [UInt8], uri: String) async throws -> [UInt8] -} - - -extension ASN1ObjectIdentifier { - static let sha256NoSign: Self = [2, 16, 840, 1, 101, 3, 4, 2, 1] - static let sha1NoSign: Self = [1, 3, 14, 3, 2, 26] -} - -public struct OCSPVerifierPolicy: VerifierPolicy { - enum RequestHashAlgorithm { - case insecureSha1 - // we can't yet enable sha256 by default but we want in the future - case sha256 - - var oid: ASN1ObjectIdentifier { - switch self { - case .insecureSha1: return .sha1NoSign - case .sha256: return .sha256NoSign - } - } - private func hashed(_ value: some DataProtocol) -> ArraySlice { - switch self { - case .insecureSha1: - var hashAlgorithm = Insecure.SHA1() - hashAlgorithm.update(data: value) - return Array(hashAlgorithm.finalize())[...] - case .sha256: - var hashAlgorithm = SHA256() - hashAlgorithm.update(data: value) - return Array(hashAlgorithm.finalize())[...] - } - } - - fileprivate func issuerNameHashed(_ certificate: Certificate) throws -> ArraySlice { - /// issuerNameHash is the hash of the issuer's distinguished name - /// (DN). The hash shall be calculated over the DER encoding of the - /// issuer's name field in the certificate being checked. - var serializer = DER.Serializer() - try serializer.serialize(certificate.subject) - return hashed(serializer.serializedBytes) - } - - fileprivate func issuerPublicKeyHashed(_ certificate: Certificate) -> ArraySlice { - /// issuerKeyHash is the hash of the issuer's public key. The hash - /// shall be calculated over the value (excluding tag and length) of - /// the subject public key field in the issuer's certificate. - hashed(SubjectPublicKeyInfo(certificate.publicKey).key.bytes) - } - } - var requester: Requester - var requestHashAlgorithm: RequestHashAlgorithm - - /// max duration the policy verification is allowed in total - /// - /// This is not the duration for a single OCSP request but the total duration of all OCSP requests. - var maxDuration: TimeInterval - - public init(requester: Requester) { - self.requester = requester - self.requestHashAlgorithm = .insecureSha1 - self.maxDuration = 10 - } - - public func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { - await withDeadline(maxDuration) { - await chainMeetsPolicyRequirementsWithoutDeadline(chain: chain) - } - } - - private func chainMeetsPolicyRequirementsWithoutDeadline(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { - for index in chain.dropLast().indices { - let certificate = chain[index] - let issuer = chain[chain.index(after: index)] - switch await self.certificateMeetsPolicyRequirements(certificate, issuer: issuer) { - case .meetsPolicy: - continue - case .failsToMeetPolicy(let reason): - return .failsToMeetPolicy(reason: reason) - } - } - - do { - let hasRootCertificateOCSPURI = try chain.last?.extensions.authorityInformationAccess?.contains { $0.method == .ocspServer } ?? false - guard !hasRootCertificateOCSPURI else { - return .failsToMeetPolicy(reason: "root certificate is not allowed to have an OCSP URI") - } - } catch { - return .failsToMeetPolicy(reason: "failed to parse AuthorityInformationAccess extension") - } - return .meetsPolicy - } - - - - private func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult { - guard let description = certificate.extensions[oid: .X509ExtensionID.authorityInformationAccess] else { - // OCSP not necessary for certificate - return .meetsPolicy - } - let authorityInformationAccess: Certificate.Extensions.AuthorityInformationAccess - do { - authorityInformationAccess = try .init(description) - } catch { - return .failsToMeetPolicy(reason: "failed to decode AuthorityInformationAccess \(error)") - } - guard let ocspAccessDescription = authorityInformationAccess.first(where: { $0.method == .ocspServer }) else { - // OCSP not necessary for certificate - return .meetsPolicy - } - - guard case .uniformResourceIdentifier(let responderURI) = ocspAccessDescription.location else { - return .failsToMeetPolicy(reason: "expected OCSP location to be a URI but got \(ocspAccessDescription.location)") - } - - let certID: OCSPCertID - do { - certID = try self.certID(certificate: certificate, issuer: issuer) - } catch { - return .failsToMeetPolicy(reason: "failed to create OCSPCertID \(error)") - } - - return await queryAndVerifyCertificateStatus(for: certID, responderURI: responderURI) - } - - private func queryAndVerifyCertificateStatus(for certID: OCSPCertID, responderURI: String) async -> PolicyEvaluationResult { - let requestNonce = OCSPNonce() - let requestBytes: [UInt8] - do { - let request = try request(certID: certID, nonce: requestNonce) - var serializer = DER.Serializer() - try serializer.serialize(request) - requestBytes = serializer.serializedBytes - } catch { - return .failsToMeetPolicy(reason: "failed to create OCSPRequest \(error)") - } - - let responseDerEncoded: [UInt8] - do { - responseDerEncoded = try await requester.query(request: requestBytes, uri: responderURI) - } catch { - // the request can fail for various reasons and we need to tolerate this - return .meetsPolicy - } - let response: OCSPResponse - do { - response = try OCSPResponse(derEncoded: responseDerEncoded[...]) - } catch { - return .failsToMeetPolicy(reason: "OCSP deserialisation failed \(error)") - } - - return verifyResponse(response, requestedCertID: certID, requestNonce: requestNonce) - } - - private func verifyResponse(_ response: OCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce) -> 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 { - // 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 { - guard requestNonce == responseNonce else { - 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") - } - - switch response.certStatus { - case .good: - switch response.verifyTime() { - case .meetsPolicy: - break - case .failsToMeetPolicy(let reason): - return .failsToMeetPolicy(reason: reason) - } - - // TODO: verify signature - 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") - } - } - } - - func certID(certificate: Certificate, issuer: Certificate) throws -> OCSPCertID { - OCSPCertID( - hashAlgorithm: .init(algorithm: requestHashAlgorithm.oid, parameters: nil), - issuerNameHash: .init(contentBytes: try requestHashAlgorithm.issuerNameHashed(issuer)), - issuerKeyHash: .init(contentBytes: requestHashAlgorithm.issuerPublicKeyHashed(issuer)), - serialNumber: certificate.serialNumber - ) - } - - func request(certID: OCSPCertID, nonce: OCSPNonce) throws -> OCSPRequest { - OCSPRequest(tbsRequest: OCSPTBSRequest( - version: .v1, - requestList: [ - OCSPSingleRequest(certID: certID) - ], - requestExtensions: try .init(builder: { - nonce - }) - )) - } -} - -extension OCSPSingleResponse { - func verifyTime(now: Date = Date()) -> PolicyEvaluationResult { - guard let nextUpdateGeneralizedTime = self.nextUpdate else { - return .failsToMeetPolicy(reason: "OCSP response `nextUpdate` is nil") - } - - guard - let thisUpdate = Date(self.thisUpdate), - let nextUpdate = Date(nextUpdateGeneralizedTime) - else { - return .failsToMeetPolicy(reason: "could not convert time specified in certificate to a `Date`") - } - guard thisUpdate <= now else { - return .failsToMeetPolicy(reason: "OCSP response `thisUpdate` (\(self.thisUpdate) is in the future but should be in the past") - } - - guard nextUpdate >= now else { - return .failsToMeetPolicy(reason: "OCSP response `nextUpdate` (\(nextUpdateGeneralizedTime) is in the past but should be in the future") - } - - return .meetsPolicy - } -} - - -/// Executes the given `task` up to `maxDuration` seconds and cancel it it exceeds this deadline. -/// - Parameters: -/// - maxDuration: max execution duration of -/// - task: the async task to execute and cancel after `maxDuration` seconds -/// - Returns: the result of `task` -private func withDeadline( - _ maxDuration: TimeInterval, - task: @escaping () async -> Result -) async -> Result { - let resultTask = Task { - await task() - } - - let cancelationTask = Task { - // seconds -> milliseconds -> microseconds -> nanoseconds - try await Task.sleep(nanoseconds: UInt64(maxDuration * 1000 * 1000 * 1000)) - resultTask.cancel() - } - defer { cancelationTask.cancel() } - - return await withTaskCancellationHandler { - await resultTask.value - } onCancel: { - resultTask.cancel() - } -} From f068d90254f2367c630e08e16f094c68336218ac Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Fri, 20 Jan 2023 10:54:19 +0100 Subject: [PATCH 12/12] Fix review comments --- Sources/X509/CertificateSerialNumber.swift | 20 +--------- Sources/X509/OCSP/OCSPNonce.swift | 2 +- Sources/X509/OCSP/OCSPResponse.swift | 23 ++++++----- Sources/X509/OCSP/OCSPResponseData.swift | 2 +- Sources/X509/OCSP/OCSPResponseStatus.swift | 2 +- Sources/X509/OCSP/OCSPSignature.swift | 4 +- Sources/X509/OCSP/OCSPSingleResponse.swift | 2 +- Sources/X509/OCSP/OCSPTBSRequest.swift | 2 +- .../X509/RandomNumberGenerator+bytes.swift | 39 +++++++++++++++++++ 9 files changed, 60 insertions(+), 36 deletions(-) create mode 100644 Sources/X509/RandomNumberGenerator+bytes.swift diff --git a/Sources/X509/CertificateSerialNumber.swift b/Sources/X509/CertificateSerialNumber.swift index b51953f..2305eca 100644 --- a/Sources/X509/CertificateSerialNumber.swift +++ b/Sources/X509/CertificateSerialNumber.swift @@ -64,13 +64,7 @@ extension Certificate { @inlinable public init() { var rng = SystemRandomNumberGenerator() - var bytes = [UInt8]() - - while bytes.count < 20 { - bytes.appendLittleEndianBytes(rng.next()) - } - - self.bytes = bytes[..<20] + self.bytes = rng.bytes(count: 20) } } } @@ -84,15 +78,3 @@ extension Certificate.SerialNumber: CustomStringConvertible { return self.bytes.lazy.map { String($0, radix: 16) }.joined(separator: ":") } } - -extension Array where Element == UInt8 { - @inlinable - mutating func appendLittleEndianBytes(_ number: UInt64) { - let number = number.littleEndian - - for byte in 0..<(MemoryLayout.size) { - let shifted = number >> (byte * 8) - self.append(UInt8(truncatingIfNeeded: shifted)) - } - } -} diff --git a/Sources/X509/OCSP/OCSPNonce.swift b/Sources/X509/OCSP/OCSPNonce.swift index 872ecaf..46deff5 100644 --- a/Sources/X509/OCSP/OCSPNonce.swift +++ b/Sources/X509/OCSP/OCSPNonce.swift @@ -32,7 +32,7 @@ struct OCSPNonce: DERImplicitlyTaggable, Hashable, Sendable { } init(generator: inout some RandomNumberGenerator) { - self.rawValue = .init(contentBytes: (0..<32).map { _ in UInt8.random(in: 0...255, using: &generator) }[...] ) + self.rawValue = .init(contentBytes: generator.bytes(count: 32)) } init(_ ext: Certificate.Extension) throws { diff --git a/Sources/X509/OCSP/OCSPResponse.swift b/Sources/X509/OCSP/OCSPResponse.swift index a1372ac..9f166ac 100644 --- a/Sources/X509/OCSP/OCSPResponse.swift +++ b/Sources/X509/OCSP/OCSPResponse.swift @@ -50,23 +50,26 @@ enum OCSPResponse: DERImplicitlyTaggable, Hashable { } return .successful(try BasicOCSPResponse(derEncoded: responseBytes.response.bytes)) case .malformedRequest: - guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } - return .malformedRequest + return try .init(unsuccessfulStatus: .malformedRequest, responseBytes: responseBytes) case .internalError: - guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } - return .internalError + return try .init(unsuccessfulStatus: .internalError, responseBytes: responseBytes) case .tryLater: - guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } - return .tryLater + return try .init(unsuccessfulStatus: .tryLater, responseBytes: responseBytes) case .sigRequired: - guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } - return .sigRequired + return try .init(unsuccessfulStatus: .sigRequired, responseBytes: responseBytes) case .unauthorized: - guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } - return .unauthorized + return try .init(unsuccessfulStatus: .unauthorized, responseBytes: responseBytes) } } } + + private init(unsuccessfulStatus: OCSPResponse, responseBytes: OCSPResponseBytes?) throws { + if case .successful = unsuccessfulStatus { + preconditionFailure("this init is not allowed to be called with a successful response status") + } + guard responseBytes == nil else { throw ASN1Error.invalidASN1Object } + self = unsuccessfulStatus + } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { try coder.appendConstructedNode(identifier: identifier) { coder in diff --git a/Sources/X509/OCSP/OCSPResponseData.swift b/Sources/X509/OCSP/OCSPResponseData.swift index 42a9779..45bef92 100644 --- a/Sources/X509/OCSP/OCSPResponseData.swift +++ b/Sources/X509/OCSP/OCSPResponseData.swift @@ -46,7 +46,7 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable { responderID: ResponderID, producedAt: GeneralizedTime, responses: [OCSPSingleResponse], - responseExtensions: Certificate.Extensions?) { + responseExtensions: Certificate.Extensions? = nil) { self.version = version self.responderID = responderID self.producedAt = producedAt diff --git a/Sources/X509/OCSP/OCSPResponseStatus.swift b/Sources/X509/OCSP/OCSPResponseStatus.swift index 26fbbfc..444d9bb 100644 --- a/Sources/X509/OCSP/OCSPResponseStatus.swift +++ b/Sources/X509/OCSP/OCSPResponseStatus.swift @@ -74,7 +74,7 @@ enum OCSPResponseStatus: DERImplicitlyTaggable, Hashable { } func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws { - try integerValue.serialize(into: &coder, withIdentifier: identifier) + try self.integerValue.serialize(into: &coder, withIdentifier: identifier) } } diff --git a/Sources/X509/OCSP/OCSPSignature.swift b/Sources/X509/OCSP/OCSPSignature.swift index b96f70f..36ebe25 100644 --- a/Sources/X509/OCSP/OCSPSignature.swift +++ b/Sources/X509/OCSP/OCSPSignature.swift @@ -40,12 +40,12 @@ struct OCSPSignature: DERImplicitlyTaggable, Hashable { init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { self = try DER.sequence(derEncoded, identifier: identifier) { nodes in - let algorithmIIdentifier = try AlgorithmIdentifier(derEncoded: &nodes) + let algorithmIdentifier = try AlgorithmIdentifier(derEncoded: &nodes) let signature = try ASN1BitString(derEncoded: &nodes) let certs = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in try DER.sequence(of: Certificate.self, identifier: .sequence, rootNode: node) } - return .init(algorithmIIdentifier: algorithmIIdentifier, signature: signature, certs: certs) + return .init(algorithmIIdentifier: algorithmIdentifier, signature: signature, certs: certs) } } diff --git a/Sources/X509/OCSP/OCSPSingleResponse.swift b/Sources/X509/OCSP/OCSPSingleResponse.swift index 5282230..4d329c4 100644 --- a/Sources/X509/OCSP/OCSPSingleResponse.swift +++ b/Sources/X509/OCSP/OCSPSingleResponse.swift @@ -44,7 +44,7 @@ struct OCSPSingleResponse: DERImplicitlyTaggable, Hashable { certStatus: OCSPCertStatus, thisUpdate: GeneralizedTime, nextUpdate: GeneralizedTime?, - extensions: [Certificate.Extension]?) { + extensions: [Certificate.Extension]? = nil) { self.certID = certID self.certStatus = certStatus self.thisUpdate = thisUpdate diff --git a/Sources/X509/OCSP/OCSPTBSRequest.swift b/Sources/X509/OCSP/OCSPTBSRequest.swift index a00758b..990322c 100644 --- a/Sources/X509/OCSP/OCSPTBSRequest.swift +++ b/Sources/X509/OCSP/OCSPTBSRequest.swift @@ -50,7 +50,7 @@ struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable { let requestorName = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { try GeneralName(derEncoded: $0) } - let requestList = try DER.sequence(of: OCSPSingleRequest.self,identifier: .sequence, nodes: &nodes) + let requestList = try DER.sequence(of: OCSPSingleRequest.self, identifier: .sequence, nodes: &nodes) let extensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific) { try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: $0) } diff --git a/Sources/X509/RandomNumberGenerator+bytes.swift b/Sources/X509/RandomNumberGenerator+bytes.swift new file mode 100644 index 0000000..c0f5ab7 --- /dev/null +++ b/Sources/X509/RandomNumberGenerator+bytes.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +extension RandomNumberGenerator { + @inlinable + internal mutating func bytes(count: Int) -> ArraySlice { + precondition(count >= 0) + var bytes = [UInt8]() + + while bytes.count < count { + bytes.appendLittleEndianBytes(self.next()) + } + + return bytes[...size) { + let shifted = number >> (byte * 8) + self.append(UInt8(truncatingIfNeeded: shifted)) + } + } +}