Merge pull request #24 from apple/cb-leafs-as-roots

Handle leaves as trust roots
This commit is contained in:
Cory Benfield authored and GitHub committed 2023-03-06 13:00:56 +00:00
commit a7735a35f9
3 files changed
+109 -3

No files matched your search

@@ -49,4 +49,9 @@ public struct CertificateStore: Sendable, Hashable {
self._certificates[subject] = newValue
}
}
@inlinable
func contains(_ certificate: Certificate) -> Bool {
return self[certificate.subject]?.contains(certificate) ?? false
}
}
+23 -3
View File
@@ -28,6 +28,25 @@ public struct Verifier {
var policyFailures: [VerificationResult.PolicyFailure] = []
// First check: is this leaf _already in_ the certificate store? If it is, we can just trust it directly.
//
// Note that this requires an _exact match_: if there isn't an exact match, we'll fall back to chain building,
// which may let us chain through another variant of this certificate and build a valid chain. This is a very
// deliberate choice: certificates that assert the same combination of (subject, public key, SAN) but different
// extensions or policies should not be tolerated by this check, and will be ignored.
if self.rootCertificates.contains(leafCertificate) {
let unverifiedChain = UnverifiedCertificateChain([leafCertificate])
switch await self.policy.chainMeetsPolicyRequirements(chain: unverifiedChain) {
case .meetsPolicy:
// We're good!
return .validCertificate(unverifiedChain.certificates)
case .failsToMeetPolicy(reason: let reason):
policyFailures.append(VerificationResult.PolicyFailure(chain: unverifiedChain, policyFailureReason: reason))
}
}
// This is essentially a DFS of the certificate tree. We attempt to iteratively build up possible chains.
while let nextPartialCandidate = partialChains.popLast() {
// We want to search for parents. Our preferred parent comes from the root store, as this will potentially
@@ -180,9 +199,10 @@ extension Certificate {
extension UnverifiedCertificateChain {
fileprivate init(chain: CandidatePartialChain, root: Certificate) {
self = .init(chain.chain)
self.certificates.append(chain.currentTip)
self.certificates.append(root)
var certificates = chain.chain
certificates.append(chain.currentTip)
certificates.append(root)
self = .init(certificates)
}
}
+81
View File
@@ -232,6 +232,33 @@ final class VerifierTests: XCTestCase {
)
}()
private static let isolatedSelfSignedCertKey = P256.Signing.PrivateKey()
private static let isolatedSelfSignedCert: Certificate = {
let isolatedSelfSignedCertName = try! DistinguishedName {
CountryName("US")
OrganizationName("Apple")
CommonName("Isolated Self-Signed Cert")
}
return try! Certificate(
version: .v3,
serialNumber: .init(),
publicKey: .init(isolatedSelfSignedCertKey.publicKey),
notValidBefore: Date() - .days(365),
notValidAfter: Date() + .days(365),
issuer: isolatedSelfSignedCertName,
subject: isolatedSelfSignedCertName,
signatureAlgorithm: .ecdsaWithSHA256,
extensions: Certificate.Extensions {
Critical(
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
},
issuerPrivateKey: .init(isolatedSelfSignedCertKey)
)
}()
// MARK: Deeply insane PKI
//
// This section defines a deeply insane PKI. The PKI has one root CA and two intermediate CAs, and looks roughly like this:
@@ -598,6 +625,60 @@ final class VerifierTests: XCTestCase {
XCTAssertEqual(chain, [Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1, Self.ca1])
}
func testSelfSignedCertsAreRejectedWhenNotInTheTrustStore() async throws {
let roots = CertificateStore([Self.ca1])
var verifier = Verifier(rootCertificates: roots, policy: PolicySet(policies: []))
let result = await verifier.validate(leafCertificate: Self.isolatedSelfSignedCert, intermediates: CertificateStore([Self.intermediate1]))
guard case .couldNotValidate = result else {
XCTFail("Incorrectly validated: \(result)")
return
}
}
func testSelfSignedCertsAreTrustedWhenInTrustStore() async throws {
let roots = CertificateStore([Self.ca1, Self.isolatedSelfSignedCert])
var verifier = Verifier(rootCertificates: roots, policy: PolicySet(policies: []))
let result = await verifier.validate(leafCertificate: Self.isolatedSelfSignedCert, intermediates: CertificateStore([Self.intermediate1]))
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
return
}
XCTAssertEqual(chain, [Self.isolatedSelfSignedCert])
}
func testTrustRootsCanBeNonSelfSignedLeaves() async throws {
let roots = CertificateStore([Self.localhostLeaf])
var verifier = Verifier(rootCertificates: roots, policy: PolicySet(policies: []))
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]))
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
return
}
XCTAssertEqual(chain, [Self.localhostLeaf])
}
func testTrustRootsCanBeNonSelfSignedIntermediates() async throws {
let roots = CertificateStore([Self.intermediate1])
var verifier = Verifier(rootCertificates: roots, policy: PolicySet(policies: []))
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]))
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
return
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1])
}
}
fileprivate struct FailIfCalledPolicy: VerifierPolicy {