Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions macos/Sources/ReverseAPIProxy/CA/CAStore.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import Foundation
import Crypto
import X509
import SwiftASN1
import Security

public enum CAStoreError: Error {
case missingCertificateOnDisk
case missingPrivateKeyInKeychain
case keychainWriteFailed(OSStatus)
case keychainReadFailed(OSStatus)
case keychainDeleteFailed(OSStatus)
case invalidStoredPrivateKey
case certificateDeleteFailed(any Error)
}

public final class CAStore: @unchecked Sendable {
public let directory: URL
public let certificateURL: URL

private let keychainService = "app.reverseapi"
private let keychainAccount = "ca.root-private-key"

public init(applicationSupportURL: URL) throws {
let root = applicationSupportURL.appendingPathComponent("ReverseAPI", isDirectory: true)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
self.directory = root
self.certificateURL = root.appendingPathComponent("root.cer")
}

public func loadOrCreate() throws -> RootCertificate {
if exists() {
return try load()
}
return try createAndStore()
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.

public func load() throws -> RootCertificate {
guard FileManager.default.fileExists(atPath: certificateURL.path) else {
throw CAStoreError.missingCertificateOnDisk
}
let derBytes = try Data(contentsOf: certificateURL)
let certificate = try Certificate(derEncoded: Array(derBytes))
let pemData = try loadPrivateKeyPEM()
guard let pemString = String(data: pemData, encoding: .utf8) else {
throw CAStoreError.invalidStoredPrivateKey
}
let privateKey = try Certificate.PrivateKey(pemEncoded: pemString)
return RootCertificate(certificate: certificate, privateKey: privateKey)
}

public func createAndStore() throws -> RootCertificate {
let root = try CertificateAuthority.generateRoot()
try Data(try root.derBytes()).write(to: certificateURL, options: .atomic)
let pem = try root.privateKey.serializeAsPEM().pemString
try storePrivateKeyPEM(Data(pem.utf8))
return root
}

public func reset() throws {
let manager = FileManager.default
if manager.fileExists(atPath: certificateURL.path) {
do {
try manager.removeItem(at: certificateURL)
} catch {
throw CAStoreError.certificateDeleteFailed(error)
}
}
try deletePrivateKey()
}

public func exists() -> Bool {
guard FileManager.default.fileExists(atPath: certificateURL.path) else { return false }
return privateKeyExists()
}

private func storePrivateKeyPEM(_ data: Data) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: keychainAccount,
]
let deleteStatus = SecItemDelete(query as CFDictionary)
if deleteStatus != errSecSuccess && deleteStatus != errSecItemNotFound {
throw CAStoreError.keychainDeleteFailed(deleteStatus)
}

var addQuery = query
addQuery[kSecValueData as String] = data
addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
let status = SecItemAdd(addQuery as CFDictionary, nil)
guard status == errSecSuccess else { throw CAStoreError.keychainWriteFailed(status) }
}

private func loadPrivateKeyPEM() throws -> Data {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: keychainAccount,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecItemNotFound {
throw CAStoreError.missingPrivateKeyInKeychain
}
guard status == errSecSuccess, let data = result as? Data else {
throw CAStoreError.keychainReadFailed(status)
}
return data
}

private func privateKeyExists() -> Bool {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: keychainAccount,
kSecReturnData as String: false,
kSecMatchLimit as String: kSecMatchLimitOne,
]
let status = SecItemCopyMatching(query as CFDictionary, nil)
return status == errSecSuccess
}

private func deletePrivateKey() throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: keychainService,
kSecAttrAccount as String: keychainAccount,
]
let status = SecItemDelete(query as CFDictionary)
if status != errSecSuccess && status != errSecItemNotFound {
throw CAStoreError.keychainDeleteFailed(status)
}
}
}
21 changes: 21 additions & 0 deletions macos/Sources/ReverseAPIProxy/ProxyEngine+Bootstrap.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Foundation

extension ProxyEngine {
public static func bootstrap(
applicationSupportURL: URL,
port: Int = 8888,
bus: FlowBus = FlowBus()
) throws -> ProxyEngine {
let store = try CAStore(applicationSupportURL: applicationSupportURL)
let root = try store.loadOrCreate()
return try ProxyEngine(root: root, port: port, bus: bus)
}

public func rootDERBytes() throws -> Data {
Data(try root.derBytes())
}

public func rootPEM() throws -> String {
try root.pem()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import Foundation
import Security

public enum CertificateTrustError: Error {
case invalidCertificate
case addFailed(OSStatus)
case trustFailed(OSStatus)
}

public final class CertificateTrustInstaller: Sendable {
public init() {}

public func install(derBytes: Data) throws {
let cert = try secCertificate(from: derBytes)

let addQuery: [String: Any] = [
kSecClass as String: kSecClassCertificate,
kSecValueRef as String: cert,
]
let status = SecItemAdd(addQuery as CFDictionary, nil)
if status != errSecSuccess && status != errSecDuplicateItem {
throw CertificateTrustError.addFailed(status)
}

let trustSettings: [[String: Any]] = [[
kSecTrustSettingsResult as String: SecTrustSettingsResult.trustRoot.rawValue
]]
let trustStatus = SecTrustSettingsSetTrustSettings(cert, .user, trustSettings as CFArray)
guard trustStatus == errSecSuccess else {
throw CertificateTrustError.trustFailed(trustStatus)
}
}

public func uninstall(derBytes: Data) throws {
let cert = try secCertificate(from: derBytes)
SecTrustSettingsRemoveTrustSettings(cert, .user)
let removeQuery: [String: Any] = [
kSecClass as String: kSecClassCertificate,
kSecValueRef as String: cert,
]
SecItemDelete(removeQuery as CFDictionary)
}

public func isInstalled(derBytes: Data) -> Bool {
guard let cert = try? secCertificate(from: derBytes) else { return false }
var settings: CFArray?
let status = SecTrustSettingsCopyTrustSettings(cert, .user, &settings)
guard status == errSecSuccess, let array = settings as? [[String: Any]] else {
return false
}
for entry in array {
if let raw = entry[kSecTrustSettingsResult as String] as? Int,
raw == Int(SecTrustSettingsResult.trustRoot.rawValue) {
return true
}
}
return false
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.

private func secCertificate(from derBytes: Data) throws -> SecCertificate {
guard let cert = SecCertificateCreateWithData(nil, derBytes as CFData) else {
throw CertificateTrustError.invalidCertificate
}
return cert
}
}
Loading