1pub use keychain_core;
13
14use std::path::PathBuf;
15
16use clap::Parser;
17use keychain_core::{GenericSecret, Keychain, KeychainError};
18use serde::Serialize;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
22#[serde(rename_all = "kebab-case")]
23pub enum FindingKind {
24 GenericSecret,
26 SafeStorageKey,
28}
29
30#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32pub struct Finding {
33 pub kind: FindingKind,
34 pub account: String,
35 pub service: String,
36 pub label: String,
37 pub secret: String,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
43pub struct AuditReport {
44 pub findings: Vec<Finding>,
45 pub key_count: usize,
47}
48
49#[must_use]
56pub fn classify(service: &str) -> FindingKind {
57 if service.ends_with("Safe Storage") {
58 FindingKind::SafeStorageKey
59 } else {
60 FindingKind::GenericSecret
61 }
62}
63
64fn to_finding(s: GenericSecret) -> Finding {
65 Finding {
66 kind: classify(&s.service),
67 secret: s.display(),
68 account: s.account,
69 service: s.service,
70 label: s.label,
71 }
72}
73
74pub fn audit(data: &[u8], password: &[u8]) -> Result<AuditReport, KeychainError> {
79 let kc = Keychain::open(data)?;
80 let unlocked = kc.unlock(password)?;
81 let findings = unlocked
82 .generic_secrets()
83 .into_iter()
84 .map(to_finding)
85 .collect();
86 Ok(AuditReport {
87 findings,
88 key_count: unlocked.key_count(),
89 })
90}
91
92#[derive(Debug)]
94pub enum CliError {
95 Io(String),
97 Parse(KeychainError),
99 Locked(String),
101}
102
103impl std::fmt::Display for CliError {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 match self {
106 CliError::Io(s) => write!(f, "io error: {s}"),
107 CliError::Parse(e) => write!(f, "not a usable keychain: {e}"),
108 CliError::Locked(path) => write!(
109 f,
110 "{path}: keychain present but LOCKED — the supplied login password did not unwrap the DBKey"
111 ),
112 }
113 }
114}
115
116impl std::error::Error for CliError {}
117
118#[derive(Debug, Parser)]
120#[command(
121 name = "kc4n6",
122 version,
123 about = "Offline macOS keychain secret recovery"
124)]
125pub struct Cli {
126 pub keychain: PathBuf,
128 #[arg(long)]
130 pub password: String,
131 #[arg(long)]
133 pub json: bool,
134}
135
136impl Cli {
137 pub fn run(&self) -> Result<AuditReport, CliError> {
139 let data = std::fs::read(&self.keychain)
140 .map_err(|e| CliError::Io(format!("{}: {e}", self.keychain.display())))?;
141 match audit(&data, self.password.as_bytes()) {
142 Ok(report) => Ok(report),
143 Err(KeychainError::Locked) => {
144 Err(CliError::Locked(self.keychain.display().to_string()))
145 }
146 Err(e) => Err(CliError::Parse(e)),
147 }
148 }
149}
150
151#[must_use]
153pub fn render_text(report: &AuditReport) -> String {
154 use std::fmt::Write as _;
155 let mut out = String::new();
156 if report.findings.is_empty() {
157 let _ = writeln!(
158 out,
159 "Unlocked ({} record keys) but recovered no generic secrets.",
160 report.key_count
161 );
162 return out;
163 }
164 for f in &report.findings {
165 let tag = match f.kind {
166 FindingKind::SafeStorageKey => "SAFE-STORAGE",
167 FindingKind::GenericSecret => "generic",
168 };
169 let _ = writeln!(
170 out,
171 "[{tag}] service={} account={} secret={}",
172 f.service, f.account, f.secret
173 );
174 }
175 out
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn classify_detects_safe_storage_variants() {
184 assert_eq!(classify("Chrome Safe Storage"), FindingKind::SafeStorageKey);
185 assert_eq!(
186 classify("Microsoft Edge Safe Storage"),
187 FindingKind::SafeStorageKey
188 );
189 assert_eq!(classify("Brave Safe Storage"), FindingKind::SafeStorageKey);
190 assert_eq!(classify("MySecretService"), FindingKind::GenericSecret);
191 }
192
193 #[test]
194 fn cli_parses_positional_and_flags() {
195 let cli = Cli::try_parse_from(["kc4n6", "/tmp/login.keychain-db", "--password", "pw"])
196 .expect("parse");
197 assert_eq!(cli.keychain, PathBuf::from("/tmp/login.keychain-db"));
198 assert_eq!(cli.password, "pw");
199 assert!(!cli.json);
200 }
201
202 #[test]
203 fn cli_version_flag_supported() {
204 let err = Cli::try_parse_from(["kc4n6", "--version"]).unwrap_err();
205 assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
206 }
207
208 #[test]
209 fn empty_report_renders_key_count() {
210 let r = AuditReport {
211 findings: vec![],
212 key_count: 3,
213 };
214 assert!(render_text(&r).contains("3 record keys"));
215 }
216}