mirror of
https://github.com/maxgoedjen/secretive.git
synced 2026-06-19 11:28:58 +02:00
Merge
This commit is contained in:
@@ -19,12 +19,21 @@ let package = Package(
|
||||
.library(
|
||||
name: "SmartCardSecretKit",
|
||||
targets: ["SmartCardSecretKit"]),
|
||||
.library(
|
||||
name: "CertificateKit",
|
||||
targets: ["CertificateKit"]),
|
||||
.library(
|
||||
name: "SecretAgentKit",
|
||||
targets: ["SecretAgentKit"]),
|
||||
.library(
|
||||
name: "Formatters",
|
||||
targets: ["Formatters"]),
|
||||
.library(
|
||||
name: "Common",
|
||||
targets: ["Common"]),
|
||||
.library(
|
||||
name: "SharedXPCServices",
|
||||
targets: ["SharedXPCServices"]),
|
||||
.library(
|
||||
name: "Brief",
|
||||
targets: ["Brief"]),
|
||||
@@ -61,9 +70,15 @@ let package = Package(
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "CertificateKit",
|
||||
dependencies: ["SecretKit", "Formatters"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "SecretAgentKit",
|
||||
dependencies: ["SecretKit", "SSHProtocolKit", "Common"],
|
||||
dependencies: ["SecretKit", "SSHProtocolKit", "CertificateKit", "Common", "Formatters"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
@@ -73,7 +88,7 @@ let package = Package(
|
||||
),
|
||||
.target(
|
||||
name: "SSHProtocolKit",
|
||||
dependencies: ["SecretKit"],
|
||||
dependencies: ["SecretKit", "CertificateKit"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
@@ -82,12 +97,24 @@ let package = Package(
|
||||
dependencies: ["SSHProtocolKit"],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "Formatters",
|
||||
dependencies: [],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "Common",
|
||||
dependencies: ["SSHProtocolKit", "SecretKit"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "SharedXPCServices",
|
||||
dependencies: ["CertificateKit", "SSHProtocolKit"],
|
||||
resources: [localization],
|
||||
swiftSettings: swiftSettings,
|
||||
),
|
||||
.target(
|
||||
name: "Brief",
|
||||
dependencies: ["XPCWrappers", "SSHProtocolKit"],
|
||||
|
||||
@@ -365,16 +365,6 @@
|
||||
},
|
||||
"shouldTranslate" : false
|
||||
},
|
||||
"%@ - %@" : {
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "%1$@ - %2$@"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"about_build_log_button" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
@@ -5557,6 +5547,130 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_critical_options_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Critical Options"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_extensions_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Extensions"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_key_id_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Key ID"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_path_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Certificate Path"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_principals_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Principals"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_serial_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Serial Number"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_sha256_public_key_fingerprint_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Public Key Fingerprint"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_sha256_signing_key_fingerprint_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Signing CA Fingerprint"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_valid_after_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Valid After"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_valid_until_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Valid Until"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"certificate_detail_validity_range_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Validity Range"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Certificates" : {
|
||||
|
||||
},
|
||||
"copyable_click_to_copy_button" : {
|
||||
"extractionState" : "manual",
|
||||
@@ -10004,181 +10118,181 @@
|
||||
"af" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"ar" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"ca" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Esborrar %1$(secretName)@?"
|
||||
"value" : "Esborrar %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"cs" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"da" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"de" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%1$(secretName)@ Löschen?"
|
||||
"value" : "%1$(name)@ Löschen?"
|
||||
}
|
||||
},
|
||||
"el" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"state" : "translated",
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"es" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"fi" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Poista %1$(secretName)@?"
|
||||
"value" : "Poista %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"fr" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Supprimer %1$(secretName)@?"
|
||||
"value" : "Supprimer %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"he" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"hu" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"it" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Eliminare %1$(secretName)@?"
|
||||
"value" : "Eliminare %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"ja" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%1$(secretName)@を削除しますか?"
|
||||
"value" : "%1$(name)@を削除しますか?"
|
||||
}
|
||||
},
|
||||
"ko" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "%1$(secretName)@를 지우겠습니까?"
|
||||
"value" : "%1$(name)@를 지우겠습니까?"
|
||||
}
|
||||
},
|
||||
"nb" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"nl" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"pl" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Usunąć %1$(secretName)@?"
|
||||
"value" : "Usunąć %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"pt" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"pt-BR" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Deletar %1$(secretName)@?"
|
||||
"value" : "Deletar %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"ro" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"ru" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Удалить %1$(secretName)@?"
|
||||
"value" : "Удалить %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"sr" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"sv" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"tr" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"uk" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"vi" : {
|
||||
"stringUnit" : {
|
||||
"state" : "new",
|
||||
"value" : "Delete %1$(secretName)@?"
|
||||
"value" : "Delete %1$(name)@?"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "删除“%1$(secretName)@”吗?"
|
||||
"value" : "删除“%1$(name)@”吗?"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "刪除「%1$(secretName)@」嗎?"
|
||||
"value" : "刪除「%1$(name)@」嗎?"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19647,6 +19761,28 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"rename_certificate_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Name"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"rename_certificate_name_placeholder" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Certificate Name"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"reveal_in_finder_button" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
@@ -19832,11 +19968,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"Review" : {
|
||||
|
||||
},
|
||||
"Review All" : {
|
||||
|
||||
"secret_detail_certificate_path_label" : {
|
||||
"extractionState" : "manual",
|
||||
"localizations" : {
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "Matching Certificates"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"secret_detail_md5_fingerprint_label" : {
|
||||
"extractionState" : "manual",
|
||||
|
||||
24
Sources/Packages/Sources/CertificateKit/Certificate.swift
Normal file
24
Sources/Packages/Sources/CertificateKit/Certificate.swift
Normal file
@@ -0,0 +1,24 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import Formatters
|
||||
|
||||
@dynamicMemberLookup
|
||||
public struct Certificate: Sendable, Codable, Equatable, Hashable, Identifiable, CustomDebugStringConvertible {
|
||||
|
||||
public var openSSHCertificate: OpenSSHCertificate
|
||||
public let rawData: Data
|
||||
|
||||
public init(openSSHCertificate: OpenSSHCertificate, rawData: Data) {
|
||||
self.openSSHCertificate = openSSHCertificate
|
||||
self.rawData = rawData
|
||||
}
|
||||
|
||||
public var id: String { Insecure.MD5.hash(data: rawData).formatted(.hex(separator: "")) }
|
||||
|
||||
public var debugDescription: String { openSSHCertificate.debugDescription }
|
||||
|
||||
public subscript<T>(dynamicMember keyPath: KeyPath<OpenSSHCertificate, T>) -> T {
|
||||
openSSHCertificate[keyPath: keyPath]
|
||||
}
|
||||
|
||||
}
|
||||
153
Sources/Packages/Sources/CertificateKit/CertificateStore.swift
Normal file
153
Sources/Packages/Sources/CertificateKit/CertificateStore.swift
Normal file
@@ -0,0 +1,153 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import Security
|
||||
import os
|
||||
import SecretKit
|
||||
|
||||
@Observable @MainActor public final class CertificateStore: Sendable {
|
||||
|
||||
public private(set) var certificates: [Certificate] = []
|
||||
|
||||
/// Initializes a Store.
|
||||
public init() {
|
||||
loadCertificates()
|
||||
Task {
|
||||
for await note in DistributedNotificationCenter.default().notifications(named: .certificateStoreUpdated) {
|
||||
guard Constants.notificationToken != (note.object as? String) else {
|
||||
// Don't reload if we're the ones triggering this by reloading.
|
||||
continue
|
||||
}
|
||||
loadCertificates()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func reloadCertificates() {
|
||||
let before = certificates
|
||||
certificates.removeAll()
|
||||
loadCertificates()
|
||||
if certificates != before {
|
||||
NotificationCenter.default.post(name: .certificateStoreReloaded, object: self)
|
||||
DistributedNotificationCenter.default().postNotificationName(.certificateStoreUpdated, object: Constants.notificationToken, deliverImmediately: true)
|
||||
}
|
||||
}
|
||||
|
||||
public func save(certificate: Certificate) throws {
|
||||
let attributes = try JSONEncoder().encode(certificate.openSSHCertificate)
|
||||
let keychainAttributes = KeychainDictionary([
|
||||
kSecClass: Constants.keyClass,
|
||||
kSecAttrService: Constants.keyTag,
|
||||
kSecAttrAccount: certificate.id,
|
||||
kSecUseDataProtectionKeychain: true,
|
||||
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
|
||||
kSecValueData: certificate.rawData,
|
||||
kSecAttrGeneric: attributes
|
||||
])
|
||||
let status = SecItemAdd(keychainAttributes, nil)
|
||||
if status != errSecSuccess && status != errSecDuplicateItem {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadCertificates()
|
||||
}
|
||||
|
||||
public func delete(certificate: Certificate) throws {
|
||||
let deleteAttributes = KeychainDictionary([
|
||||
kSecClass: Constants.keyClass,
|
||||
kSecAttrService: Constants.keyTag,
|
||||
kSecUseDataProtectionKeychain: true,
|
||||
kSecAttrAccount: certificate.id,
|
||||
])
|
||||
let status = SecItemDelete(deleteAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadCertificates()
|
||||
}
|
||||
|
||||
public func update(certificate: Certificate) throws {
|
||||
let updateQuery = KeychainDictionary([
|
||||
kSecClass: Constants.keyClass,
|
||||
kSecAttrAccount: certificate.id,
|
||||
])
|
||||
|
||||
let cert = try JSONEncoder().encode(certificate.openSSHCertificate)
|
||||
let updatedAttributes = KeychainDictionary([
|
||||
kSecAttrGeneric: cert,
|
||||
])
|
||||
|
||||
let status = SecItemUpdate(updateQuery, updatedAttributes)
|
||||
if status != errSecSuccess {
|
||||
throw KeychainError(statusCode: status)
|
||||
}
|
||||
reloadCertificates()
|
||||
}
|
||||
|
||||
public func certificates(for secret: any Secret) -> [Certificate] {
|
||||
certificates.filter { $0.openSSHCertificate.publicKey.data == secret.publicKey }
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension CertificateStore {
|
||||
|
||||
/// Loads all certificates from the store.
|
||||
private func loadCertificates() {
|
||||
let queryAttributes = KeychainDictionary([
|
||||
kSecClass: Constants.keyClass,
|
||||
kSecAttrService: Constants.keyTag,
|
||||
kSecUseDataProtectionKeychain: true,
|
||||
kSecReturnData: true,
|
||||
kSecMatchLimit: kSecMatchLimitAll,
|
||||
kSecReturnAttributes: true
|
||||
])
|
||||
var untyped: CFTypeRef?
|
||||
unsafe SecItemCopyMatching(queryAttributes, &untyped)
|
||||
guard let typed = untyped as? [[CFString: Any]] else { return }
|
||||
let decoder = JSONDecoder()
|
||||
let wrapped: [Certificate] = typed.compactMap {
|
||||
do {
|
||||
guard let data = $0[kSecValueData] as? Data,
|
||||
let attributesData = $0[kSecAttrGeneric] as? Data else {
|
||||
throw MissingAttributesError()
|
||||
}
|
||||
return Certificate(openSSHCertificate: try decoder.decode(OpenSSHCertificate.self, from: attributesData), rawData: data)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
.filter {
|
||||
if let validityRange = $0.validityRange {
|
||||
validityRange.contains(Date())
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
certificates.append(contentsOf: wrapped)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension CertificateStore {
|
||||
|
||||
enum Constants {
|
||||
static let keyClass = kSecClassGenericPassword as String
|
||||
static let keyTag = Data("com.maxgoedjen.certificatestore.opensshcertificate".utf8)
|
||||
static let notificationToken = UUID().uuidString
|
||||
}
|
||||
|
||||
struct UnsupportedAlgorithmError: Error {}
|
||||
struct MissingAttributesError: Error {}
|
||||
|
||||
}
|
||||
|
||||
extension NSNotification.Name {
|
||||
|
||||
// Distributed notification that keys were modified out of process (ie, that the management tool added/removed certificates)
|
||||
public static let certificateStoreUpdated = NSNotification.Name("com.maxgoedjen.Secretive.certificateStore.updated")
|
||||
// Internal notification that certificates were reloaded from the backing store.
|
||||
public static let certificateStoreReloaded = NSNotification.Name("com.maxgoedjen.Secretive.certificateStore.reloaded")
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import Foundation
|
||||
import Formatters
|
||||
|
||||
public struct OpenSSHCertificate: Sendable, Codable, Equatable, Hashable, CustomDebugStringConvertible {
|
||||
|
||||
public var type: CertificateType
|
||||
public var name: String
|
||||
public var data: Data
|
||||
|
||||
public var publicKey: PublicKey
|
||||
public var principals: [String]
|
||||
public var keyID: String
|
||||
public var serial: UInt64
|
||||
public var validityRange: Range<Date>?
|
||||
public var criticalOptions: [String]
|
||||
public var extensions: [String]
|
||||
public var signingKey: PublicKey
|
||||
|
||||
public init(
|
||||
type: OpenSSHCertificate.CertificateType,
|
||||
name: String,
|
||||
data: Data,
|
||||
publicKey: PublicKey,
|
||||
principals: [String],
|
||||
keyID: String,
|
||||
serial: UInt64,
|
||||
validityRange: Range<Date>? = nil,
|
||||
criticalOptions: [String],
|
||||
extensions: [String],
|
||||
signingKey: PublicKey,
|
||||
) {
|
||||
self.type = type
|
||||
self.name = name
|
||||
self.data = data
|
||||
self.publicKey = publicKey
|
||||
self.principals = principals
|
||||
self.keyID = keyID
|
||||
self.serial = serial
|
||||
self.validityRange = validityRange
|
||||
self.criticalOptions = criticalOptions
|
||||
self.extensions = extensions
|
||||
self.signingKey = signingKey
|
||||
}
|
||||
|
||||
public var debugDescription: String {
|
||||
"OpenSSH Certificate \(name, default: "Unnamed"): \(data.formatted(.hex()))"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension OpenSSHCertificate {
|
||||
|
||||
public enum CertificateType: String, Sendable, Codable {
|
||||
case ecdsa256 = "ecdsa-sha2-nistp256-cert-v01@openssh.com"
|
||||
case ecdsa384 = "ecdsa-sha2-nistp384-cert-v01@openssh.com"
|
||||
case nistp521 = "ecdsa-sha2-nistp521-cert-v01@openssh.com"
|
||||
|
||||
public var keyIdentifier: String {
|
||||
rawValue.replacingOccurrences(of: "-cert-v01@openssh.com", with: "")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension OpenSSHCertificate {
|
||||
|
||||
public struct PublicKey: Hashable, Sendable, Codable {
|
||||
|
||||
public let keyType: String
|
||||
public let curveName: String
|
||||
public let data: Data
|
||||
|
||||
public init(keyType: String, curveName: String, data: Data) {
|
||||
self.keyType = keyType
|
||||
self.curveName = curveName
|
||||
self.data = data
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
import SSHProtocolKit
|
||||
import CertificateKit
|
||||
import SecretKit
|
||||
|
||||
extension URL {
|
||||
@@ -20,6 +21,10 @@ extension URL {
|
||||
agentHomeURL.appending(component: "PublicKeys")
|
||||
}
|
||||
|
||||
public static var certificatesDirectory: URL {
|
||||
agentHomeURL.appending(component: "Certificates")
|
||||
}
|
||||
|
||||
/// The path for a Secret's public key.
|
||||
/// - Parameter secret: The Secret to return the path for.
|
||||
/// - Returns: The path to the Secret's public key.
|
||||
@@ -30,6 +35,14 @@ extension URL {
|
||||
return directory.appending(component: "\(minimalHex).pub").path()
|
||||
}
|
||||
|
||||
/// The path for a certificate.
|
||||
/// - Parameter certificate: The Certificate to return the path for.
|
||||
/// - Returns: The path to the Certificate.
|
||||
/// - Warning: This method returning a path does not imply that a certificate has been written to disk already. This method only describes where it will be written to.
|
||||
public static func certificatePath(for certificateID: String, in directory: URL) -> String {
|
||||
return directory.appending(component: "\(certificateID)-cert.pub").path()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension String {
|
||||
|
||||
74
Sources/Packages/Sources/Formatters/Data+Hex.swift
Normal file
74
Sources/Packages/Sources/Formatters/Data+Hex.swift
Normal file
@@ -0,0 +1,74 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
public struct HexDataStyle<SequenceType: Sequence>: Hashable, Codable {
|
||||
|
||||
let separator: String
|
||||
|
||||
public init(separator: String) {
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension HexDataStyle: FormatStyle where SequenceType.Element == UInt8 {
|
||||
|
||||
public func format(_ value: SequenceType) -> String {
|
||||
value
|
||||
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
||||
.joined(separator: separator)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FormatStyle where Self == HexDataStyle<Data> {
|
||||
|
||||
public static func hex(separator: String = "") -> HexDataStyle<Data> {
|
||||
HexDataStyle(separator: separator)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FormatStyle where Self == HexDataStyle<Insecure.MD5Digest> {
|
||||
|
||||
public static func hex(separator: String = ":") -> HexDataStyle<Insecure.MD5Digest> {
|
||||
HexDataStyle(separator: separator)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public struct Base64DataStyle<SequenceType: Sequence>: Hashable, Codable {
|
||||
|
||||
private let stripPadding: Bool
|
||||
|
||||
public init(stripPadding: Bool) {
|
||||
self.stripPadding = stripPadding
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Base64DataStyle: FormatStyle where SequenceType.Element == UInt8 {
|
||||
|
||||
public func format(_ value: SequenceType) -> String {
|
||||
let base64 = Data(value).base64EncodedString()
|
||||
let paddingRange = base64.index(base64.endIndex, offsetBy: -2)..<base64.endIndex
|
||||
return base64.replacingOccurrences(of: "=", with: "", range: paddingRange)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FormatStyle where Self == Base64DataStyle<Data> {
|
||||
|
||||
public static func base64(stripPadding: Bool) -> Base64DataStyle<Data> {
|
||||
Base64DataStyle(stripPadding: stripPadding)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FormatStyle where Self == Base64DataStyle<SHA256.Digest> {
|
||||
|
||||
public static func base64(stripPadding: Bool) -> Base64DataStyle<SHA256.Digest> {
|
||||
Base64DataStyle(stripPadding: stripPadding)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
public struct HexDataStyle<SequenceType: Sequence>: Hashable, Codable {
|
||||
|
||||
let separator: String
|
||||
|
||||
public init(separator: String) {
|
||||
self.separator = separator
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension HexDataStyle: FormatStyle where SequenceType.Element == UInt8 {
|
||||
|
||||
public func format(_ value: SequenceType) -> String {
|
||||
value
|
||||
.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }
|
||||
.joined(separator: separator)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FormatStyle where Self == HexDataStyle<Data> {
|
||||
|
||||
public static func hex(separator: String = "") -> HexDataStyle<Data> {
|
||||
HexDataStyle(separator: separator)
|
||||
}
|
||||
|
||||
}
|
||||
extension FormatStyle where Self == HexDataStyle<Insecure.MD5Digest> {
|
||||
|
||||
public static func hex(separator: String = ":") -> HexDataStyle<Insecure.MD5Digest> {
|
||||
HexDataStyle(separator: separator)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import CertificateKit
|
||||
import Formatters
|
||||
|
||||
/// Generates OpenSSH representations of Certificates.
|
||||
public struct OpenSSHCertificateWriter: Sendable {
|
||||
|
||||
/// Initializes the writer.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Generates an OpenSSH data payload identifying the certificate.
|
||||
/// - Returns: OpenSSH data payload identifying the certificate.
|
||||
public func data(publicKey: OpenSSHCertificate.PublicKey) -> Data {
|
||||
// https://datatracker.ietf.org/doc/html/rfc5656#section-3.1
|
||||
publicKey.keyType.lengthAndData +
|
||||
publicKey.curveName.lengthAndData +
|
||||
publicKey.data.lengthAndData
|
||||
}
|
||||
|
||||
/// Generates an OpenSSH SHA256 fingerprint string.
|
||||
/// - Returns: OpenSSH SHA256 fingerprint string.
|
||||
public func openSSHSHA256KeyFingerprint(publicKey: OpenSSHCertificate.PublicKey) -> String {
|
||||
// OpenSSL format seems to strip the padding at the end.
|
||||
let cleaned = SHA256.hash(data: data(publicKey: publicKey)).formatted(.base64(stripPadding: true))
|
||||
return "SHA256:\(cleaned)"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import Foundation
|
||||
import CertificateKit
|
||||
|
||||
public protocol OpenSSHCertificateParserProtocol {
|
||||
func parse(data: Data) async throws -> OpenSSHCertificate
|
||||
}
|
||||
|
||||
public struct OpenSSHCertificateParser: OpenSSHCertificateParserProtocol, Sendable {
|
||||
|
||||
public init() {
|
||||
assert(Bundle.main.bundleURL.pathExtension == "xpc" || ProcessInfo.processInfo.processName == "xctest", "Potentially unsafe parsing code should run in an XPC service")
|
||||
}
|
||||
|
||||
public func parse(data: Data) throws(OpenSSHCertificateError) -> OpenSSHCertificate {
|
||||
let string = String(decoding: data, as: UTF8.self)
|
||||
var elements = string
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
.components(separatedBy: " ")
|
||||
guard elements.count >= 2 else {
|
||||
throw OpenSSHCertificateError.parsingFailed
|
||||
}
|
||||
let typeString = elements.removeFirst()
|
||||
guard let type = OpenSSHCertificate.CertificateType(rawValue: typeString) else { throw .unsupportedType }
|
||||
let encodedKey = elements.removeFirst()
|
||||
guard let decoded = Data(base64Encoded: encodedKey) else {
|
||||
throw OpenSSHCertificateError.parsingFailed
|
||||
}
|
||||
let comment = elements.first
|
||||
do {
|
||||
let dataParser = OpenSSHReader(data: decoded)
|
||||
let publicKeyType = try dataParser.readNextChunkAsString() // Theoretically the same as typeString, but
|
||||
.replacingOccurrences(of: "-cert-v01@openssh.com", with: "")
|
||||
_ = try dataParser.readNextChunk() // Nonce
|
||||
let publicKeyCurveName = try dataParser.readNextChunkAsString()
|
||||
let publicKeyData = try dataParser.readNextChunk()
|
||||
let publicKey = OpenSSHCertificate.PublicKey(keyType: publicKeyType, curveName: publicKeyCurveName, data: publicKeyData)
|
||||
let serialNumber = try dataParser.readNextBytes(as: UInt64.self, convertEndianness: true)
|
||||
let role = try dataParser.readNextBytes(as: UInt32.self, convertEndianness: true)
|
||||
_ = role
|
||||
let keyIdentifier = try dataParser.readNextChunkAsString()
|
||||
let principalsReader = try dataParser.readNextChunkAsSubReader()
|
||||
var principals: [String] = []
|
||||
while !principalsReader.done {
|
||||
try principals.append(principalsReader.readNextChunkAsString())
|
||||
}
|
||||
let validAfter = try dataParser.readNextBytes(as: UInt64.self, convertEndianness: true)
|
||||
let validBefore = try dataParser.readNextBytes(as: UInt64.self, convertEndianness: true)
|
||||
let validityRange = Date(timeIntervalSince1970: TimeInterval(validAfter))..<Date(timeIntervalSince1970: TimeInterval(validBefore))
|
||||
let criticalOptionsReader = try dataParser.readNextChunkAsSubReader()
|
||||
var criticalOptions: [String] = []
|
||||
while !criticalOptionsReader.done {
|
||||
let next = try criticalOptionsReader.readNextChunkAsString()
|
||||
if !next.isEmpty {
|
||||
criticalOptions.append(next)
|
||||
}
|
||||
}
|
||||
let extensionsReader = try dataParser.readNextChunkAsSubReader()
|
||||
var extensions: [String] = []
|
||||
while !extensionsReader.done {
|
||||
let next = try extensionsReader.readNextChunkAsString()
|
||||
if !next.isEmpty {
|
||||
extensions.append(next)
|
||||
}
|
||||
}
|
||||
_ = try dataParser.readNextChunk() // reserved
|
||||
let signingKeyReader = try dataParser.readNextChunkAsSubReader()
|
||||
let signingKeyType = try signingKeyReader.readNextChunkAsString()
|
||||
let signingKeyCurveName = try signingKeyReader.readNextChunkAsString()
|
||||
let signingKeyData = try signingKeyReader.readNextChunk()
|
||||
let signingKey = OpenSSHCertificate.PublicKey(keyType: signingKeyType, curveName: signingKeyCurveName, data: signingKeyData)
|
||||
|
||||
return OpenSSHCertificate(
|
||||
type: type,
|
||||
name: comment ?? keyIdentifier,
|
||||
data: decoded,
|
||||
publicKey: publicKey,
|
||||
principals: principals,
|
||||
keyID: keyIdentifier,
|
||||
serial: serialNumber,
|
||||
validityRange: validityRange,
|
||||
criticalOptions: criticalOptions,
|
||||
extensions: extensions,
|
||||
signingKey: signingKey,
|
||||
)
|
||||
} catch {
|
||||
throw .parsingFailed
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public enum OpenSSHCertificateError: Error, Codable {
|
||||
case unsupportedType
|
||||
case parsingFailed
|
||||
}
|
||||
@@ -41,9 +41,7 @@ public struct OpenSSHPublicKeyWriter: Sendable {
|
||||
/// - Returns: OpenSSH SHA256 fingerprint string.
|
||||
public func openSSHSHA256Fingerprint<SecretType: Secret>(secret: SecretType) -> String {
|
||||
// OpenSSL format seems to strip the padding at the end.
|
||||
let base64 = Data(SHA256.hash(data: data(secret: secret))).base64EncodedString()
|
||||
let paddingRange = base64.index(base64.endIndex, offsetBy: -2)..<base64.endIndex
|
||||
let cleaned = base64.replacingOccurrences(of: "=", with: "", range: paddingRange)
|
||||
let cleaned = SHA256.hash(data: data(secret: secret)).formatted(.base64(stripPadding: true))
|
||||
return "SHA256:\(cleaned)"
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,9 @@ public final class OpenSSHReader {
|
||||
/// - Parameter data: The data to read.
|
||||
public init(data: Data) {
|
||||
remaining = Data(data)
|
||||
if remaining.count == 0 {
|
||||
done = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the next chunk of data from the playload.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import SecretKit
|
||||
import SSHProtocolKit
|
||||
import CertificateKit
|
||||
|
||||
public protocol SSHAgentInputParserProtocol {
|
||||
|
||||
@@ -14,7 +14,7 @@ public struct SSHAgentInputParser: SSHAgentInputParserProtocol {
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "InputParser")
|
||||
|
||||
public init() {
|
||||
|
||||
assert(Bundle.main.bundleURL.pathExtension == "xpc" || ProcessInfo.processInfo.processName == "xctest", "Potentially unsafe parsing code should run in an XPC service")
|
||||
}
|
||||
|
||||
public func parse(data: Data) throws(AgentParsingError) -> SSHAgent.Request {
|
||||
@@ -75,21 +75,16 @@ extension SSHAgentInputParser {
|
||||
func certificatePublicKeyBlob(from hash: Data) -> Data? {
|
||||
let reader = OpenSSHReader(data: hash)
|
||||
do {
|
||||
let certType = String(decoding: try reader.readNextChunk(), as: UTF8.self)
|
||||
switch certType {
|
||||
case "ecdsa-sha2-nistp256-cert-v01@openssh.com",
|
||||
"ecdsa-sha2-nistp384-cert-v01@openssh.com",
|
||||
"ecdsa-sha2-nistp521-cert-v01@openssh.com":
|
||||
_ = try reader.readNextChunk() // nonce
|
||||
let curveIdentifier = try reader.readNextChunk()
|
||||
let publicKey = try reader.readNextChunk()
|
||||
let openSSHIdentifier = certType.replacingOccurrences(of: "-cert-v01@openssh.com", with: "")
|
||||
return openSSHIdentifier.lengthAndData +
|
||||
curveIdentifier.lengthAndData +
|
||||
let certType = try reader.readNextChunkAsString()
|
||||
guard let certType = OpenSSHCertificate.CertificateType(rawValue: certType) else { return nil }
|
||||
_ = try reader.readNextChunk() // nonce
|
||||
let curveIdentifier = try reader.readNextChunk()
|
||||
let publicKey = try reader.readNextChunk()
|
||||
let openSSHIdentifier = certType.keyIdentifier
|
||||
return openSSHIdentifier.lengthAndData +
|
||||
curveIdentifier.lengthAndData +
|
||||
publicKey.lengthAndData
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import Foundation
|
||||
import CryptoKit
|
||||
import OSLog
|
||||
import SecretKit
|
||||
import CertificateKit
|
||||
import AppKit
|
||||
import SSHProtocolKit
|
||||
|
||||
@@ -9,25 +10,32 @@ import SSHProtocolKit
|
||||
public final class Agent: Sendable {
|
||||
|
||||
private let storeList: SecretStoreList
|
||||
<<<<<<< HEAD
|
||||
private let authenticationHandler: AuthenticationHandler
|
||||
=======
|
||||
private let certificateStore: CertificateStore
|
||||
>>>>>>> main
|
||||
private let witness: SigningWitness?
|
||||
private let publicKeyWriter = OpenSSHPublicKeyWriter()
|
||||
private let signatureWriter = OpenSSHSignatureWriter()
|
||||
private let certificateHandler = OpenSSHCertificateHandler()
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "Agent")
|
||||
|
||||
/// Initializes an agent with a store list and a witness.
|
||||
/// - Parameters:
|
||||
/// - storeList: The `SecretStoreList` to make available.
|
||||
/// - witness: A witness to notify of requests.
|
||||
<<<<<<< HEAD
|
||||
public init(storeList: SecretStoreList, authenticationHandler: AuthenticationHandler, witness: SigningWitness? = nil) {
|
||||
logger.debug("Agent is running")
|
||||
self.storeList = storeList
|
||||
self.authenticationHandler = authenticationHandler
|
||||
=======
|
||||
public init(storeList: SecretStoreList, certificateStore: CertificateStore, witness: SigningWitness? = nil) {
|
||||
logger.debug("Agent is running")
|
||||
self.storeList = storeList
|
||||
self.certificateStore = certificateStore
|
||||
>>>>>>> main
|
||||
self.witness = witness
|
||||
Task { @MainActor in
|
||||
await certificateHandler.reloadCertificates(for: storeList.allSecrets)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -70,7 +78,6 @@ extension Agent {
|
||||
/// - Returns: An OpenSSH formatted Data payload listing the identities available for signing operations.
|
||||
func identities() async -> Data {
|
||||
let secrets = await storeList.allSecrets
|
||||
await certificateHandler.reloadCertificates(for: secrets)
|
||||
var count = 0
|
||||
var keyData = Data()
|
||||
|
||||
@@ -79,10 +86,9 @@ extension Agent {
|
||||
keyData.append(keyBlob.lengthAndData)
|
||||
keyData.append(publicKeyWriter.comment(secret: secret).lengthAndData)
|
||||
count += 1
|
||||
|
||||
if let (certificateData, name) = try? await certificateHandler.keyBlobAndName(for: secret) {
|
||||
keyData.append(certificateData.lengthAndData)
|
||||
keyData.append(name.lengthAndData)
|
||||
for certificate in await certificateStore.certificates(for: secret) {
|
||||
keyData.append(certificate.data.lengthAndData)
|
||||
keyData.append(certificate.name.lengthAndData)
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
@@ -99,7 +105,7 @@ extension Agent {
|
||||
/// - Returns: An OpenSSH formatted Data payload containing the signed data response.
|
||||
func sign(data: Data, keyBlob: Data, provenance: SigningRequestProvenance) async throws -> Data {
|
||||
guard let (secret, store) = await secret(matching: keyBlob) else {
|
||||
let keyBlobHex = keyBlob.compactMap { ("0" + String($0, radix: 16, uppercase: false)).suffix(2) }.joined()
|
||||
let keyBlobHex = keyBlob.formatted(.hex())
|
||||
logger.debug("Agent did not have a key matching \(keyBlobHex)")
|
||||
throw NoMatchingKeyError()
|
||||
}
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import SecretKit
|
||||
import SSHProtocolKit
|
||||
|
||||
/// Manages storage and lookup for OpenSSH certificates.
|
||||
public actor OpenSSHCertificateHandler: Sendable {
|
||||
|
||||
private let publicKeyFileStoreController = PublicKeyFileStoreController(directory: URL.publicKeyDirectory)
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "OpenSSHCertificateHandler")
|
||||
private let writer = OpenSSHPublicKeyWriter()
|
||||
private var keyBlobsAndNames: [AnySecret: (Data, Data)] = [:]
|
||||
|
||||
/// Initializes an OpenSSHCertificateHandler.
|
||||
public init() {
|
||||
}
|
||||
|
||||
/// Reloads any certificates in the PublicKeys folder.
|
||||
/// - Parameter secrets: the secrets to look up corresponding certificates for.
|
||||
public func reloadCertificates(for secrets: [AnySecret]) {
|
||||
guard publicKeyFileStoreController.hasAnyCertificates else {
|
||||
logger.log("No certificates, short circuiting")
|
||||
return
|
||||
}
|
||||
keyBlobsAndNames = secrets.reduce(into: [:]) { partialResult, next in
|
||||
partialResult[next] = try? loadKeyblobAndName(for: next)
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||
/// - Parameter secret: The secret to search for a certificate with
|
||||
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||
public func keyBlobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||
keyBlobsAndNames[AnySecret(secret)]
|
||||
}
|
||||
|
||||
/// Attempts to find an OpenSSH Certificate that corresponds to a ``Secret``
|
||||
/// - Parameter secret: The secret to search for a certificate with
|
||||
/// - Returns: A (``Data``, ``Data``) tuple containing the certificate and certificate name, respectively.
|
||||
private func loadKeyblobAndName<SecretType: Secret>(for secret: SecretType) throws -> (Data, Data)? {
|
||||
let certificatePath = publicKeyFileStoreController.sshCertificatePath(for: secret)
|
||||
guard FileManager.default.fileExists(atPath: certificatePath) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.debug("Found certificate for \(secret.name)")
|
||||
let certContent = try String(contentsOfFile:certificatePath, encoding: .utf8)
|
||||
let certElements = certContent.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ")
|
||||
|
||||
guard certElements.count >= 2 else {
|
||||
logger.warning("Certificate found for \(secret.name) but failed to load")
|
||||
throw OpenSSHCertificateError.parsingFailed
|
||||
}
|
||||
guard let certDecoded = Data(base64Encoded: certElements[1] as String) else {
|
||||
logger.warning("Certificate found for \(secret.name) but failed to decode base64 key")
|
||||
throw OpenSSHCertificateError.parsingFailed
|
||||
}
|
||||
|
||||
if certElements.count >= 3 {
|
||||
let certName = Data(certElements[2].utf8)
|
||||
return (certDecoded, certName)
|
||||
}
|
||||
let certName = Data(secret.name.utf8)
|
||||
logger.info("Certificate for \(secret.name) does not have a name tag, using secret name instead")
|
||||
return (certDecoded, certName)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension OpenSSHCertificateHandler {
|
||||
|
||||
enum OpenSSHCertificateError: LocalizedError {
|
||||
case unsupportedType
|
||||
case parsingFailed
|
||||
case doesNotExist
|
||||
|
||||
public var errorDescription: String? {
|
||||
switch self {
|
||||
case .unsupportedType:
|
||||
return "The key type was unsupported"
|
||||
case .parsingFailed:
|
||||
return "Failed to properly parse the SSH certificate"
|
||||
case .doesNotExist:
|
||||
return "Certificate does not exist"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,18 +2,21 @@ import Foundation
|
||||
import OSLog
|
||||
import SecretKit
|
||||
import SSHProtocolKit
|
||||
import CertificateKit
|
||||
import Common
|
||||
|
||||
/// Controller responsible for writing public keys to disk, so that they're easily accessible by scripts.
|
||||
public final class PublicKeyFileStoreController: Sendable {
|
||||
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.secretagent", category: "PublicKeyFileStoreController")
|
||||
private let directory: URL
|
||||
private let publicKeysURL: URL
|
||||
private let certificatesURL: URL
|
||||
private let keyWriter = OpenSSHPublicKeyWriter()
|
||||
|
||||
/// Initializes a PublicKeyFileStoreController.
|
||||
public init(directory: URL) {
|
||||
self.directory = directory
|
||||
public init(publicKeysURL: URL, certificatesURL: URL) {
|
||||
self.publicKeysURL = publicKeysURL
|
||||
self.certificatesURL = certificatesURL
|
||||
}
|
||||
|
||||
/// Writes out the keys specified to disk.
|
||||
@@ -22,10 +25,10 @@ public final class PublicKeyFileStoreController: Sendable {
|
||||
public func generatePublicKeys(for secrets: [AnySecret], clear: Bool = false) throws {
|
||||
logger.log("Writing public keys to disk")
|
||||
if clear {
|
||||
let validPaths = Set(secrets.map { URL.publicKeyPath(for: $0, in: directory) })
|
||||
.union(Set(secrets.map { sshCertificatePath(for: $0) }))
|
||||
let contentsOfDirectory = (try? FileManager.default.contentsOfDirectory(atPath: directory.path())) ?? []
|
||||
let fullPathContents = contentsOfDirectory.map { directory.appending(path: $0).path() }
|
||||
let validPaths = Set(secrets.map { URL.publicKeyPath(for: $0, in: publicKeysURL) })
|
||||
.union(Set(secrets.map { legacySSHCertificatePath(for: $0) }))
|
||||
let contentsOfDirectory = (try? FileManager.default.contentsOfDirectory(atPath: publicKeysURL.path())) ?? []
|
||||
let fullPathContents = contentsOfDirectory.map { publicKeysURL.appending(path: $0).path() }
|
||||
|
||||
let untracked = Set(fullPathContents)
|
||||
.subtracting(validPaths)
|
||||
@@ -34,35 +37,47 @@ public final class PublicKeyFileStoreController: Sendable {
|
||||
try? FileManager.default.removeItem(at: URL(string: path)!)
|
||||
}
|
||||
}
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: nil)
|
||||
try? FileManager.default.createDirectory(at: publicKeysURL, withIntermediateDirectories: false, attributes: nil)
|
||||
for secret in secrets {
|
||||
let path = URL.publicKeyPath(for: secret, in: directory)
|
||||
let path = URL.publicKeyPath(for: secret, in: publicKeysURL)
|
||||
let data = Data(keyWriter.openSSHString(secret: secret).utf8)
|
||||
FileManager.default.createFile(atPath: path, contents: data, attributes: nil)
|
||||
}
|
||||
logger.log("Finished writing public keys")
|
||||
}
|
||||
|
||||
/// Writes out the certificates specified to disk.
|
||||
/// - Parameter certificates: The Secrets to generate keys for.
|
||||
/// - Parameter clear: Whether or not any untracked files in the directory should be removed.
|
||||
public func generateCertificates(for certificates: [Certificate], clear: Bool = false) throws {
|
||||
logger.log("Writing certificates to disk")
|
||||
if clear {
|
||||
let validPaths = Set(certificates.map { URL.certificatePath(for: $0.id, in: certificatesURL) })
|
||||
let contentsOfDirectory = (try? FileManager.default.contentsOfDirectory(atPath: certificatesURL.path())) ?? []
|
||||
let fullPathContents = contentsOfDirectory.map { certificatesURL.appending(path: $0).path() }
|
||||
|
||||
/// Short-circuit check to ship enumerating a bunch of paths if there's nothing in the cert directory.
|
||||
public var hasAnyCertificates: Bool {
|
||||
do {
|
||||
return try FileManager.default
|
||||
.contentsOfDirectory(atPath: directory.path())
|
||||
.filter { $0.hasSuffix("-cert.pub") }
|
||||
.isEmpty == false
|
||||
} catch {
|
||||
return false
|
||||
let untracked = Set(fullPathContents)
|
||||
.subtracting(validPaths)
|
||||
for path in untracked {
|
||||
// string instead of fileURLWithPath since we're already using fileURL format.
|
||||
try? FileManager.default.removeItem(at: URL(string: path)!)
|
||||
}
|
||||
}
|
||||
try? FileManager.default.createDirectory(at: certificatesURL, withIntermediateDirectories: false, attributes: nil)
|
||||
for certificate in certificates {
|
||||
let path = URL.certificatePath(for: certificate.id, in: certificatesURL)
|
||||
FileManager.default.createFile(atPath: path, contents: certificate.rawData, attributes: nil)
|
||||
}
|
||||
logger.log("Finished writing certificates")
|
||||
}
|
||||
|
||||
/// The path for a Secret's SSH Certificate public key.
|
||||
/// - Parameter secret: The Secret to return the path for.
|
||||
/// - Returns: The path to the SSH Certificate public key.
|
||||
/// - Warning: This method returning a path does not imply that a key has a SSH certificates. This method only describes where it will be.
|
||||
public func sshCertificatePath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||
private func legacySSHCertificatePath<SecretType: Secret>(for secret: SecretType) -> String {
|
||||
let minimalHex = keyWriter.openSSHMD5Fingerprint(secret: secret).replacingOccurrences(of: ":", with: "")
|
||||
return directory.appending(component: "\(minimalHex)-cert.pub").path()
|
||||
return publicKeysURL.appending(component: "\(minimalHex).pub").path()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import Foundation
|
||||
import Security
|
||||
import CryptoTokenKit
|
||||
import CryptoKit
|
||||
import os
|
||||
import SSHProtocolKit
|
||||
import CertificateKit
|
||||
|
||||
public struct CertificateMigrator {
|
||||
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive.migration", category: "CertificateKitMigrator")
|
||||
private let publicKeysDirectory: URL
|
||||
private let certificatesDirectory: URL
|
||||
private let certificateStore: CertificateStore
|
||||
|
||||
/// Initializes a PublicKeyFileStoreController.
|
||||
public init(homeDirectory: URL, certificateStore: CertificateStore) {
|
||||
publicKeysDirectory = homeDirectory.appending(component: "PublicKeys")
|
||||
certificatesDirectory = homeDirectory.appending(component: "Certificates")
|
||||
self.certificateStore = certificateStore
|
||||
}
|
||||
|
||||
@MainActor public func migrate() throws {
|
||||
try migrate(directory: publicKeysDirectory)
|
||||
try migrate(directory: certificatesDirectory)
|
||||
}
|
||||
|
||||
@MainActor public func migrate(directory: URL) throws {
|
||||
let fileCerts = try FileManager.default
|
||||
.contentsOfDirectory(atPath: directory.path())
|
||||
.filter { $0.hasSuffix("-cert.pub") }
|
||||
Task {
|
||||
for path in fileCerts {
|
||||
do {
|
||||
let url = directory.appending(component: path)
|
||||
let data = try Data(contentsOf: url)
|
||||
let parser = try await XPCCertificateParser()
|
||||
let cert = try await parser.parse(data: data)
|
||||
try certificateStore.save(certificate: Certificate(openSSHCertificate: cert, rawData: data))
|
||||
do {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
} catch {
|
||||
logger.error("Failed to delete successfully migrated cert: \(path)")
|
||||
}
|
||||
} catch {
|
||||
logger.error("Failed to migrate cert: \(path)")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import SSHProtocolKit
|
||||
import CertificateKit
|
||||
import XPCWrappers
|
||||
|
||||
/// Delegates all agent input parsing to an XPC service which wraps OpenSSH
|
||||
public final class XPCCertificateParser: OpenSSHCertificateParserProtocol {
|
||||
|
||||
private let logger = Logger(subsystem: "com.maxgoedjen.secretive", category: "XPCCertificateParser")
|
||||
private let session: XPCTypedSession<OpenSSHCertificate, OpenSSHCertificateError>
|
||||
|
||||
public init() async throws {
|
||||
logger.debug("Creating XPCCertificateParser")
|
||||
session = try await XPCTypedSession(serviceName: "com.maxgoedjen.Secretive.SecretiveCertificateParser", warmup: true)
|
||||
logger.debug("XPCCertificateParser is warmed up.")
|
||||
}
|
||||
|
||||
public func parse(data: Data) async throws -> OpenSSHCertificate {
|
||||
logger.debug("Parsing input")
|
||||
defer { logger.debug("Parsed input") }
|
||||
return try await session.send(data)
|
||||
}
|
||||
|
||||
deinit {
|
||||
session.complete()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import CryptoKit
|
||||
import CertificateKit
|
||||
@testable import SSHProtocolKit
|
||||
@testable import SecretKit
|
||||
@testable import SecretAgentKit
|
||||
|
||||
@Suite struct AgentTests {
|
||||
@Suite @MainActor struct AgentTests {
|
||||
|
||||
// MARK: Identity Listing
|
||||
|
||||
@Test func emptyStores() async throws {
|
||||
let agent = Agent(storeList: SecretStoreList())
|
||||
let agent = Agent(storeList: SecretStoreList(), certificateStore: CertificateStore())
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities)
|
||||
let response = await agent.handle(request: request, provenance: .test)
|
||||
#expect(response == Constants.Responses.requestIdentitiesEmpty)
|
||||
@@ -18,7 +19,7 @@ import CryptoKit
|
||||
|
||||
@Test func identitiesList() async throws {
|
||||
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let agent = Agent(storeList: list)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore())
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestIdentities)
|
||||
let response = await agent.handle(request: request, provenance: .test)
|
||||
|
||||
@@ -32,7 +33,7 @@ import CryptoKit
|
||||
|
||||
@Test func noMatchingIdentities() async throws {
|
||||
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let agent = Agent(storeList: list)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore())
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignatureWithNoneMatching)
|
||||
let response = await agent.handle(request: request, provenance: .test)
|
||||
#expect(response == Constants.Responses.requestFailure)
|
||||
@@ -42,7 +43,7 @@ import CryptoKit
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||
guard case SSHAgent.Request.signRequest(let context) = request else { return }
|
||||
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let agent = Agent(storeList: list)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore())
|
||||
let response = await agent.handle(request: request, provenance: .test)
|
||||
let responseReader = OpenSSHReader(data: response)
|
||||
let length = try responseReader.readNextBytes(as: UInt32.self)
|
||||
@@ -77,7 +78,7 @@ import CryptoKit
|
||||
let witness = StubWitness(speakNow: { _,_ in
|
||||
return true
|
||||
}, witness: { _, _ in })
|
||||
let agent = Agent(storeList: list, witness: witness)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore(), witness: witness)
|
||||
let response = await agent.handle(request: .signRequest(.empty), provenance: .test)
|
||||
#expect(response == Constants.Responses.requestFailure)
|
||||
}
|
||||
@@ -90,7 +91,7 @@ import CryptoKit
|
||||
}, witness: { _, trace in
|
||||
witnessed = true
|
||||
})
|
||||
let agent = Agent(storeList: list, witness: witness)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore(), witness: witness)
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||
_ = await agent.handle(request: request, provenance: .test)
|
||||
#expect(witnessed)
|
||||
@@ -106,7 +107,7 @@ import CryptoKit
|
||||
}, witness: { _, trace in
|
||||
witnessTrace = trace
|
||||
})
|
||||
let agent = Agent(storeList: list, witness: witness)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore(), witness: witness)
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||
_ = await agent.handle(request: request, provenance: .test)
|
||||
#expect(witnessTrace == speakNowTrace)
|
||||
@@ -117,9 +118,9 @@ import CryptoKit
|
||||
|
||||
@Test func signatureException() async throws {
|
||||
let list = await storeList(with: [Constants.Secrets.ecdsa256Secret, Constants.Secrets.ecdsa384Secret])
|
||||
let store = await list.stores.first?.base as! Stub.Store
|
||||
let store = list.stores.first?.base as! Stub.Store
|
||||
store.shouldThrow = true
|
||||
let agent = Agent(storeList: list)
|
||||
let agent = Agent(storeList: list, certificateStore: CertificateStore())
|
||||
let request = try SSHAgentInputParser().parse(data: Constants.Requests.requestSignature)
|
||||
let response = await agent.handle(request: request, provenance: .test)
|
||||
#expect(response == Constants.Responses.requestFailure)
|
||||
@@ -128,7 +129,7 @@ import CryptoKit
|
||||
// MARK: Unsupported
|
||||
|
||||
@Test func unhandledAdd() async throws {
|
||||
let agent = Agent(storeList: SecretStoreList())
|
||||
let agent = Agent(storeList: SecretStoreList(), certificateStore: CertificateStore())
|
||||
let response = await agent.handle(request: .addIdentity, provenance: .test)
|
||||
#expect(response == Constants.Responses.requestFailure)
|
||||
}
|
||||
@@ -143,7 +144,7 @@ extension SigningRequestProvenance {
|
||||
|
||||
extension AgentTests {
|
||||
|
||||
@MainActor func storeList(with secrets: [Stub.Secret]) async -> SecretStoreList {
|
||||
func storeList(with secrets: [Stub.Secret]) async -> SecretStoreList {
|
||||
let store = Stub.Store()
|
||||
store.secrets.append(contentsOf: secrets)
|
||||
let storeList = SecretStoreList()
|
||||
|
||||
Reference in New Issue
Block a user