Skip to main content

keychain_forensic/
lib.rs

1//! `kc4n6` — the forensic analyzer over [`keychain_core`].
2//!
3//! Audits an acquired macOS `login.keychain-db` **offline**: given the account
4//! login password it recovers every generic-password secret and flags the
5//! high-value **Chromium Safe Storage** key (which in turn unlocks Chrome / Edge
6//! cookie and login stores). A wrong or absent password yields a loud
7//! *present-but-locked* report with a non-zero exit, never a guessed secret.
8//!
9//! Decision logic lives in this library (the testable [`audit`] / [`classify`]
10//! functions + [`Cli::run`]); `main.rs` is a thin shell (Humble Object).
11
12pub use keychain_core;
13
14use std::path::PathBuf;
15
16use clap::Parser;
17use keychain_core::{GenericSecret, Keychain, KeychainError};
18use serde::Serialize;
19
20/// The class of a recovered item.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
22#[serde(rename_all = "kebab-case")]
23pub enum FindingKind {
24    /// An ordinary generic-password secret.
25    GenericSecret,
26    /// The Chromium `Safe Storage` key — unlocks Chrome/Edge cookie & login DBs.
27    SafeStorageKey,
28}
29
30/// One recovered secret, classified.
31#[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    /// Display form: UTF-8 text, or `hex:...` for a binary key.
38    pub secret: String,
39}
40
41/// The audit result: recovered findings plus recovery context.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
43pub struct AuditReport {
44    pub findings: Vec<Finding>,
45    /// Number of per-record keys the login password unwrapped.
46    pub key_count: usize,
47}
48
49/// Classify a record by its service attribute.
50///
51/// Chromium stores its master cookie key as a generic password whose service is
52/// `Chrome Safe Storage` (Edge: `Microsoft Edge Safe Storage`, Brave:
53/// `Brave Safe Storage`, …). The general rule is a `Safe Storage` service
54/// suffix — not a hard-coded allowlist of one browser.
55#[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
74/// Audit a keychain image with the login password.
75///
76/// Returns [`KeychainError::Locked`] when the password does not unwrap the
77/// DBKey — the caller reports the store present-but-locked, never a secret.
78pub 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/// A typed CLI failure surfaced to the user (never a guessed secret).
93#[derive(Debug)]
94pub enum CliError {
95    /// Reading the keychain file failed.
96    Io(String),
97    /// The container could not be parsed as a keychain.
98    Parse(KeychainError),
99    /// The store is present but the password did not unlock it.
100    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/// `kc4n6` — recover secrets from an acquired macOS `login.keychain-db`.
119#[derive(Debug, Parser)]
120#[command(
121    name = "kc4n6",
122    version,
123    about = "Offline macOS keychain secret recovery"
124)]
125pub struct Cli {
126    /// Path to the `login.keychain-db` file.
127    pub keychain: PathBuf,
128    /// The account login password that protects the keychain.
129    #[arg(long)]
130    pub password: String,
131    /// Emit the report as JSON instead of a human table.
132    #[arg(long)]
133    pub json: bool,
134}
135
136impl Cli {
137    /// Read the keychain and audit it, returning the report or a typed error.
138    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/// Render an [`AuditReport`] as a human-readable table.
152#[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}