openmoat_core/token/
credentials.rs1#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Credential {
26 pub id: &'static str,
28 pub denied: bool,
31 owner: Owner,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35enum Owner {
36 Hosts(&'static [&'static str]),
38 Named(String),
40 Nobody,
42}
43
44impl Credential {
45 #[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
64const AWS_SECRET_NAMES: &[&str] = &["secret_access_key", "secret-access-key", "secretaccesskey"];
66
67const AWS_SECRET_LEN: usize = 40;
69
70const 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
87const JWT_PART_MIN: usize = 10;
89
90#[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
132fn 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
158fn 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
177fn 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
202fn 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 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;