SPB Git

Repository Public License

FixtureTLSIdentity.swift 4.3 KB 89 lines swift

1#if os(macOS)2import Foundation3import Network4import Security56/// A throw-away self-signed TLS identity for `FixtureServer(tls:)`, generated at test time with the system7/// `openssl` so that no private key is ever stored in the repository. The certificate is deliberately not8/// trusted by anyone: it is the "invalid certificate" case.9public struct FixtureTLSIdentity: @unchecked Sendable {10    public enum Failure: Error, CustomStringConvertible {11        case toolFailed(String)12        case importFailed(OSStatus)13        case noIdentity1415        public var description: String {16            switch self {17            case .toolFailed(let message): "openssl failed: \(message)"18            case .importFailed(let status): "SecPKCS12Import failed: \(status)"19            case .noIdentity: "The PKCS#12 archive contained no identity"20            }21        }22    }2324    public let identity: SecIdentity25    public let certificate: SecCertificate26    /// DER encoding of the certificate.27    public let certificateData: Data2829    /// Generates a certificate for `commonName` valid from now for `days` days (`days` may be 0 for one that30    /// expires immediately). Subject alternative names cover 127.0.0.1 and localhost.31    public static func makeSelfSigned(commonName: String = "127.0.0.1", days: Int = 2) throws -> FixtureTLSIdentity {32        let directory = try TemporaryDirectory(prefix: "orix-tls")33        defer { directory.remove() }34        let key = directory.url.appendingPathComponent("key.pem").path35        let cert = directory.url.appendingPathComponent("cert.pem").path36        let archive = directory.url.appendingPathComponent("identity.p12").path37        // Random per run; it only protects a file that lives for a few milliseconds in a private temp folder.38        let passphrase = UUID().uuidString3940        try run(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-out", cert,41                 "-days", "\(days)", "-subj", "/CN=\(commonName)/O=ORIX Navigator Fixture",42                 "-addext", "subjectAltName=IP:127.0.0.1,DNS:localhost"])43        try run(["pkcs12", "-export", "-inkey", key, "-in", cert, "-out", archive,44                 "-passout", "pass:\(passphrase)", "-name", "orix-fixture"])4546        let data = try Data(contentsOf: URL(fileURLWithPath: archive))47        // In-memory import: nothing is added to the user's keychain.48        let options: [String: Any] = [kSecImportExportPassphrase as String: passphrase,49                                      kSecImportToMemoryOnly as String: true]50        var items: CFArray?51        let status = SecPKCS12Import(data as CFData, options as CFDictionary, &items)52        guard status == errSecSuccess else { throw Failure.importFailed(status) }53        guard let first = (items as? [[String: Any]])?.first,54              let anyIdentity = first[kSecImportItemIdentity as String] else { throw Failure.noIdentity }55        let identity = anyIdentity as! SecIdentity56        var certificate: SecCertificate?57        SecIdentityCopyCertificate(identity, &certificate)58        guard let certificate else { throw Failure.noIdentity }59        return FixtureTLSIdentity(identity: identity, certificate: certificate,60                                  certificateData: SecCertificateCopyData(certificate) as Data)61    }6263    /// TLS listener options presenting this identity.64    public func tlsOptions() -> NWProtocolTLS.Options {65        let options = NWProtocolTLS.Options()66        if let secIdentity = sec_identity_create(identity) {67            sec_protocol_options_set_local_identity(options.securityProtocolOptions, secIdentity)68        }69        sec_protocol_options_set_min_tls_protocol_version(options.securityProtocolOptions, .TLSv12)70        return options71    }7273    private static func run(_ arguments: [String]) throws {74        let process = Process()75        process.executableURL = URL(fileURLWithPath: "/usr/bin/openssl")76        process.arguments = arguments77        let errors = Pipe()78        process.standardError = errors79        process.standardOutput = Pipe()80        do { try process.run() } catch { throw Failure.toolFailed(String(describing: error)) }81        let errorData = errors.fileHandleForReading.readDataToEndOfFile()82        process.waitUntilExit()83        guard process.terminationStatus == 0 else {84            throw Failure.toolFailed(String(decoding: errorData, as: UTF8.self))85        }86    }87}88#endif89
Files main
Menu

Theme