DomainDig/SSLCheckService.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDig/SSLCheckService.swift history · blame · raw

483 lines · 17557 bytes

24 symbols in this file
  1import Foundation
  2import Security
  3
  4struct SSLCheckService {
  5
  6    static func check(domain: String) async -> ServiceResult<SSLCertificateInfo> {
  7        guard let url = DomainHostURL.https(domain) else {
  8            return .error("Not a valid domain name")
  9        }
 10
 11        let delegate = SSLSessionDelegate()
 12        let session = URLSession(
 13            configuration: .ephemeral,
 14            delegate: delegate,
 15            delegateQueue: nil
 16        )
 17        defer { session.invalidateAndCancel() }
 18
 19        let request = URLRequest(url: url, timeoutInterval: 10)
 20
 21        do {
 22            _ = try await session.data(for: request)
 23
 24            guard let trust = delegate.serverTrust else {
 25                return .empty(SSLError.noCertificate.localizedDescription)
 26            }
 27
 28            return .success(try extractCertificateInfo(from: trust, metadata: delegate.tlsMetadata))
 29        } catch {
 30            return .error(error.localizedDescription)
 31        }
 32    }
 33
 34    static func checkHSTSPreload(domain: String) async -> Bool? {
 35        var components = URLComponents(string: "https://hstspreload.org/api/v2/status")
 36        components?.queryItems = [
 37            URLQueryItem(name: "domain", value: domain)
 38        ]
 39
 40        guard let url = components?.url else {
 41            return nil
 42        }
 43
 44        do {
 45            let (data, _) = try await URLSession.shared.data(from: url)
 46            let response = try JSONDecoder().decode(HSTSPreloadResponse.self, from: data)
 47            return response.status == "preloaded"
 48        } catch {
 49            return nil
 50        }
 51    }
 52
 53    private static func extractCertificateInfo(
 54        from trust: SecTrust,
 55        metadata: TLSMetadata?
 56    ) throws -> SSLCertificateInfo {
 57        let chainCount = SecTrustGetCertificateCount(trust)
 58        guard chainCount > 0,
 59              let certChain = SecTrustCopyCertificateChain(trust) as? [SecCertificate],
 60              let leaf = certChain.first else {
 61            throw SSLError.noCertificate
 62        }
 63
 64        // Common Name — use subject summary (available on iOS)
 65        let commonName = SecCertificateCopySubjectSummary(leaf) as String? ?? "Unknown"
 66
 67        // Validity dates
 68        let validFrom: Date
 69        let validUntil: Date
 70
 71        let derData = SecCertificateCopyData(leaf) as Data
 72        let parsed = DERCertificateParser.parse(derData)
 73
 74        if #available(iOS 18.0, *) {
 75            if let notBefore = SecCertificateCopyNotValidBeforeDate(leaf) as Date? {
 76                validFrom = notBefore
 77            } else {
 78                validFrom = parsed.notBefore ?? Date.distantPast
 79            }
 80
 81            if let notAfter = SecCertificateCopyNotValidAfterDate(leaf) as Date? {
 82                validUntil = notAfter
 83            } else {
 84                validUntil = parsed.notAfter ?? Date.distantFuture
 85            }
 86        } else {
 87            validFrom = parsed.notBefore ?? Date.distantPast
 88            validUntil = parsed.notAfter ?? Date.distantFuture
 89        }
 90
 91        let daysUntilExpiry = Calendar.current.dateComponents([.day], from: Date(), to: validUntil).day ?? 0
 92
 93        let sans = parsed.subjectAltNames.isEmpty ? [commonName] : parsed.subjectAltNames
 94
 95        // Issuer: prefer parsed issuer, fall back to chain's next cert summary
 96        var issuer = parsed.issuerCommonName ?? "Unknown"
 97        if issuer == "Unknown" && certChain.count > 1 {
 98            let issuerCert = certChain[1]
 99            if let issuerSummary = SecCertificateCopySubjectSummary(issuerCert) as String? {
100                issuer = issuerSummary
101            }
102        }
103
104        let chain = certChain.map { certificate in
105            let subject = SecCertificateCopySubjectSummary(certificate) as String? ?? "Unknown"
106            let parsedCertificate = DERCertificateParser.parse(SecCertificateCopyData(certificate) as Data)
107            return SSLCertificateInfo.CertChainEntry(
108                subject: subject,
109                issuer: parsedCertificate.issuerCommonName ?? "Unknown"
110            )
111        }
112
113        return SSLCertificateInfo(
114            commonName: commonName,
115            subjectAltNames: sans,
116            issuer: issuer,
117            validFrom: validFrom,
118            validUntil: validUntil,
119            daysUntilExpiry: daysUntilExpiry,
120            chainDepth: Int(chainCount),
121            tlsVersion: metadata?.tlsVersion,
122            cipherSuite: metadata?.cipherSuite,
123            chain: chain
124        )
125    }
126
127}
128
129fileprivate struct TLSMetadata {
130    let tlsVersion: String?
131    let cipherSuite: String?
132}
133
134private struct HSTSPreloadResponse: Decodable {
135    let status: String
136}
137
138// MARK: - Minimal DER/ASN.1 parser for X.509 certificate fields
139
140private enum DERCertificateParser {
141    struct Result {
142        var issuerCommonName: String?
143        var subjectAltNames: [String] = []
144        var notBefore: Date?
145        var notAfter: Date?
146    }
147
148    static func parse(_ data: Data) -> Result {
149        var result = Result()
150        let bytes = [UInt8](data)
151
152        // X.509 structure: SEQUENCE { tbsCertificate, signatureAlgorithm, signatureValue }
153        // tbsCertificate: SEQUENCE { version, serialNumber, signature, issuer, validity, subject, ... extensions }
154        guard let tbsRange = readSequence(bytes, offset: 0),
155              let tbsContent = readSequence(bytes, offset: tbsRange.contentStart) else {
156            return result
157        }
158
159        var offset = tbsContent.contentStart
160
161        // Skip version (explicit tag [0]) if present
162        if offset < bytes.count, (bytes[offset] & 0xE0) == 0xA0,
163           let tagLen = readTagAndLength(bytes, offset: offset) {
164            offset = tagLen.contentStart + tagLen.length
165        }
166
167        // Skip serialNumber
168        if let serial = readTagAndLength(bytes, offset: offset) {
169            offset = serial.contentStart + serial.length
170        }
171
172        // Skip signature algorithm
173        if let sigAlg = readTagAndLength(bytes, offset: offset) {
174            offset = sigAlg.contentStart + sigAlg.length
175        }
176
177        // Issuer — a SEQUENCE of SETs of attribute type-value pairs
178        if let issuerSeq = readTagAndLength(bytes, offset: offset) {
179            result.issuerCommonName = extractCommonName(bytes, sequenceStart: issuerSeq.contentStart, length: issuerSeq.length)
180            offset = issuerSeq.contentStart + issuerSeq.length
181        }
182
183        // Validity
184        if let validity = readTagAndLength(bytes, offset: offset) {
185            let (notBefore, notAfter) = extractValidity(bytes, sequenceStart: validity.contentStart, length: validity.length)
186            result.notBefore = notBefore
187            result.notAfter = notAfter
188            offset = validity.contentStart + validity.length
189        }
190
191        // Skip subject
192        if let subject = readTagAndLength(bytes, offset: offset) {
193            offset = subject.contentStart + subject.length
194        }
195
196        // Skip subjectPublicKeyInfo
197        if let spki = readTagAndLength(bytes, offset: offset) {
198            offset = spki.contentStart + spki.length
199        }
200
201        // Extensions are in an explicit tag [3]
202        while offset < tbsContent.contentStart + tbsContent.length {
203            if bytes[offset] == 0xA3 {
204                // Inside the wrapper is a SEQUENCE of SEQUENCE extensions
205                if let extWrapper = readTagAndLength(bytes, offset: offset),
206                   let extsSeq = readTagAndLength(bytes, offset: extWrapper.contentStart) {
207                    result.subjectAltNames = extractSANs(bytes, sequenceStart: extsSeq.contentStart, length: extsSeq.length)
208                }
209                break
210            }
211            // Skip optional implicit tags (issuerUniqueID [1], subjectUniqueID [2])
212            if let tl = readTagAndLength(bytes, offset: offset) {
213                offset = tl.contentStart + tl.length
214            } else {
215                break
216            }
217        }
218
219        return result
220    }
221
222    // OID for commonName: 2.5.4.3 = 55 04 03
223    private static let cnOID: [UInt8] = [0x55, 0x04, 0x03]
224
225    // OID for subjectAltName: 2.5.29.17 = 55 1D 11
226    private static let sanOID: [UInt8] = [0x55, 0x1D, 0x11]
227
228    private static func extractCommonName(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> String? {
229        let end = sequenceStart + length
230        var pos = sequenceStart
231        while pos < end {
232            // Each SET in the issuer
233            guard let setTL = readTagAndLength(bytes, offset: pos) else { break }
234            pos = setTL.contentStart + setTL.length
235
236            // Inside the SET is a SEQUENCE with OID + value
237            guard let seqTL = readTagAndLength(bytes, offset: setTL.contentStart),
238                  let oidTL = readTagAndLength(bytes, offset: seqTL.contentStart),
239                  content(of: oidTL, in: bytes).elementsEqual(cnOID),
240                  let valueTL = readTagAndLength(bytes, offset: oidTL.contentStart + oidTL.length)
241            else { continue }
242            return String(bytes: content(of: valueTL, in: bytes), encoding: .utf8)
243        }
244        return nil
245    }
246
247    private static func extractSANs(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> [String] {
248        let end = sequenceStart + length
249        var pos = sequenceStart
250        var sans: [String] = []
251
252        while pos < end {
253            guard let extSeq = readTagAndLength(bytes, offset: pos) else { break }
254            let extEnd = extSeq.contentStart + extSeq.length
255
256            // Each extension is SEQUENCE { OID, [critical], value }
257            if let oidTL = readTagAndLength(bytes, offset: extSeq.contentStart), content(of: oidTL, in: bytes).elementsEqual(sanOID) {
258                sans += sanDNSNames(bytes, valueStart: oidTL.contentStart + oidTL.length, extensionEnd: extEnd)
259            }
260            pos = extEnd
261        }
262        return sans
263    }
264
265    /// The dNSName entries of a subjectAltName extension whose value starts at `valueStart`.
266    private static func sanDNSNames(_ bytes: [UInt8], valueStart: Int, extensionEnd: Int) -> [String] {
267        var valuePos = valueStart
268        // Skip optional critical BOOLEAN
269        if valuePos < extensionEnd, bytes[valuePos] == 0x01,
270           let boolTL = readTagAndLength(bytes, offset: valuePos) {
271            valuePos = boolTL.contentStart + boolTL.length
272        }
273        // The value is an OCTET STRING wrapping a SEQUENCE of GeneralNames
274        guard let octetTL = readTagAndLength(bytes, offset: valuePos),
275              let sanSeq = readTagAndLength(bytes, offset: octetTL.contentStart)
276        else { return [] }
277
278        let sanEnd = sanSeq.contentStart + sanSeq.length
279        var sanPos = sanSeq.contentStart
280        var names: [String] = []
281        while sanPos < sanEnd {
282            guard let nameTL = readTagAndLength(bytes, offset: sanPos) else { break }
283            // Context tag [2] = dNSName (IA5String)
284            if (bytes[sanPos] & 0x1F) == 2, let name = String(bytes: content(of: nameTL, in: bytes), encoding: .ascii) {
285                names.append(name)
286            }
287            sanPos = nameTL.contentStart + nameTL.length
288        }
289        return names
290    }
291
292    private static func extractValidity(_ bytes: [UInt8], sequenceStart: Int, length: Int) -> (Date?, Date?) {
293        let end = sequenceStart + length
294        var position = sequenceStart
295        var dates: [Date] = []
296
297        while position < end, dates.count < 2 {
298            guard let timeTL = readTagAndLength(bytes, offset: position) else { break }
299            let raw = String(bytes: bytes[timeTL.contentStart..<timeTL.contentStart + timeTL.length], encoding: .ascii)
300            if let raw {
301                dates.append(parseASN1Time(raw))
302            }
303            position = timeTL.contentStart + timeTL.length
304        }
305
306        let notBefore = dates.indices.contains(0) ? dates[0] : nil
307        let notAfter = dates.indices.contains(1) ? dates[1] : nil
308        return (notBefore, notAfter)
309    }
310
311    private static func parseASN1Time(_ string: String) -> Date {
312        let utcFormatter = DateFormatter()
313        utcFormatter.locale = Locale(identifier: "en_US_POSIX")
314        utcFormatter.timeZone = TimeZone(secondsFromGMT: 0)
315        utcFormatter.dateFormat = "yyMMddHHmmss'Z'"
316
317        if let date = utcFormatter.date(from: string) {
318            return date
319        }
320
321        let generalizedFormatter = DateFormatter()
322        generalizedFormatter.locale = Locale(identifier: "en_US_POSIX")
323        generalizedFormatter.timeZone = TimeZone(secondsFromGMT: 0)
324        generalizedFormatter.dateFormat = "yyyyMMddHHmmss'Z'"
325
326        return generalizedFormatter.date(from: string) ?? Date.distantFuture
327    }
328
329    private struct TLV {
330        let contentStart: Int
331        let length: Int
332    }
333
334    private static func readSequence(_ bytes: [UInt8], offset: Int) -> TLV? {
335        guard offset < bytes.count, bytes[offset] == 0x30 else { return nil }
336        return readTagAndLength(bytes, offset: offset)
337    }
338
339    private static func readTagAndLength(_ bytes: [UInt8], offset: Int) -> TLV? {
340        guard offset < bytes.count else { return nil }
341        var pos = offset + 1 // skip tag byte
342        guard pos < bytes.count else { return nil }
343
344        let firstLen = bytes[pos]
345        pos += 1
346
347        let length: Int
348        if firstLen < 0x80 {
349            length = Int(firstLen)
350        } else {
351            let numBytes = Int(firstLen & 0x7F)
352            guard numBytes > 0, numBytes <= 4, pos + numBytes <= bytes.count else { return nil }
353            var len = 0
354            for i in 0..<numBytes {
355                len = (len << 8) | Int(bytes[pos + i])
356            }
357            pos += numBytes
358            length = len
359        }
360
361        // A length past the end of the data is malformed, and slicing to it would trap.
362        guard length <= bytes.count - pos else { return nil }
363        return TLV(contentStart: pos, length: length)
364    }
365
366    private static func content(of tlv: TLV, in bytes: [UInt8]) -> ArraySlice<UInt8> {
367        bytes[tlv.contentStart..<tlv.contentStart + tlv.length]
368    }
369}
370
371enum SSLError: LocalizedError {
372    case noCertificate
373    case connectionFailed
374
375    var errorDescription: String? {
376        switch self {
377        case .noCertificate:
378            return "No certificate found"
379        case .connectionFailed:
380            return "Failed to connect to server"
381        }
382    }
383}
384
385final class SSLSessionDelegate: NSObject, URLSessionDelegate, @unchecked Sendable {
386    private let lock = NSLock()
387    private var storedServerTrust: SecTrust?
388    private var storedTLSMetadata: TLSMetadata?
389
390    var serverTrust: SecTrust? {
391        lock.lock()
392        defer { lock.unlock() }
393        return storedServerTrust
394    }
395
396    fileprivate var tlsMetadata: TLSMetadata? {
397        lock.lock()
398        defer { lock.unlock() }
399        return storedTLSMetadata
400    }
401
402    func urlSession(
403        _ _: URLSession,
404        didReceive challenge: URLAuthenticationChallenge,
405        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
406    ) {
407        guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
408              let trust = challenge.protectionSpace.serverTrust else {
409            completionHandler(.performDefaultHandling, nil)
410            return
411        }
412
413        lock.lock()
414        storedServerTrust = trust
415        lock.unlock()
416
417        let credential = URLCredential(trust: trust)
418        completionHandler(.useCredential, credential)
419    }
420}
421
422extension SSLSessionDelegate: URLSessionTaskDelegate {
423    func urlSession(
424        _ _: URLSession,
425        task _: URLSessionTask,
426        didFinishCollecting metrics: URLSessionTaskMetrics
427    ) {
428        guard let transaction = metrics.transactionMetrics.last else {
429            return
430        }
431
432        let tlsVersion = transaction.negotiatedTLSProtocolVersion.map {
433            Self.describeTLSVersion($0)
434        }
435        let cipherSuite = transaction.negotiatedTLSCipherSuite.map {
436            Self.describeCipherSuite($0)
437        }
438
439        lock.lock()
440        storedTLSMetadata = TLSMetadata(tlsVersion: tlsVersion, cipherSuite: cipherSuite)
441        lock.unlock()
442    }
443
444    private static func describeTLSVersion(_ version: tls_protocol_version_t) -> String {
445        switch version.rawValue {
446        case 0x0301:
447            return "TLS 1.0"
448        case 0x0302:
449            return "TLS 1.1"
450        case 0x0303:
451            return "TLS 1.2"
452        case 0x0304:
453            return "TLS 1.3"
454        default:
455            return String(describing: version)
456        }
457    }
458
459    private static func describeCipherSuite(_ suite: tls_ciphersuite_t) -> String {
460        switch suite.rawValue {
461        case 0x1301:
462            return "TLS_AES_128_GCM_SHA256"
463        case 0x1302:
464            return "TLS_AES_256_GCM_SHA384"
465        case 0x1303:
466            return "TLS_CHACHA20_POLY1305_SHA256"
467        case 0xC02F:
468            return "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
469        case 0xC030:
470            return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
471        case 0xC02B:
472            return "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"
473        case 0xC02C:
474            return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
475        case 0xCCA8:
476            return "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"
477        case 0xCCA9:
478            return "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"
479        default:
480            return String(format: "0x%04X", suite.rawValue)
481        }
482    }
483}