-
Notifications
You must be signed in to change notification settings - Fork 70
M2: CA persistence + Keychain trust + system proxy toggle #73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kalil0321
wants to merge
3
commits into
claude/system-proxy-monitor-UEsLp
Choose a base branch
from
claude/proxy-monitor-m2-ca-keychain
base: claude/system-proxy-monitor-UEsLp
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| } | ||
|
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) | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | ||
| } | ||
| } |
66 changes: 66 additions & 0 deletions
66
macos/Sources/ReverseAPIProxy/System/CertificateTrustInstaller.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
|
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 | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.