SPB Git

Repository Public License

CertificateTrust.swift 8.7 KB 170 lines swift

1import CryptoKit2import Foundation3import Security45/// What the UI may show about one certificate. Contains no key material.6public struct CertificateSummary: Sendable, Hashable, Codable {7    /// Human-readable subject (usually the common name).8    public var subject: String9    public var commonName: String?10    public var notValidBefore: Date?11    public var notValidAfter: Date?12    /// Uppercase hex SHA-256 of the DER certificate.13    public var sha256Fingerprint: String14    public var serialNumber: String?15    /// Issuer and subject are identical: the certificate vouches for itself.16    public var isSelfIssued: Bool1718    public init(subject: String, commonName: String? = nil, notValidBefore: Date? = nil, notValidAfter: Date? = nil,19                sha256Fingerprint: String, serialNumber: String? = nil, isSelfIssued: Bool = false) {20        self.subject = subject; self.commonName = commonName; self.notValidBefore = notValidBefore21        self.notValidAfter = notValidAfter; self.sha256Fingerprint = sha256Fingerprint22        self.serialNumber = serialNumber; self.isSelfIssued = isSelfIssued23    }2425    public init(certificate: SecCertificate) {26        let der = SecCertificateCopyData(certificate) as Data27        subject = (SecCertificateCopySubjectSummary(certificate) as String?) ?? ""28        var name: CFString?29        commonName = SecCertificateCopyCommonName(certificate, &name) == errSecSuccess ? name as String? : nil30        notValidBefore = SecCertificateCopyNotValidBeforeDate(certificate) as Date?31        notValidAfter = SecCertificateCopyNotValidAfterDate(certificate) as Date?32        sha256Fingerprint = SHA256.hash(data: der).map { String(format: "%02X", $0) }.joined()33        serialNumber = (SecCertificateCopySerialNumberData(certificate, nil) as Data?)?34            .map { String(format: "%02X", $0) }.joined()35        let issuer = SecCertificateCopyNormalizedIssuerSequence(certificate) as Data?36        let subjectSequence = SecCertificateCopyNormalizedSubjectSequence(certificate) as Data?37        isSelfIssued = issuer != nil && issuer == subjectSequence38    }39}4041/// Security state of the committed page, derived from `WKWebView.serverTrust`.42public struct ServerTrustSummary: Sendable, Hashable {43    public var host: String44    /// Leaf first.45    public var chain: [CertificateSummary]46    /// True when the page is shown only because the user accepted an invalid certificate for this session.47    public var usesUserException: Bool4849    public var leaf: CertificateSummary? { chain.first }5051    public init(host: String, chain: [CertificateSummary], usesUserException: Bool = false) {52        self.host = host; self.chain = chain; self.usesUserException = usesUserException53    }5455    init(trust: SecTrust, host: String, usesUserException: Bool) {56        let certificates = (SecTrustCopyCertificateChain(trust) as? [SecCertificate]) ?? []57        self.init(host: host, chain: certificates.map(CertificateSummary.init(certificate:)),58                  usesUserException: usesUserException)59    }60}6162/// A TLS certificate the system refused. The load was cancelled; the UI shows a native error page from this.63public struct CertificateError: Error, Sendable, Hashable {64    public enum Reason: String, Sendable, Codable {65        case expired, notYetValid, hostnameMismatch, untrustedIssuer, selfSigned, revoked, weakOrInvalid, unknown66    }6768    public var host: String69    public var port: Int70    public var reason: Reason71    /// The system's description of the failure (localised by the OS).72    public var systemMessage: String73    public var osStatus: Int74    /// The page that was being loaded, when it was the main document.75    public var failingURL: URL?76    public var certificate: CertificateSummary?77    public var chain: [CertificateSummary]78    public var occurredAt: Date7980    public init(host: String, port: Int, reason: Reason, systemMessage: String, osStatus: Int, failingURL: URL? = nil,81                certificate: CertificateSummary? = nil, chain: [CertificateSummary] = [], occurredAt: Date = .now) {82        self.host = host; self.port = port; self.reason = reason; self.systemMessage = systemMessage83        self.osStatus = osStatus; self.failingURL = failingURL; self.certificate = certificate84        self.chain = chain; self.occurredAt = occurredAt85    }86}8788/// An explicit user decision to accept one invalid certificate for one host, for the life of the profile session.89/// Held in memory only: it is not `Codable` on purpose.90public struct CertificateException: Sendable, Hashable, Identifiable {91    public var host: String92    public var port: Int93    /// The exception is bound to the exact certificate the user saw. Another certificate fails again.94    public var sha256Fingerprint: String95    public var reason: CertificateError.Reason96    public var grantedAt: Date9798    public var id: String { "\(host):\(port):\(sha256Fingerprint)" }99100    public init(host: String, port: Int, sha256Fingerprint: String, reason: CertificateError.Reason, grantedAt: Date = .now) {101        self.host = host.lowercased(); self.port = port; self.sha256Fingerprint = sha256Fingerprint102        self.reason = reason; self.grantedAt = grantedAt103    }104}105106public enum ServerTrustDecision: Sendable, Hashable {107    /// The system trusts the chain: let WebKit proceed with its default handling.108    case performDefaultHandling109    /// The chain is invalid but matches an exception the user granted in this session.110    case acceptWithUserException(CertificateException)111    /// The chain is invalid: cancel the load and report.112    case reject(CertificateError)113}114115/// Decides what to do with a server-trust challenge. There is no path from an invalid chain to "proceed" other116/// than a matching `CertificateException`.117public enum CertificateTrustEvaluator {118    /// Evaluates `trust` for `host`. Blocking (may consult the network for revocation): call it off the main actor.119    public static func decide(trust: SecTrust, host: String, port: Int,120                              exceptions: [CertificateException]) -> ServerTrustDecision {121        var error: CFError?122        if SecTrustEvaluateWithError(trust, &error) { return .performDefaultHandling }123124        let chain = ((SecTrustCopyCertificateChain(trust) as? [SecCertificate]) ?? []).map(CertificateSummary.init(certificate:))125        let leaf = chain.first126        let code = error.map { CFErrorGetCode($0) } ?? Int(errSecNotTrusted)127        let message = error.map { CFErrorCopyDescription($0) as String } ?? "The certificate is not trusted."128        let reason = Self.reason(forStatus: code, leaf: leaf)129130        if let leaf, let match = exceptions.first(where: {131            $0.host == host.lowercased() && $0.port == port && $0.sha256Fingerprint == leaf.sha256Fingerprint132        }) {133            return .acceptWithUserException(match)134        }135        return .reject(CertificateError(host: host.lowercased(), port: port, reason: reason, systemMessage: message,136                                        osStatus: code, certificate: leaf, chain: chain))137    }138139    static func reason(forStatus status: Int, leaf: CertificateSummary?) -> CertificateError.Reason {140        switch Int32(truncatingIfNeeded: status) {141        case errSecCertificateExpired: return .expired142        case errSecCertificateNotValidYet: return .notYetValid143        case errSecHostNameMismatch: return .hostnameMismatch144        case errSecCertificateRevoked: return .revoked145        case errSecNotTrusted, errSecCreateChainFailed, errSecMissingRequiredExtension, errSecUnknownCriticalExtensionFlag:146            return leaf?.isSelfIssued == true ? .selfSigned : .untrustedIssuer147        case errSecUnsupportedKeySize, errSecInvalidDigestAlgorithm, errSecInvalidCertificateRef, errSecInvalidSignature,148             errSecInvalidKeyUsageForPolicy, errSecInvalidExtendedKeyUsage:149            return .weakOrInvalid150        default:151            if let leaf {152                // The status is not always specific; the dates tell the common cases apart.153                if let end = leaf.notValidAfter, end < .now { return .expired }154                if let start = leaf.notValidBefore, start > .now { return .notYetValid }155                if leaf.isSelfIssued { return .selfSigned }156            }157            return .unknown158        }159    }160161    /// Builds a trust object for `certificates` (leaf first) with the SSL policy for `host`. Used by tests and by162    /// callers that hold certificate data rather than a live challenge.163    public static func makeTrust(certificates: [SecCertificate], host: String) -> SecTrust? {164        var trust: SecTrust?165        let policy = SecPolicyCreateSSL(true, host as CFString)166        guard SecTrustCreateWithCertificates(certificates as CFArray, policy, &trust) == errSecSuccess else { return nil }167        return trust168    }169}170
Files main
Menu

Theme