From 4975de4e97c9b92fbd2b074a7d94b06e28cea478 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Mon, 22 Apr 2024 16:24:19 +0100 Subject: [PATCH] Add support for validating server hostnames and IP addresses (#171) Motivation To make Swift Certificates useful for the Web PKI it's vital that we can validate that a particular certificate is authoritative for a specific domain. This requires a new verifier policy. Modifications Added ServerIdentityPolicy Added tests Result We can validate the identity of remote servers. --- Sources/X509/CMakeLists.txt | 1 + Sources/X509/Docs.docc/index.md | 23 + .../X509/Verifier/ServerIdentityPolicy.swift | 524 ++++++++++++++ .../X509Tests/ServerIdentityPolicyTests.swift | 657 ++++++++++++++++++ scripts/soundness.sh | 2 +- 5 files changed, 1206 insertions(+), 1 deletion(-) create mode 100644 Sources/X509/Verifier/ServerIdentityPolicy.swift create mode 100644 Tests/X509Tests/ServerIdentityPolicyTests.swift diff --git a/Sources/X509/CMakeLists.txt b/Sources/X509/CMakeLists.txt index b66b81e..fd8afb2 100644 --- a/Sources/X509/CMakeLists.txt +++ b/Sources/X509/CMakeLists.txt @@ -96,6 +96,7 @@ add_library(X509 "Verifier/RFC5280/RFC5280Policy.swift" "Verifier/RFC5280/URIConstraints.swift" "Verifier/RFC5280/VersionPolicy.swift" + "Verifier/ServerIdentityPolicy.swift" "Verifier/TrustRootLoading.swift" "Verifier/UnverifiedChain.swift" "Verifier/VerificationDiagnostic.swift" diff --git a/Sources/X509/Docs.docc/index.md b/Sources/X509/Docs.docc/index.md index c8979cc..e02c988 100644 --- a/Sources/X509/Docs.docc/index.md +++ b/Sources/X509/Docs.docc/index.md @@ -76,6 +76,29 @@ certificate authorities, authenticating peers, and more. - ``StateOrProvinceName`` - ``StreetAddress`` +### Verifying Certificates + +- ``Verifier`` +- ``VerifierPolicy`` +- ``PolicyBuilder`` +- ``PolicyFailureReason`` +- ``AnyPolicy`` +- ``CertificateStore`` +- ``UnverifiedCertificateChain`` +- ``VerificationDiagnostic`` + +### Pre-implemented Verifier Policies + +- ``RFC5280Policy`` +- ``ServerIdentityPolicy`` +- ``OCSPVerifierPolicy`` + +### OCSP Policy Helpers + +- ``OCSPRequester`` +- ``OCSPFailureMode`` +- ``OCSPRequesterQueryResult`` + ### Errors - ``CertificateError`` diff --git a/Sources/X509/Verifier/ServerIdentityPolicy.swift b/Sources/X509/Verifier/ServerIdentityPolicy.swift new file mode 100644 index 0000000..4a796b9 --- /dev/null +++ b/Sources/X509/Verifier/ServerIdentityPolicy.swift @@ -0,0 +1,524 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2024 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 Foundation +import SwiftASN1 + +/// A ``VerifierPolicy`` that validates that the leaf certificate is authoritative +/// for a given hostname or IP address. +/// +/// This policy is most commonly used to validate the leaf certificate presented by a server +/// during a TLS handshake. +/// +/// This policy implements the logic for service validation as specified by +/// RFC 6125 (https://tools.ietf.org/search/rfc6125), which loosely speaking +/// defines the common algorithm used for validating that an X.509 certificate +/// is valid for a given service +public struct ServerIdentityPolicy { + @usableFromInline + var serverHostname: LazyServerHostname? + + // This field is `var` becuase we lazily convert from String to something more useful, if needed. + @usableFromInline + var serverIP: LazyIPAddress? + + /// Constructs a new ``ServerIdentityPolicy``. + /// + /// - parameters: + /// - serverHostname: The hostname used to connect to the server. + /// - serverIP: The IP address of the server, if known. + @inlinable + public init( + serverHostname: String?, + serverIP: String? + ) { + self.serverHostname = serverHostname.map { .string($0) } + self.serverIP = serverIP.map { .string($0) } + } +} + +extension ServerIdentityPolicy: VerifierPolicy { + @inlinable + public var verifyingCriticalExtensions: [ASN1ObjectIdentifier] { + [.X509ExtensionID.subjectAlternativeName] + } + + @inlinable + public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) -> PolicyEvaluationResult { + let targetIP = self.serverIP.convert() + let targetHostname = self.serverHostname.convert() + + // We only validate the leaf node in this policy. + // + // Note that we also deliberately call a non-inlinable method here. That's to avoid + // littering the repo with things that shouldn't be at internal visibility. As a practical + // matter the worst possible outcome here is some excess retain/releases, none of the + // code is generic, so this is basically acceptable. + return chain.leaf.hasValidIdentityForService( + serverHostname: targetHostname, + serverIP: targetIP + ) + } +} + +extension ServerIdentityPolicy { + @usableFromInline + enum IPAddress { + case v4(in_addr) + case v6(in6_addr) + } + + @usableFromInline + enum LazyIPAddress { + case ipAddress(IPAddress) + case string(String) + } + + @usableFromInline + enum LazyServerHostname { + case string(String) + case prepared(PreparedServerHostname) + } + + @usableFromInline + struct PreparedServerHostname { + var bytes: ArraySlice + var firstPeriodIndex: ArraySlice.Index? + + /// Creates an `PreparedServerHostname` + /// + /// This consists of a non-NULL-terminated sequence of ASCII bytes and the index of the + /// first period in that hostname. + /// + /// If the string this method is called on contains non-ACSII code points, this constructor fails. + /// + /// This constructor exists to avoid doing repeated loops over the string buffer. + /// In a naive implementation we'd loop at least four times: once to lowercase + /// the string, once to get a buffer pointer to a contiguous buffer, once + /// to confirm the string is ASCII, and once to find the first period for matching wildcards. + /// Here we can do that all in one loop. + @usableFromInline + init?(lowercaseASCIIBytes string: String) { + let utf8View = string.utf8 + self.firstPeriodIndex = nil + + var value: [UInt8] = [] + value.reserveCapacity(utf8View.count) + + for codeUnit in utf8View { + guard codeUnit.isValidDNSCharacter else { + return nil + } + + if self.firstPeriodIndex == nil && codeUnit == asciiPeriod { + // This is tricky and not generically correct, but it's safe for Array. + self.firstPeriodIndex = value.endIndex + } + + // We know we have only ASCII printables, we can safely unconditionally set the 6 bit to 1 to lowercase. + value.append(codeUnit | (0x20)) + } + + self.bytes = value[...] + + // Strip trailing period. + if self.bytes.last == asciiPeriod { + self.bytes = self.bytes.dropLast() + } + } + } + + // This should really be an init, but weird compiler issues have prevented it from being one. + @_spi(Testing) + public static func parsingIPv4Address(_ string: String) -> in_addr? { + var value = in_addr() + + let rc = string.withCString { + inet_pton(AF_INET, $0, &value) + } + + if rc != 1 { return nil } + return value + } + + // This should really be an init, but weird compiler issues have prevented it from being one. + @_spi(Testing) + public static func parsingIPv6Address(_ string: String) -> in6_addr? { + var value = in6_addr() + + let rc = string.withCString { + inet_pton(AF_INET6, $0, &value) + } + + if rc != 1 { return nil } + return value + } +} + +extension Optional where Wrapped == ServerIdentityPolicy.LazyIPAddress { + /// Converts the value from string to one of the IP address cases and + /// returns it. + /// + /// Does nothing if the value is nil. + @usableFromInline + mutating func convert() -> ServerIdentityPolicy.IPAddress? { + switch self { + case .some(.ipAddress(let address)): + return address + case .some(.string(let value)): + if let v4 = ServerIdentityPolicy.parsingIPv4Address(value) { + self = .some(.ipAddress(.v4(v4))) + return .v4(v4) + } else if let v6 = ServerIdentityPolicy.parsingIPv6Address(value) { + self = .some(.ipAddress(.v6(v6))) + return .v6(v6) + } else { + // This is fine, if we can't convert the IP address + // it's just not eligible to match anything. + self = .none + return nil + } + case .none: + return nil + } + } +} + +extension Optional where Wrapped == ServerIdentityPolicy.LazyServerHostname { + /// Converts the value from string to the prepared case and + /// returns it. + /// + /// Does nothing if the value is nil. Nils the value if the conversion fails. + @usableFromInline + mutating func convert() -> ServerIdentityPolicy.PreparedServerHostname? { + switch self { + case .none: + return nil + case .some(.string(let string)): + guard let prepared = ServerIdentityPolicy.PreparedServerHostname(lowercaseASCIIBytes: string) else { + // failed to convert, don't try. + self = .none + return nil + } + + self = .some(.prepared(prepared)) + return prepared + case .some(.prepared(let prepared)): + return prepared + } + } +} + +extension ServerIdentityPolicy.IPAddress { + init?(sanField: ASN1OctetString) { + switch sanField.bytes.count { + case 4: + let addr = sanField.bytes.withUnsafeBufferPointer { + UnsafeRawPointer($0.baseAddress!).loadUnaligned(as: in_addr.self) + } + self = .v4(addr) + case 16: + let addr = sanField.bytes.withUnsafeBufferPointer { + UnsafeRawPointer($0.baseAddress!).loadUnaligned(as: in6_addr.self) + } + self = .v6(addr) + default: + return nil + } + } +} + +extension Certificate { + /// Validates that a given leaf certificate is valid for a service. + /// + /// This function implements the logic for service validation as specified by + /// RFC 6125 (https://tools.ietf.org/search/rfc6125), which loosely speaking + /// defines the common algorithm used for validating that an X.509 certificate + /// is valid for a given service + /// + /// The algorithm we're implementing is specified in RFC 6125 Section 6 if you want to + /// follow along at home. + @usableFromInline + internal func hasValidIdentityForService( + serverHostname: ServerIdentityPolicy.PreparedServerHostname?, + serverIP: ServerIdentityPolicy.IPAddress? + ) -> PolicyEvaluationResult { + // We want to begin by checking the subjectAlternativeName fields. If there are any fields + // in there that we could validate against (either IP or hostname) we will validate against + // them, and then refuse to check the commonName field. If there are no SAN fields to + // validate against, we'll check commonName. + // + // If the SAN field is invalid and we can't parse it, we fail. + let subjectAlternativeNames: SubjectAlternativeNames + do { + subjectAlternativeNames = try self.extensions.subjectAlternativeNames ?? SubjectAlternativeNames() + } catch { + return .failsToMeetPolicy(reason: "Error parsing SAN field, cert cannot be trusted: \(error)") + } + + var checkedMatch = false + for name in subjectAlternativeNames { + checkedMatch = true + + switch name { + case .dnsName(let dnsName): + if Self.matchHostname(serverHostname: serverHostname, dnsName: dnsName) { + return .meetsPolicy + } + case .ipAddress(let ipAddressBytes): + if let serverIP = serverIP, + let certificateIP = ServerIdentityPolicy.IPAddress(sanField: ipAddressBytes), + Self.matchIpAddress(serverIP: serverIP, certificateIP: certificateIP) + { + return .meetsPolicy + } + default: + continue + } + } + + guard !checkedMatch else { + // We had some subject alternative names, but none matched. We failed here. + return .failsToMeetPolicy(reason: "None of the names in SAN extension matched: \(subjectAlternativeNames)") + } + + // In the absence of any matchable subjectAlternativeNames, we can fall back to checking + // the common name. This is a deprecated practice, and in a future release we should + // stop doing this. + // + // As distinguished names move from least significant to most significant, we actually + // want the _last_ CN value. + guard let commonName = self.subject.lastCommonName else { + // No CN, no match. + return .failsToMeetPolicy(reason: "No SAN extension and no common name") + } + + // We have a common name. Let's check it against the provided hostname. We never check + // the common name against the IP address. + guard let cn = String(commonName), Self.matchHostname(serverHostname: serverHostname, dnsName: cn) else { + return .failsToMeetPolicy(reason: "Common name \(commonName) does not match expected hostname") + } + + return .meetsPolicy + } + + private static func matchHostname( + serverHostname: ServerIdentityPolicy.PreparedServerHostname?, + dnsName: String + ) -> Bool { + guard let serverHostname else { + // No server hostname was provided, so we cannot match. + return false + } + + // Now we validate the cert hostname. + guard let validatedHostname = AnalysedCertificateHostname(baseName: dnsName.utf8) else { + // This is a hostname we can't match, return false. + return false + } + return validatedHostname.validMatchForName(serverHostname) + } + + private static func matchIpAddress( + serverIP: ServerIdentityPolicy.IPAddress, + certificateIP: ServerIdentityPolicy.IPAddress + ) -> Bool { + // These match if the two underlying IP address structures match. + switch (serverIP, certificateIP) { + case (.v4(var addr1), .v4(var addr2)): + return memcmp(&addr1, &addr2, MemoryLayout.size) == 0 + case (.v6(var addr1), .v6(var addr2)): + return memcmp(&addr1, &addr2, MemoryLayout.size) == 0 + default: + // Different protocol families, no match. + return false + } + } +} + +extension DistinguishedName { + // TODO: We should have a bunch of these as API. + var lastCommonName: RelativeDistinguishedName.Attribute.Value? { + for rdn in self.reversed() { + for ava in rdn.reversed() { + if ava.type == .RDNAttributeType.commonName { + return ava.value + } + } + } + + return nil + } +} + +private let asciiIDNAIdentifier: ArraySlice = Array("xn--".utf8)[...] +private let asciiCapitals: ClosedRange = (UInt8(ascii: "A")...UInt8(ascii: "Z")) +private let asciiLowercase: ClosedRange = (UInt8(ascii: "a")...UInt8(ascii: "z")) +private let asciiNumbers: ClosedRange = (UInt8(ascii: "0")...UInt8(ascii: "9")) +private let asciiHyphen: UInt8 = UInt8(ascii: "-") +private let asciiPeriod: UInt8 = UInt8(ascii: ".") +private let asciiAsterisk: UInt8 = UInt8(ascii: "*") + +extension Collection { + /// Splits a collection in two around a given index. This index may be nil, in which case the split + /// will occur around the end. + fileprivate func splitAroundIndex(_ index: Index?) -> (SubSequence, SubSequence) { + guard let index = index else { + return (self[...], self[self.endIndex...]) + } + + let subsequentIndex = self.index(after: index) + return (self[.. where BaseNameType.Element == UInt8 { + private var name: NameType + + fileprivate init?(baseName: BaseNameType) { + var baseName = baseName[...] + + // First, strip a trailing period from this name. + if baseName.last == .some(asciiPeriod) { + baseName = baseName.dropLast() + } + + // Ok, start looping. + var index = baseName.startIndex + var firstPeriodIndex: BaseNameType.Index? + var asteriskIndex: BaseNameType.Index? + + while index < baseName.endIndex { + switch baseName[index] { + case asciiPeriod where firstPeriodIndex == nil: + // This is the first period we've seen, great. Future + // periods will be ignored. + firstPeriodIndex = index + + case asciiCapitals, asciiLowercase, asciiNumbers, asciiHyphen, asciiPeriod: + // Valid character, no notes. + break + + case asciiAsterisk where asteriskIndex == nil && firstPeriodIndex == nil: + // Found an asterisk, it's the first one, and it precedes any periods. + asteriskIndex = index + + case asciiAsterisk: + // An extra asterisk, or an asterisk after a period, is unacceptable. + return nil + + default: + // Unacceptable character in the name. + return nil + } + + baseName.formIndex(after: &index) + } + + // Now we can finally initialize ourself. + if let asteriskIndex = asteriskIndex { + // One final check: if we found a wildcard, we need to confirm that the first label isn't an IDNA A label. + if baseName.prefix(4).elementsEqual(asciiIDNAIdentifier) { + return nil + } + + self.name = .wildcard(baseName, asteriskIndex: asteriskIndex, firstPeriodIndex: firstPeriodIndex) + } else { + self.name = .singleName(baseName) + } + } + + /// Whether this parsed name is a valid match for the one passed in. + fileprivate func validMatchForName( + _ target: ServerIdentityPolicy.PreparedServerHostname + ) -> Bool { + switch self.name { + case .singleName(let baseName): + // For non-wildcard names, we just do a straightforward comparison. + return baseName.elementsEqual(target.bytes) + + case .wildcard(let baseName, asteriskIndex: let asteriskIndex, firstPeriodIndex: let firstPeriodIndex): + // The wildcard can appear more-or-less anywhere in the first label. The wildcard + // character itself can match any number of characters, though it must match at least + // one. + // The algorithm for this is simple: first, we split the two names on their first period to get their + // first label and their subsequent components. Second, we check that the subcomponents match a straightforward + // bytewise comparison: if that fails, we can avoid the expensive wildcard checking operation. + // Third, we split the wildcard label on the wildcard character, and and confirm that + // the characters *before* the wildcard are the prefix of the target first label, and that the + // characters *after* the wildcard are the suffix of the target first label. This works well because + // the empty string is a prefix and suffix of all strings. + let (wildcardLabel, remainingComponents) = baseName.splitAroundIndex(firstPeriodIndex) + let (targetFirstLabel, targetRemainingComponents) = target.bytes.splitAroundIndex(target.firstPeriodIndex) + + guard remainingComponents.elementsEqual(targetRemainingComponents) else { + // Wildcard is irrelevant, the remaining components don't match. + return false + } + + guard targetFirstLabel.count >= wildcardLabel.count else { + // The target label cannot possibly match the wildcard. + return false + } + + let (wildcardLabelPrefix, wildcardLabelSuffix) = wildcardLabel.splitAroundIndex(asteriskIndex) + let targetBeforeWildcard = targetFirstLabel.prefix(wildcardLabelPrefix.count) + let targetAfterWildcard = targetFirstLabel.suffix(wildcardLabelSuffix.count) + + let leadingBytesMatch = targetBeforeWildcard.elementsEqual(wildcardLabelPrefix) + let trailingBytesMatch = targetAfterWildcard.elementsEqual(wildcardLabelSuffix) + + return leadingBytesMatch && trailingBytesMatch + } + } +} + +extension AnalysedCertificateHostname { + private enum NameType { + case wildcard( + BaseNameType.SubSequence, + asteriskIndex: BaseNameType.Index, + firstPeriodIndex: BaseNameType.Index? + ) + case singleName(BaseNameType.SubSequence) + } +} diff --git a/Tests/X509Tests/ServerIdentityPolicyTests.swift b/Tests/X509Tests/ServerIdentityPolicyTests.swift new file mode 100644 index 0000000..dd94493 --- /dev/null +++ b/Tests/X509Tests/ServerIdentityPolicyTests.swift @@ -0,0 +1,657 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftCertificates open source project +// +// Copyright (c) 2024 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 Foundation +import XCTest +import Crypto +import SwiftASN1 +@_spi(Testing) import X509 + +private let key = Certificate.PrivateKey(P256.Signing.PrivateKey()) +private let certName = try! DistinguishedName { + CommonName("httpbin.org") +} +private let localhostName = try! DistinguishedName { + CommonName("localhost") +} +private let multiCNName = try! DistinguishedName { + CountryName("US") + CommonName("Ignore me") + StateOrProvinceName("Nebraska") + CommonName("localhost") +} +private let noCNName = try! DistinguishedName { + CountryName("US") + StateOrProvinceName("Nebraska") +} +private let unicodeCNName = try! DistinguishedName { + CommonName("straße.org") +} + +/// This cert contains the following SAN fields: +/// DNS:*.wildcard.example.com - A straightforward wildcard, should be accepted +/// DNS:fo*.example.com - A suffix wildcard, should be accepted +/// DNS:*ar.example.com - A prefix wildcard, should be accepted +/// DNS:b*z.example.com - An infix wildcard +/// DNS:trailing.period.example.com. - A domain with a trailing period, should match +/// DNS:xn--strae-oqa.unicode.example.com. - An IDN A-label, should match. +/// DNS:xn--x*-gia.unicode.example.com. - An IDN A-label with a wildcard, invalid. +/// DNS:weirdwildcard.*.example.com. - A wildcard not in the leftmost label, invalid. +/// DNS:*.*.double.example.com. - Two wildcards, invalid. +/// DNS:*.xn--strae-oqa.example.com. - A wildcard followed by a new IDN A-label, this is fine. +/// A SAN with a null in it, should be ignored. +/// +/// This also contains a commonName of httpbin.org. +private let weirdoSANCert = try! Certificate( + version: .v3, + serialNumber: Certificate.SerialNumber(), + publicKey: key.publicKey, + notValidBefore: Date() - .days(1), + notValidAfter: Date() + .days(354), + issuer: certName, + subject: certName, + signatureAlgorithm: .ecdsaWithSHA256, + extensions: Certificate.Extensions { + BasicConstraints.notCertificateAuthority + + SubjectAlternativeNames([ + // A straightforward wildcard, should be accepted + .dnsName("*.wildcard.example.com"), + + // A suffix wildcard, should be accepted + .dnsName("fo*.example.com"), + + /// A prefix wildcard, should be accepted + .dnsName("*ar.example.com"), + + /// An infix wildcard + .dnsName("b*z.example.com"), + + /// A domain with a trailing period, should match + .dnsName("trailing.period.example.com."), + + /// An IDN A-label, should match. + .dnsName("xn--strae-oqa.unicode.example.com."), + + /// An IDN A-label with a wildcard, invalid. + .dnsName("xn--x*-gia.unicode.example.com."), + + /// A wildcard not in the leftmost label, invalid. + .dnsName("weirdwildcard.*.example.com."), + + /// Two wildcards, invalid. + .dnsName("*.*.double.example.com."), + + /// A wildcard followed by a new IDN A-label, this is fine. + .dnsName("*.xn--strae-oqa.example.com."), + + /// A SAN with a null in it, should be ignored. + .dnsName("\u{0000}"), + ]) + + }, + issuerPrivateKey: key +) + +private let multiSANCert = try! Certificate( + version: .v3, + serialNumber: Certificate.SerialNumber(), + publicKey: key.publicKey, + notValidBefore: Date() - .days(1), + notValidAfter: Date() + .days(354), + issuer: localhostName, + subject: localhostName, + signatureAlgorithm: .ecdsaWithSHA256, + extensions: Certificate.Extensions { + BasicConstraints.notCertificateAuthority + + SubjectAlternativeNames([ + .dnsName("localhost"), + .dnsName("example.com"), + .rfc822Name("user@example.com"), + .ipAddress(ASN1OctetString(ipv4Address: "192.168.0.1")), + .ipAddress(ASN1OctetString(ipv6Address: "2001:DB8:0:0:0:0:0:1")), + ]) + + }, + issuerPrivateKey: key +) +private let multiCNCert = try! Certificate( + version: .v3, + serialNumber: Certificate.SerialNumber(), + publicKey: key.publicKey, + notValidBefore: Date() - .days(1), + notValidAfter: Date() + .days(354), + issuer: multiCNName, + subject: multiCNName, + signatureAlgorithm: .ecdsaWithSHA256, + extensions: Certificate.Extensions { + BasicConstraints.notCertificateAuthority + }, + issuerPrivateKey: key +) +private let noCNCert = try! Certificate( + version: .v3, + serialNumber: Certificate.SerialNumber(), + publicKey: key.publicKey, + notValidBefore: Date() - .days(1), + notValidAfter: Date() + .days(354), + issuer: noCNName, + subject: noCNName, + signatureAlgorithm: .ecdsaWithSHA256, + extensions: Certificate.Extensions { + BasicConstraints.notCertificateAuthority + }, + issuerPrivateKey: key +) +private let unicodeCNCert = try! Certificate( + version: .v3, + serialNumber: Certificate.SerialNumber(), + publicKey: key.publicKey, + notValidBefore: Date() - .days(1), + notValidAfter: Date() + .days(354), + issuer: unicodeCNName, + subject: unicodeCNName, + signatureAlgorithm: .ecdsaWithSHA256, + extensions: Certificate.Extensions { + BasicConstraints.notCertificateAuthority + }, + issuerPrivateKey: key +) + +final class ServerIdentityPolicyTests: XCTestCase { + func testCanValidateHostnameInFirstSan() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "localhost", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testCanValidateHostnameInSecondSan() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testIgnoresTrailingPeriod() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "example.com.", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testLowercasesHostnameForSan() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "LoCaLhOsT", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsIncorrectHostname() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "httpbin.org", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testAcceptsIpv4Address() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: nil, serverIP: "192.168.0.1") + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testAcceptsIpv6Address() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: nil, serverIP: "2001:db8::1") + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsIncorrectIpv4Address() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: nil, serverIP: "192.168.0.2") + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsIncorrectIpv6Address() async throws { + let roots = CertificateStore([multiSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: nil, serverIP: "2001:db8::2") + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: multiSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testAcceptsWildcards() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "this.wildcard.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testAcceptsSuffixWildcard() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "foo.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testAcceptsPrefixWildcard() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "bar.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testAcceptsInfixWildcard() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "baz.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testIgnoresTrailingPeriodInCert() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "trailing.period.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsEncodedIDNALabel() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "straße.unicode.example.com", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testMatchesUnencodedIDNALabel() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "xn--strae-oqa.unicode.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testDoesNotMatchIDNALabelWithWildcard() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "xn--xx-gia.unicode.example.com", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testDoesNotMatchNonLeftmostWildcards() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "weirdwildcard.nomatch.example.com", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testDoesNotMatchMultipleWildcards() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "one.two.double.example.com", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsWildcardBeforeUnencodedIDNALabel() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "foo.straße.example.com", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testMatchesWildcardBeforeEncodedIDNALabel() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "foo.xn--strae-oqa.example.com", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testDoesNotMatchSANWithEmbeddedNULL() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "nul\u{0000}l.example.com", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } + + func testFallsBackToCommonName() async throws { + let roots = CertificateStore([multiCNCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "localhost", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiCNCert, + intermediates: CertificateStore() + ) + ) + } + + func testLowercasesForCommonName() async throws { + let roots = CertificateStore([multiCNCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "LoCaLhOsT", serverIP: nil) + } + ) + await XCTAssertValidCertificate( + await verifier.validate( + leafCertificate: multiCNCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsUnicodeCommonNameWithUnencodedIDNALabel() async throws { + let roots = CertificateStore([unicodeCNCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "straße.org", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: unicodeCNCert, + intermediates: CertificateStore() + ) + ) + } + + func testRejectsUnicodeCommonNameWithEncodedIDNALabel() async throws { + let roots = CertificateStore([unicodeCNCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "xn--strae-oqa.org", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: unicodeCNCert, + intermediates: CertificateStore() + ) + ) + } + + func testHandlesMissingCommonName() async throws { + let roots = CertificateStore([noCNCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "localhost", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: noCNCert, + intermediates: CertificateStore() + ) + ) + } + + func testDoesNotFallBackToCNWithSans() async throws { + let roots = CertificateStore([weirdoSANCert]) + var verifier = Verifier( + rootCertificates: roots, + policy: { + ServerIdentityPolicy(serverHostname: "httpbin.org", serverIP: nil) + } + ) + await XCTAssertInvalidCertificate( + await verifier.validate( + leafCertificate: weirdoSANCert, + intermediates: CertificateStore() + ) + ) + } +} + +extension ASN1OctetString { + fileprivate init(ipv4Address: String) { + let bytes = ServerIdentityPolicy.parsingIPv4Address(ipv4Address)! + let byteArray = Swift.withUnsafeBytes(of: bytes) { Array($0) } + self.init(contentBytes: byteArray[...]) + } + + fileprivate init(ipv6Address: String) { + let bytes = ServerIdentityPolicy.parsingIPv6Address(ipv6Address)! + let byteArray = Swift.withUnsafeBytes(of: bytes) { Array($0) } + self.init(contentBytes: byteArray[...]) + } +} + +private func XCTAssertValidCertificate( + _ verifier: @autoclosure () async throws -> VerificationResult, + file: StaticString = #file, + line: UInt = #line +) async rethrows { + let result = try await verifier() + if case .couldNotValidate(let reason) = result { + XCTFail("Could not validate certificate, reason: \(reason)", file: file, line: line) + } +} + +private func XCTAssertInvalidCertificate( + _ verifier: @autoclosure () async throws -> VerificationResult, + file: StaticString = #file, + line: UInt = #line +) async rethrows { + let result = try await verifier() + if case .validCertificate = result { + XCTFail("Incorrectly validated certificate", file: file, line: line) + } +} diff --git a/scripts/soundness.sh b/scripts/soundness.sh index b6b47ee..6a7c39c 100755 --- a/scripts/soundness.sh +++ b/scripts/soundness.sh @@ -31,7 +31,7 @@ here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" function replace_acceptable_years() { # this needs to replace all acceptable forms with 'YEARS' - sed -e 's/20[12][789012]-20[12][890123]/YEARS/' -e 's/20[12][890123]/YEARS/' + sed -e 's/20[12][78901234]-20[12][8901234]/YEARS/' -e 's/20[12][8901234]/YEARS/' } printf "=> Checking for unacceptable language... "