Skip to main content

openmoat_core/token/
credentials.rs

1//! Credentials with no vendor prefix that a precise shape still finds in what
2//! leaves the machine (POLICY.md §3, `token-egress` and `credential-egress`).
3//!
4//! [`super::SHAPES`] are prefixed formats, kept in step with the audit log's
5//! patterns and the push check. These are found only in context, so they stay
6//! out of that list:
7//!
8//! - an AWS secret access key: 40 characters of its alphabet as the value of a
9//!   name ending in `secret_access_key` (`aws_secret_access_key=…`,
10//!   `"SecretAccessKey": "…"`). Its service is AWS's hosts.
11//! - a private key in PEM form: a PEM `BEGIN … PRIVATE KEY` header line (also
12//!   `PGP PRIVATE KEY BLOCK`). No host owns it.
13//! - a JSON web token: three base64url parts, the first two `eyJ` (a JSON
14//!   object). No host owns it.
15//! - a database URL with a password (`postgres://user:pass@db/…`, `mysql`,
16//!   `mongodb+srv`, `redis`, …). Its own host owns it.
17//!
18//! The first two are tokens `token-egress` denies; a JWT and a database URL
19//! are often sent to the service they belong to, which their shape does not
20//! name, so they are `@credential-egress` atoms `credential-egress` holds for
21//! review. No value is ever put in an atom.
22
23/// One credential found in a text.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Credential {
26    /// Short id used in atoms and reasons (`jwt`).
27    pub id: &'static str,
28    /// Whether it is a token `token-egress` denies; otherwise it is held for
29    /// review (`credential-egress`).
30    pub denied: bool,
31    owner: Owner,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35enum Owner {
36    /// Host names (and their subdomains) of the service it is for.
37    Hosts(&'static [&'static str]),
38    /// The host the credential itself names (a database URL's).
39    Named(String),
40    /// No host: it should leave the machine for none.
41    Nobody,
42}
43
44impl Credential {
45    /// Whether `host` is where this credential belongs.
46    #[must_use]
47    pub fn owns(&self, host: &str) -> bool {
48        let host = host.trim_end_matches('.').to_ascii_lowercase();
49        match &self.owner {
50            Owner::Hosts(hosts) => hosts.iter().any(|own| {
51                host == *own
52                    || host
53                        .strip_suffix(own)
54                        .is_some_and(|rest| rest.ends_with('.'))
55            }),
56            Owner::Named(own) => host == *own,
57            Owner::Nobody => false,
58        }
59    }
60}
61
62const AWS_HOSTS: &[&str] = &["amazonaws.com", "amazonaws.com.cn", "aws.amazon.com"];
63
64/// Names whose value is an AWS secret access key, compared lowercase.
65const AWS_SECRET_NAMES: &[&str] = &["secret_access_key", "secret-access-key", "secretaccesskey"];
66
67/// Length of an AWS secret access key.
68const AWS_SECRET_LEN: usize = 40;
69
70/// Schemes of database URLs that carry a login.
71const DATABASE_SCHEMES: &[&str] = &[
72    "postgres",
73    "postgresql",
74    "mysql",
75    "mariadb",
76    "mongodb",
77    "mongodb+srv",
78    "redis",
79    "rediss",
80    "amqp",
81    "amqps",
82    "mssql",
83    "sqlserver",
84    "cockroachdb",
85];
86
87/// Shortest part of a JSON web token this module counts.
88const JWT_PART_MIN: usize = 10;
89
90/// Every credential found in `text`, each kind once (a database URL once per host).
91#[must_use]
92pub fn in_text(text: &str) -> Vec<Credential> {
93    let mut found = Vec::new();
94    if aws_secret(text) {
95        found.push(Credential {
96            id: "aws-secret",
97            denied: true,
98            owner: Owner::Hosts(AWS_HOSTS),
99        });
100    }
101    if private_key(text) {
102        found.push(Credential {
103            id: "private-key",
104            denied: true,
105            owner: Owner::Nobody,
106        });
107    }
108    if jwt(text) {
109        found.push(Credential {
110            id: "jwt",
111            denied: false,
112            owner: Owner::Nobody,
113        });
114    }
115    for host in database_hosts(text) {
116        let credential = Credential {
117            id: "database-url",
118            denied: false,
119            owner: Owner::Named(host),
120        };
121        if !found.contains(&credential) {
122            found.push(credential);
123        }
124    }
125    found
126}
127
128fn aws_alphabet(b: u8) -> bool {
129    b.is_ascii_alphanumeric() || b == b'/' || b == b'+'
130}
131
132/// `…secret_access_key` then optional quotes and spaces, `=` or `:`, an
133/// optional quote and exactly 40 characters of the key's alphabet.
134fn aws_secret(text: &str) -> bool {
135    let lower = text.to_ascii_lowercase();
136    let bytes = lower.as_bytes();
137    let raw = text.as_bytes();
138    AWS_SECRET_NAMES.iter().any(|name| {
139        lower.match_indices(name).any(|(at, _)| {
140            let mut i = at + name.len();
141            let skip = |i: &mut usize, set: &[u8]| {
142                while bytes.get(*i).is_some_and(|b| set.contains(b)) {
143                    *i += 1;
144                }
145            };
146            skip(&mut i, b"\"' \t");
147            if !matches!(bytes.get(i), Some(b'=' | b':')) {
148                return false;
149            }
150            i += 1;
151            skip(&mut i, b" \t\"'");
152            let run = raw[i..].iter().take_while(|b| aws_alphabet(**b)).count();
153            run == AWS_SECRET_LEN && raw.get(i + run) != Some(&b'=')
154        })
155    })
156}
157
158/// A PEM `BEGIN <label> PRIVATE KEY` or `… PRIVATE KEY BLOCK` header line.
159fn private_key(text: &str) -> bool {
160    const BEGIN: &str = "-----BEGIN ";
161    text.match_indices(BEGIN).any(|(at, _)| {
162        let rest = &text[at + BEGIN.len()..];
163        let label: String = rest
164            .chars()
165            .take_while(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || *c == ' ')
166            .collect();
167        let after = &rest[label.len()..];
168        after.starts_with("-----")
169            && (label.ends_with("PRIVATE KEY") || label.ends_with("PRIVATE KEY BLOCK"))
170    })
171}
172
173fn base64url(b: u8) -> bool {
174    b.is_ascii_alphanumeric() || b == b'_' || b == b'-'
175}
176
177/// Three base64url parts of [`JWT_PART_MIN`] or more joined by `.`, the
178/// header and the payload each a JSON object (`eyJ`), at word boundaries.
179fn jwt(text: &str) -> bool {
180    let bytes = text.as_bytes();
181    text.match_indices("eyJ").any(|(at, _)| {
182        if at > 0 && base64url(bytes[at - 1]) {
183            return false;
184        }
185        let part = |from: usize| bytes[from..].iter().take_while(|b| base64url(**b)).count();
186        let header = part(at);
187        let payload_at = at + header + 1;
188        if header < JWT_PART_MIN
189            || bytes.get(at + header) != Some(&b'.')
190            || !text[payload_at..].starts_with("eyJ")
191        {
192            return false;
193        }
194        let payload = part(payload_at);
195        let signature_at = payload_at + payload + 1;
196        payload >= JWT_PART_MIN
197            && bytes.get(payload_at + payload) == Some(&b'.')
198            && part(signature_at) >= JWT_PART_MIN
199    })
200}
201
202/// The hosts of the database URLs in `text` that carry a literal password:
203/// `<scheme>://<user>:<password>@<host>`, the password not a variable.
204fn database_hosts(text: &str) -> Vec<String> {
205    let mut hosts = Vec::new();
206    for (at, _) in text.match_indices("://") {
207        let scheme_start = text[..at]
208            .rfind(|c: char| !(c.is_ascii_alphanumeric() || "+.-".contains(c)))
209            .map_or(0, |i| i + 1);
210        let scheme = text[scheme_start..at].to_ascii_lowercase();
211        if !DATABASE_SCHEMES.contains(&scheme.as_str()) {
212            continue;
213        }
214        let rest = &text[at + 3..];
215        let end = rest
216            .find(|c: char| "/?#\"'` \t\n".contains(c))
217            .unwrap_or(rest.len());
218        let authority = &rest[..end];
219        let Some((login, host)) = authority.rsplit_once('@') else {
220            continue;
221        };
222        let Some((_, password)) = login.split_once(':') else {
223            continue;
224        };
225        if password.is_empty() || password.starts_with(['$', '*', '<', '{']) {
226            continue;
227        }
228        // the first host of a list (`h1:27017,h2:27017`), without its port
229        let host = host.split(',').next().unwrap_or(host);
230        let host = host
231            .rsplit_once(':')
232            .filter(|(_, port)| port.bytes().all(|b| b.is_ascii_digit()))
233            .map_or(host, |(name, _)| name);
234        let host = host.trim_matches(['[', ']']).to_ascii_lowercase();
235        if !host.is_empty() && !hosts.contains(&host) {
236            hosts.push(host);
237        }
238    }
239    hosts
240}
241
242#[cfg(test)]
243mod tests;