Skip to main content

discord_desktop_forensic/
lib.rs

1//! Discord desktop **forensic analyzer** — audits the artifacts recovered by
2//! [`discord_desktop_core`] and emits normalized [`forensicnomicon_core::report`]
3//! findings.
4//!
5//! Its headline job is the **auth token**: Discord stores the account's bearer
6//! token as a plain `localStorage["token"]` value, a credential that grants full
7//! account access and is the prime target of Electron info-stealers. The analyzer
8//! **flags its presence and location** — origin, LevelDB sequence, and the
9//! redacted length — and never the secret itself. A recoverable *deleted* token
10//! record is surfaced separately as residual credential material.
11//!
12//! | Code | Category | Severity | Meaning |
13//! |---|---|---|---|
14//! | `DISCORD-AUTH-TOKEN-PRESENT` | Threat | High | a live Discord auth token is stored in Local Storage |
15//! | `DISCORD-DELETED-TOKEN-RECOVERABLE` | Residue | Medium | a deleted Discord token record is still recoverable |
16//!
17//! Findings are observations, never legal conclusions ("consistent with", never a
18//! verdict). MITRE ATT&CK T1528 (Steal Application Access Token) is referenced.
19#![forbid(unsafe_code)]
20#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
21
22use discord_desktop_core::token::TokenRecord;
23use discord_desktop_core::DiscordArtifacts;
24use forensicnomicon_core::report::{
25    Category, Evidence, Finding, Location, Observation, Severity, Source, SubjectRef,
26};
27
28/// The analyzer name stamped on every finding's [`Source`].
29pub const ANALYZER: &str = "discord-desktop-forensic";
30
31/// A Discord credential-exposure observation. Carries the redacted metadata that
32/// backs the finding — never the token secret itself.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum DiscordCredentialFinding {
35    /// A live Discord auth token is present in Local Storage — a bearer credential
36    /// granting full account access, and a prime info-stealer target.
37    AuthTokenPresent {
38        /// The Local Storage origin the token was stored under.
39        origin: String,
40        /// The token's length in bytes (its presence signal, never the secret).
41        token_len: usize,
42        /// LevelDB sequence number.
43        seq: u64,
44    },
45    /// A deleted Discord token record is still recoverable — residual credential
46    /// material that outlived its deletion.
47    DeletedTokenRecoverable {
48        /// The Local Storage origin the token was stored under.
49        origin: String,
50        /// The token's length in bytes.
51        token_len: usize,
52        /// LevelDB sequence number.
53        seq: u64,
54    },
55}
56
57impl DiscordCredentialFinding {
58    fn origin(&self) -> &str {
59        match self {
60            Self::AuthTokenPresent { origin, .. }
61            | Self::DeletedTokenRecoverable { origin, .. } => origin,
62        }
63    }
64
65    fn token_len(&self) -> usize {
66        match self {
67            Self::AuthTokenPresent { token_len, .. }
68            | Self::DeletedTokenRecoverable { token_len, .. } => *token_len,
69        }
70    }
71
72    fn seq(&self) -> u64 {
73        match self {
74            Self::AuthTokenPresent { seq, .. } | Self::DeletedTokenRecoverable { seq, .. } => *seq,
75        }
76    }
77}
78
79impl Observation for DiscordCredentialFinding {
80    fn severity(&self) -> Option<Severity> {
81        Some(match self {
82            Self::AuthTokenPresent { .. } => Severity::High,
83            Self::DeletedTokenRecoverable { .. } => Severity::Medium,
84        })
85    }
86
87    fn code(&self) -> &'static str {
88        match self {
89            Self::AuthTokenPresent { .. } => "DISCORD-AUTH-TOKEN-PRESENT",
90            Self::DeletedTokenRecoverable { .. } => "DISCORD-DELETED-TOKEN-RECOVERABLE",
91        }
92    }
93
94    // `TOKEN` is not one of Category::from_code's keywords, so classify explicitly.
95    fn category(&self) -> Category {
96        match self {
97            Self::AuthTokenPresent { .. } => Category::Threat,
98            Self::DeletedTokenRecoverable { .. } => Category::Residue,
99        }
100    }
101
102    fn note(&self) -> String {
103        match self {
104            Self::AuthTokenPresent {
105                origin, token_len, ..
106            } => format!(
107                "A Discord authentication token ({token_len} chars, redacted) is stored in \
108                 Local Storage at {origin} — a bearer credential that grants full account \
109                 access and is a known info-stealer target. Consistent with a signed-in \
110                 account recoverable from this artifact."
111            ),
112            Self::DeletedTokenRecoverable {
113                origin, token_len, ..
114            } => format!(
115                "A deleted Discord authentication token record ({token_len} chars, redacted) \
116                 remains recoverable in Local Storage at {origin} — residual credential \
117                 material that outlived its deletion."
118            ),
119        }
120    }
121
122    fn subjects(&self) -> Vec<SubjectRef> {
123        vec![SubjectRef {
124            scheme: "messenger".to_string(),
125            kind: "discord_auth_token".to_string(),
126            id: self.origin().to_string(),
127            label: Some("Discord".to_string()),
128        }]
129    }
130
131    fn evidence(&self) -> Vec<Evidence> {
132        vec![
133            Evidence {
134                field: "origin".to_string(),
135                value: self.origin().to_string(),
136                location: Some(Location::Path(self.origin().to_string())),
137            },
138            Evidence {
139                field: "token_length_chars".to_string(),
140                value: self.token_len().to_string(),
141                location: None,
142            },
143            Evidence {
144                field: "leveldb_seq".to_string(),
145                value: self.seq().to_string(),
146                location: Some(Location::RecordId(self.seq())),
147            },
148            Evidence {
149                field: "store".to_string(),
150                value: "Local Storage/leveldb".to_string(),
151                location: None,
152            },
153        ]
154    }
155
156    fn mitre(&self) -> &'static [&'static str] {
157        // T1528 — Steal Application Access Token.
158        &["T1528"]
159    }
160}
161
162/// Classify one token record into a credential-exposure observation.
163fn observe_token(record: &TokenRecord) -> DiscordCredentialFinding {
164    let origin = record.origin.clone();
165    let token_len = record.token.len();
166    let seq = record.seq;
167    if record.deleted {
168        DiscordCredentialFinding::DeletedTokenRecoverable {
169            origin,
170            token_len,
171            seq,
172        }
173    } else {
174        DiscordCredentialFinding::AuthTokenPresent {
175            origin,
176            token_len,
177            seq,
178        }
179    }
180}
181
182/// Audit recovered Discord artifacts and return normalized findings.
183///
184/// Flags each live auth token as a sensitive credential (presence + location,
185/// never the secret) and each recoverable deleted token record as residual
186/// credential material. Artifacts with no token yield no findings.
187#[must_use]
188pub fn audit_artifacts(artifacts: &DiscordArtifacts) -> Vec<Finding> {
189    artifacts
190        .tokens
191        .iter()
192        .map(|record| {
193            let observation = observe_token(record);
194            let source = Source {
195                analyzer: ANALYZER.to_string(),
196                scope: record.origin.clone(),
197                version: Some(env!("CARGO_PKG_VERSION").to_string()),
198            };
199            observation.to_finding(source)
200        })
201        .collect()
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207    use discord_desktop_core::token::{SensitiveToken, TokenRecord};
208    use forensicnomicon_core::report::{Category, Severity};
209
210    const FAKE_TOKEN: &str = "EXAMPLE-synthetic-fixture.not-real.discord-token-value-for-tests";
211
212    fn artifacts_with_token(deleted: bool) -> DiscordArtifacts {
213        DiscordArtifacts {
214            tokens: vec![TokenRecord {
215                origin: "https://ptb.discord.com".to_string(),
216                token: SensitiveToken::new(FAKE_TOKEN),
217                seq: 42,
218                deleted,
219            }],
220            ..DiscordArtifacts::default()
221        }
222    }
223
224    #[test]
225    fn flags_live_token_high_threat_without_leaking_secret() {
226        let findings = audit_artifacts(&artifacts_with_token(false));
227        assert_eq!(findings.len(), 1);
228        let f = &findings[0];
229        assert_eq!(f.code, "DISCORD-AUTH-TOKEN-PRESENT");
230        assert_eq!(f.severity, Some(Severity::High));
231        assert_eq!(f.category, Category::Threat);
232        assert_eq!(f.source.analyzer, ANALYZER);
233
234        // Location is surfaced.
235        assert!(f
236            .evidence
237            .iter()
238            .any(|e| e.value.contains("ptb.discord.com")));
239        assert!(f.context.external_refs.iter().any(|r| r.id == "T1528"));
240
241        // Secure-by-default: the secret must appear NOWHERE in the finding.
242        let blob = format!("{f:?}");
243        assert!(
244            !blob.contains(FAKE_TOKEN),
245            "finding must not contain the raw token"
246        );
247        // …but the redacted length is surfaced so the analyst knows it is present.
248        assert!(blob.contains(&FAKE_TOKEN.len().to_string()));
249    }
250
251    #[test]
252    fn flags_deleted_token_as_residue() {
253        let findings = audit_artifacts(&artifacts_with_token(true));
254        assert_eq!(findings.len(), 1);
255        assert_eq!(findings[0].code, "DISCORD-DELETED-TOKEN-RECOVERABLE");
256        assert_eq!(findings[0].severity, Some(Severity::Medium));
257        assert_eq!(findings[0].category, Category::Residue);
258    }
259
260    #[test]
261    fn no_token_no_findings() {
262        assert!(audit_artifacts(&DiscordArtifacts::default()).is_empty());
263    }
264}