diff --git a/README.md b/README.md index f0f5bf5..3daa238 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,28 @@ Secure Enclave to decrypt it: Biometry prompt +On macOS, the prompt also tells you which key is being used, which programs +asked for it, and optionally why, so that you don't approve a request without +knowing what it is: + +- To show a name instead of the key's recipient, list it in + `~/.config/age-plugin-se/names` (or `$XDG_CONFIG_HOME/age-plugin-se/names`), + one key per line: + + age1se1qfn44rsw0xvmez3pky46nghmnd5up0jpj97nd39zptlh83a0nja6skde3ak Backup key + +- The prompt lists the names of the processes that started the decryption, + such as the shell or the script that ran `age`. + +- A script can add a short note by setting `AGE_SE_REASON`: + + $ AGE_SE_REASON="restore backup" age --decrypt -i key.txt -o data.tar.gz data.tar.gz.age + +These lines help you notice requests you didn't expect. They are not a +security boundary: any program running as you can edit the names file, choose +its own process name and note, or use the key from the identity file directly. +Keep the identity file where only the programs you trust can read it. + ### Using `age-plugin-se` with passage diff --git a/Sources/AuthenticationReason.swift b/Sources/AuthenticationReason.swift new file mode 100644 index 0000000..ac75249 --- /dev/null +++ b/Sources/AuthenticationReason.swift @@ -0,0 +1,160 @@ +import Foundation + +#if os(macOS) + import Darwin +#endif + +/// Builds the text shown in the Touch ID / password prompt, so the user can tell +/// what they are approving before they approve it. +/// +/// The goal is to prevent approving by reflex, not to stop a deliberate attacker: +/// any process that can read the identity file can use the Secure Enclave key +/// directly and show whatever prompt it likes. For that reason the facts the plugin +/// can look up itself (which key, which processes) come first, and the text +/// supplied by the caller comes last and is labelled as such. +enum AuthenticationReason { + static let callerReasonVariable = "AGE_SE_REASON" + static let maxAncestors = 5 + + static func describe( + _ recipient: Recipient, + environment env: [String: String] = ProcessInfo.processInfo.environment + ) -> String { + var lines: [String] = [] + + if let name = keyName(for: recipient, environment: env) { + lines.append("unlock key “\(clean(name))”") + } else { + let id = recipient.ageRecipient(type: .se) + lines.append("unlock unnamed key \(id.prefix(12))…\(id.suffix(6))") + } + + let chain = ancestorNames() + if !chain.isEmpty { + lines.append("Requested by: " + chain.map(clean).joined(separator: " › ")) + } + + if let reason = env[callerReasonVariable], !clean(reason).isEmpty { + lines.append("Caller says: \(clean(reason))") + } + + return lines.joined(separator: "\n") + } + + /// Looks the key up in a names file with lines of the form + /// ` `. Blank lines and lines starting with `#` are ignored. + static func keyName(for recipient: Recipient, environment env: [String: String]) -> String? { + let configHome = + env["XDG_CONFIG_HOME"].flatMap { $0.isEmpty ? nil : $0 } + ?? (NSHomeDirectory() + "/.config") + let path = configHome + "/age-plugin-se/names" + guard let contents = try? String(contentsOfFile: path, encoding: .utf8) else { + return nil + } + + var ids = [recipient.ageRecipient(type: .se), recipient.ageRecipient(type: .tag)] + if recipient.mlkem768PublicKey != nil, let pq = try? recipient.ageTagPQRecipient { + ids.append(pq) + } + + for line in contents.split(whereSeparator: \.isNewline) { + let trimmed = line.trimmingCharacters(in: .whitespaces) + if trimmed.isEmpty || trimmed.hasPrefix("#") { + continue + } + let parts = trimmed.split(maxSplits: 1, whereSeparator: \.isWhitespace) + if parts.count == 2, ids.contains(String(parts[0])) { + return parts[1].trimmingCharacters(in: .whitespaces) + } + } + return nil + } + + /// Names of the processes above the plugin, outermost first, ending with the + /// process that started the plugin (normally `age`). + static func ancestorNames() -> [String] { + #if os(macOS) + var names: [String] = [] + var pid = getppid() + while pid > 1 && names.count < maxAncestors { + guard let (name, parent) = processInfo(pid) else { + break + } + names.append(name) + pid = parent + } + return names.reversed() + #else + return [] + #endif + } + + #if os(macOS) + private static func processInfo(_ pid: pid_t) -> (name: String, parent: pid_t)? { + var info = kinfo_proc() + var size = MemoryLayout.stride + var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid] + guard sysctl(&mib, u_int(mib.count), &info, &size, nil, 0) == 0, size > 0 else { + return nil + } + let parent = info.kp_eproc.e_ppid + + // Prefer the name the process was started as (what `ps` shows), because some + // programs live at paths that say little, e.g. Claude Code's executable is + // named after its version number. The process chooses this name itself, which + // is fine here: the prompt guards against approving by mistake, not forgery. + if let name = launchName(pid) { + return (name, parent) + } + + // Otherwise the executable path; p_comm is cut off at 16 bytes. + var buffer = [CChar](repeating: 0, count: 4096) + if proc_pidpath(pid, &buffer, UInt32(buffer.count)) > 0 { + let path = String( + decoding: buffer.prefix(while: { $0 != 0 }).map { UInt8(bitPattern: $0) }, as: UTF8.self) + return ((path as NSString).lastPathComponent, parent) + } + let comm = withUnsafeBytes(of: info.kp_proc.p_comm) { raw in + String(decoding: raw.prefix(while: { $0 != 0 }), as: UTF8.self) + } + return (comm, parent) + } + + /// File name of argv[0], without the leading "-" of login shells. + /// KERN_PROCARGS2 returns argc, then the executable path, padding NULs, then argv. + private static func launchName(_ pid: pid_t) -> String? { + var mib: [Int32] = [CTL_KERN, KERN_PROCARGS2, pid] + var size = 0 + guard sysctl(&mib, u_int(mib.count), nil, &size, nil, 0) == 0, size > 0 else { + return nil + } + var bytes = [UInt8](repeating: 0, count: size) + guard sysctl(&mib, u_int(mib.count), &bytes, &size, nil, 0) == 0 else { + return nil + } + var i = MemoryLayout.size + while i < size && bytes[i] != 0 { i += 1 } // executable path + while i < size && bytes[i] == 0 { i += 1 } // padding + let start = i + while i < size && bytes[i] != 0 { i += 1 } // argv[0] + guard i > start else { + return nil + } + var name = (String(decoding: bytes[start.. String { + let kept = text.unicodeScalars.filter { + $0.properties.generalCategory != .control && $0.properties.generalCategory != .format + } + let result = String(String.UnicodeScalarView(kept)).trimmingCharacters(in: .whitespaces) + return result.count > 80 ? String(result.prefix(80)) + "…" : result + } +} diff --git a/Sources/Crypto.swift b/Sources/Crypto.swift index 059a5ef..4649117 100644 --- a/Sources/Crypto.swift +++ b/Sources/Crypto.swift @@ -59,6 +59,13 @@ protocol Crypto { func newSecureEnclaveMLKEM768PrivateKey(accessControl: SecAccessControl) throws -> SecureEnclaveMLKEM768PrivateKey func encapsulate(mlkem768Key: MLKEM768.PublicKey) throws -> KEM.EncapsulationResult + + /// Text shown in the system authentication prompt for the next key operation. + func setAuthenticationReason(_ reason: String) +} + +extension Crypto { + func setAuthenticationReason(_ reason: String) {} } protocol SecureEnclaveP256PrivateKey { @@ -80,6 +87,10 @@ protocol SecureEnclaveMLKEM768PrivateKey { class CryptoKitCrypto: Crypto { let context = LAContext() + func setAuthenticationReason(_ reason: String) { + context.localizedReason = reason + } + var isSecureEnclaveAvailable: Bool { return SecureEnclave.isAvailable } diff --git a/Sources/Plugin.swift b/Sources/Plugin.swift index d25b06a..af18fd6 100644 --- a/Sources/Plugin.swift +++ b/Sources/Plugin.swift @@ -342,6 +342,7 @@ class Plugin { if identityTag != tag { continue } + crypto.setAuthenticationReason(AuthenticationReason.describe(identity.recipient)) var nonce: ChaChaPoly.Nonce var wrapKey: SymmetricKey diff --git a/Tests/AuthenticationReasonTests.swift b/Tests/AuthenticationReasonTests.swift new file mode 100644 index 0000000..2dfc9de --- /dev/null +++ b/Tests/AuthenticationReasonTests.swift @@ -0,0 +1,101 @@ +import XCTest + +@testable import age_plugin_se + +#if !os(Linux) && !os(Windows) + import CryptoKit +#else + import Crypto +#endif + +final class AuthenticationReasonTests: XCTestCase { + var configHome: URL! + var recipient: Recipient! + + override func setUpWithError() throws { + configHome = FileManager.default.temporaryDirectory + .appendingPathComponent("age-plugin-se-tests-\(UUID().uuidString)") + try FileManager.default.createDirectory( + at: configHome.appendingPathComponent("age-plugin-se"), withIntermediateDirectories: true) + recipient = Recipient(p256PublicKey: P256.KeyAgreement.PrivateKey().publicKey) + } + + override func tearDownWithError() throws { + try? FileManager.default.removeItem(at: configHome) + } + + private var environment: [String: String] { + return ["XDG_CONFIG_HOME": configHome.path] + } + + private func writeNames(_ contents: String) throws { + try contents.write( + to: configHome.appendingPathComponent("age-plugin-se/names"), atomically: true, + encoding: .utf8) + } + + func testKeyName_SERecipient() throws { + try writeNames("\(recipient.ageRecipient(type: .se)) Production key\n") + XCTAssertEqual( + AuthenticationReason.keyName(for: recipient, environment: environment), "Production key") + } + + func testKeyName_TagRecipient() throws { + try writeNames("\(recipient.ageRecipient(type: .tag)) Tag key\n") + XCTAssertEqual( + AuthenticationReason.keyName(for: recipient, environment: environment), "Tag key") + } + + func testKeyName_SkipsCommentsBlankLinesAndOtherKeys() throws { + let other = Recipient(p256PublicKey: P256.KeyAgreement.PrivateKey().publicKey) + try writeNames( + """ + # names for my keys + + \(other.ageRecipient(type: .se)) Other key + \(recipient.ageRecipient(type: .se)) My key + """) + XCTAssertEqual(AuthenticationReason.keyName(for: recipient, environment: environment), "My key") + } + + func testKeyName_NotListed() throws { + try writeNames("# nothing here\n") + XCTAssertNil(AuthenticationReason.keyName(for: recipient, environment: environment)) + } + + func testKeyName_NoFile() throws { + XCTAssertNil(AuthenticationReason.keyName(for: recipient, environment: environment)) + } + + func testClean_RemovesLineBreaksAndControlCharacters() { + XCTAssertEqual( + AuthenticationReason.clean("deploy\nRequested by: zsh\u{7}"), "deployRequested by: zsh") + } + + func testClean_RemovesBidiOverrides() { + XCTAssertEqual(AuthenticationReason.clean("abc\u{202E}def"), "abcdef") + } + + func testClean_Truncates() { + let result = AuthenticationReason.clean(String(repeating: "a", count: 100)) + XCTAssertEqual(result, String(repeating: "a", count: 80) + "…") + } + + func testDescribe_NamedKeyAndCallerNote() throws { + try writeNames("\(recipient.ageRecipient(type: .se)) Production key\n") + var env = environment + env["AGE_SE_REASON"] = "deploy staging" + let lines = AuthenticationReason.describe(recipient, environment: env) + .components(separatedBy: "\n") + XCTAssertEqual(lines.first, "unlock key “Production key”") + XCTAssertEqual(lines.last, "Caller says: deploy staging") + } + + func testDescribe_UnnamedKeyWithoutNote() throws { + let id = recipient.ageRecipient(type: .se) + let lines = AuthenticationReason.describe(recipient, environment: environment) + .components(separatedBy: "\n") + XCTAssertEqual(lines.first, "unlock unnamed key \(id.prefix(12))…\(id.suffix(6))") + XCTAssertFalse(lines.contains { $0.hasPrefix("Caller says:") }) + } +}