Skip to content

Find the holes before someone else does. A fast, 100% Rust vulnerability scanner: XSS, SQL injection, leaked secrets, dependency CVEs and AI agent setups.

feat(secrets): detect AWS secret access keys (#117)

Onur Ugurdea71cace996
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 07a037e..a452427 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,9 @@
- Secrets: new rule `secret.npm-token` (critical) for npm access tokens (`npm_` followed by 36 letters or digits).
- Secrets: new rule `secret.mailgun-key` (critical) for Mailgun private API keys (`key-` followed by 32 lowercase hex characters).
- Secrets: new rule `secret.telegram-bot-token` (high) for Telegram bot tokens (8 to 10 digits, a colon, then 35 letters, digits, `_` or `-`).
+- Secrets: new rule `secret.aws-secret-key` (critical) for AWS secret access keys: a 40-character value assigned to a name with `aws` and `secret` in it
+ (`aws_secret_access_key = ...`, `AWS_SECRET_ACCESS_KEY=...`, `"awsSecretAccessKey": "..."`). Values that can't be a random key are
+ skipped: the AWS docs example key, hashes, paths, words like `TestSecretKey...`, `000...` and other repeats.
- Secrets: new rule `secret.twilio-api-key` (critical) for Twilio API keys (`SK` followed by 32 lowercase hex characters).
- Secrets: new rule `secret.digitalocean-token` (critical) for DigitalOcean tokens (`dop_v1_`, `doo_v1_` or `dor_v1_` followed by 64 lowercase hex characters).
- Secrets: new rule `secret.shopify-token` (critical) for Shopify access tokens (`shpat_`, `shpca_`, `shppa_` or `shpss_` followed by 32 hex characters).
diff --git a/README.md b/README.md
index f2861f6..2893823 100644
--- a/README.md
+++ b/README.md
@@ -20,7 +20,7 @@ Every finding comes with the line, the reason and the fix.</p>
<a href="https://github.com/erkamyaman/safe-anything"><img src="https://img.shields.io/github/stars/erkamyaman/safe-anything?style=social" alt="GitHub stars"></a>
</p>
-<p align="center"><b><a href="#quick-start">Install</a></b> · <a href="https://github.com/erkamyaman/safe-anything/releases">Releases</a> · <a href="#for-ai-agents">Claude Code plugin</a> · <a href="#in-ci">GitHub Action</a> · <a href="docs/rules.md">All 90 rules</a> · <a href="docs/agent-setups.md">Agent setups</a><br>
+<p align="center"><b><a href="#quick-start">Install</a></b> · <a href="https://github.com/erkamyaman/safe-anything/releases">Releases</a> · <a href="#for-ai-agents">Claude Code plugin</a> · <a href="#in-ci">GitHub Action</a> · <a href="docs/rules.md">All 91 rules</a> · <a href="docs/agent-setups.md">Agent setups</a><br>
Made in Türkiye 🇹🇷 by <a href="https://github.com/erkamyaman">erKam Yaman</a>, who also made <a href="https://github.com/erkamyaman/rust-anything">rust-anything</a> · <a href="https://github.com/sponsors/erkamyaman">❤️ Sponsor me</a> · Sponsored by <a href="https://coderabbit.link/er-kam">CodeRabbit</a></p>
<p align="center">
@@ -104,7 +104,7 @@ it hides that finding.
## What it finds
-90 rules, each with a CWE id, an OWASP category and a link to the OWASP page that explains it.
+91 rules, each with a CWE id, an OWASP category and a link to the OWASP page that explains it.
The full list is in [docs/rules.md](docs/rules.md).
| | |
@@ -194,7 +194,7 @@ lockfile listed under Dependencies. Nothing is executed. The only network call i
names and versions to OSV.dev ([privacy](docs/privacy.md)).
It finds known patterns; it does not trace data through your program. A clean scan means none of
-these 90 problems were found, not that the code is safe. [Design notes](docs/adr).
+these 91 problems were found, not that the code is safe. [Design notes](docs/adr).
## Credits
diff --git a/docs/rules.md b/docs/rules.md
index 5cf29a7..209edf8 100644
--- a/docs/rules.md
+++ b/docs/rules.md
@@ -32,11 +32,12 @@ Every rule safe-anything checks, generated from `safe-anything --list-rules --js
| [`code.sql-grant-all`](https://cheatsheetseries.owasp.org/cheatsheets/Database_Security_Cheat_Sheet.html) | medium | [CWE-250](https://cwe.mitre.org/data/definitions/250.html) | A01:2021 Broken Access Control | A database user gets every privilege on every database. |
| [`code.sql-plaintext-password`](https://cheatsheetseries.owasp.org/cheatsheets/Database_Security_Cheat_Sheet.html) | medium | [CWE-798](https://cwe.mitre.org/data/definitions/798.html) | A07:2021 Identification and Authentication Failures | A database password is written in a SQL file. |
-## Secrets (27)
+## Secrets (28)
| Rule | Severity | CWE | OWASP | What it means |
| --- | --- | --- | --- | --- |
| [`secret.aws-access-key`](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) | critical | [CWE-798](https://cwe.mitre.org/data/definitions/798.html) | A07:2021 Identification and Authentication Failures | An AWS access key id is written in the file. |
+| [`secret.aws-secret-key`](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) | critical | [CWE-798](https://cwe.mitre.org/data/definitions/798.html) | A07:2021 Identification and Authentication Failures | An AWS secret access key is written in the file. |
| [`secret.github-token`](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) | critical | [CWE-798](https://cwe.mitre.org/data/definitions/798.html) | A07:2021 Identification and Authentication Failures | A GitHub token is written in the file. |
| [`secret.gitlab-token`](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) | critical | [CWE-798](https://cwe.mitre.org/data/definitions/798.html) | A07:2021 Identification and Authentication Failures | A GitLab personal access token is written in the file. |
| [`secret.slack-token`](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html) | high | [CWE-798](https://cwe.mitre.org/data/definitions/798.html) | A07:2021 Identification and Authentication Failures | A Slack token is written in the file. |
diff --git a/src/rules.rs b/src/rules.rs
index 58dcb68..32a5ac6 100644
--- a/src/rules.rs
+++ b/src/rules.rs
@@ -375,6 +375,9 @@ pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
{
continue;
}
+ if !secrets::plausible(c.rule.id, secret, &src[m.end()..]) {
+ continue;
+ }
if seen.insert((c.rule.id.to_string(), line)) {
out.push(finding(
file,
diff --git a/src/rules/secrets.rs b/src/rules/secrets.rs
index 2b60cee..e1ad525 100644
--- a/src/rules/secrets.rs
+++ b/src/rules/secrets.rs
@@ -1,4 +1,7 @@
use std::path::Path;
+use std::sync::LazyLock;
+
+use regex::Regex;
use ignore::gitignore::GitignoreBuilder;
@@ -96,6 +99,68 @@ const ENV_SECRET_LINE: &str = r#"(?m)^\s*(?:export\s+)?[A-Za-z0-9_]*(?i:secret|t
const ENV_PLACEHOLDER: &str = r"^\s*(?:export\s+)?(?:NEXT_PUBLIC|VITE|REACT_APP|EXPO_PUBLIC|NUXT_PUBLIC|GATSBY|VUE_APP|PUBLIC)_|(?i)=\s*[\x22']?(?:\S*(?:your|example|change|replace|placeholder|dummy|xxxx|\.\.\.|<)|sk_test_|pk_test_|(?-i:[a-z]+[-_][a-z]+[-_][a-z]+))|=\s*[\x22']?\*+[\x22']?\s*$|=\s*[\x22']?\$";
+// A name with `aws` and `secret` in it, then `=` or `:` and a 40-character value. `aws` and
+// `secret` each start a word: at the start of the line, after a character that is not a letter
+// or digit (`_`, `-`, `.`, a quote), right after the other word (`awssecret`), or as a camelCase
+// word (`myAwsSecret`, `IAMAwsSecret`, `myAWSSecret`). So `flaws_secret` and `aws_unsecret` are
+// not read as one. Between the name and the value: a closing quote and `]`
+// (`environ["AWS_SECRET_ACCESS_KEY"] =`), a type (`: string =`, `: &str =`), and an opening
+// quote or backtick. The value itself, and what follows it, is checked by `plausible`.
+const AWS_SECRET_KEY: &str = concat!(
+ r#"(?m)(?:(?:(?:^|[^A-Za-z0-9\r\n])(?i:aws)|[a-z0-9]AWS|[A-Za-z0-9]Aws)"#,
+ r#"(?:(?i:secret)|[A-Za-z0-9_.\-]{0,64}(?:[_.\-](?i:secret)|[a-z0-9]SECRET|[A-Za-z0-9]Secret))"#,
+ r#"|(?:(?:^|[^A-Za-z0-9\r\n])(?i:secret)|[a-z0-9]SECRET|[A-Za-z0-9]Secret)"#,
+ r#"(?:(?i:aws)|[A-Za-z0-9_.\-]{0,64}(?:[_.\-](?i:aws)|[a-z0-9]AWS|[A-Za-z0-9]Aws)))"#,
+ r#"[A-Za-z0-9_.\-]{0,64}["']?\]?[ \t]{0,8}"#,
+ r#"(?::[ \t]{0,8}&?(?:'[A-Za-z_]{1,16}[ \t]{1,8})?[A-Za-z_][A-Za-z0-9_:<>]{0,64}[ \t]{0,8}=|:=|=>|[:=])"#,
+ r#"[ \t]{0,8}["'`]?([A-Za-z0-9/+]{40})"#,
+);
+
+/// Whether a matched value can be a secret for the rule. Only `secret.aws-secret-key` is checked:
+/// its value has no prefix, so placeholders and other 40-character strings have to be told apart
+/// by the value alone, and its pattern stops after the 40 characters, so `after` (the text that
+/// follows the match) must not go on with another base64 character.
+pub fn plausible(id: &str, value: Option<&str>, after: &str) -> bool {
+ id != "secret.aws-secret-key"
+ || (value.is_some_and(plausible_aws_secret)
+ && !after.starts_with(|c: char| c.is_ascii_alphanumeric() || "/+=".contains(c)))
+}
+
+/// Words that read as a name or a path: a first word in small letters, then words that start
+/// with a capital or after `/` or `+`, each with digits only at its end
+/// (`TestSecretKeyTestSecretKey1`, `myAwsSecretKey123`, `/Prod/East1/Payments/Keys`). In 40
+/// random base64 characters every capital would have to be followed by a small letter and every
+/// digit by a capital, `/`, `+` or the end, which practically never happens.
+static WORDS: LazyLock<Regex> = LazyLock::new(|| {
+ Regex::new(r"^[/+]?[a-z]*[0-9]*(?:(?:[/+]?[A-Z]|[/+])[a-z]+[0-9]*)*[/+]?$").unwrap()
+});
+
+/// An AWS secret access key is 40 random base64 characters. So it has upper and lower case
+/// letters, about 30 different characters, no repeating chunk, no run of the alphabet, and it
+/// does not read as words or a path. That leaves out hex hashes, paths, `000...`, `xxx...`,
+/// `abcd...`, `TestSecretKey...` and the AWS docs key (`...EXAMPLEKEY`).
+fn plausible_aws_secret(value: &str) -> bool {
+ let v = value.as_bytes();
+ let distinct = v.iter().collect::<std::collections::HashSet<_>>().len();
+ // A chunk of up to 20 characters repeated over the value, give or take two characters.
+ let repeats = (1..=20.min(v.len() / 2)).any(|k| {
+ let same = (0..v.len() - k).filter(|&i| v[i] == v[i + k]).count();
+ same + k + 2 >= v.len()
+ });
+ let ascending = v
+ .windows(2)
+ .filter(|w| w[1] == w[0].wrapping_add(1))
+ .count();
+ v.iter().any(u8::is_ascii_uppercase)
+ && v.iter().any(u8::is_ascii_lowercase)
+ && !v.iter().all(u8::is_ascii_hexdigit)
+ && !value.to_ascii_lowercase().contains("example")
+ && distinct >= 12
+ && !repeats
+ && ascending < 10
+ && !WORDS.is_match(value)
+}
+
const ROTATE: &str = "Revoke this credential at the provider, then load it from the environment or a secrets manager and keep it out of the repository.";
macro_rules! secret {
@@ -120,6 +185,16 @@ pub static RULES: &[Rule] = &[
r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b",
"An AWS access key id is written in the file."
),
+ Rule {
+ id: "secret.aws-secret-key",
+ family: Family::Secret,
+ severity: Severity::Critical,
+ files: any_text,
+ pattern: AWS_SECRET_KEY,
+ unless: None,
+ message: "An AWS secret access key is written in the file.",
+ fix: ROTATE,
+ },
secret!(
"secret.github-token",
Critical,
@@ -302,3 +377,50 @@ pub static RULES: &[Rule] = &[
fix: "Drop the public prefix and use the value only in server code (an API route or server action); the browser should call your server instead.",
},
];
+
+#[cfg(test)]
+mod tests {
+ use super::plausible_aws_secret;
+
+ #[test]
+ fn aws_secret_value_check() {
+ // Built from parts, like the fixtures, so the source holds no key-shaped literal.
+ let random = ["Q7mZ2xK9pL4vR8tN3wB6", "yH1cF5jD0s/QmZxK+a3f"].concat();
+ assert!(plausible_aws_secret(&random));
+ let docs_key = ["wJalrXUtnFEMI/K7MDENG/bPxRfiCY", "EXAMPLEKEY"].concat();
+ let chunk = "Q7mZ2xK9pL4vR8tN".repeat(3)[..40].to_string();
+ let lower = "q7mz2xk9pl4vr8tn3wb6yh1cf5jd0sg".repeat(2)[..40].to_string();
+ let upper = lower.to_ascii_uppercase();
+ // Each shape is turned down by one check only.
+ let rejected = [
+ ("no capital", lower),
+ ("no small letter", upper),
+ (
+ "all hex",
+ ["Da39A3eE5e6b4B0d", "3255bFeF95601890", "aFd80709"].concat(),
+ ),
+ ("example", docs_key),
+ (
+ "few distinct characters",
+ ["9ZpBQm7m9aQ7xQmp", "pmxm7pQamxBBaQaa", "pQxQ7ZKp"].concat(),
+ ),
+ ("a repeated chunk", chunk),
+ (
+ "a run of the alphabet",
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN".to_string(),
+ ),
+ (
+ "a path",
+ "/Prod/East1/Payments/Stripe/Billing/Keys".to_string(),
+ ),
+ (
+ "words",
+ "AwsSecretAccessKeyParameterNameForProd12".to_string(),
+ ),
+ ];
+ for (shape, value) in rejected {
+ assert_eq!(value.len(), 40, "{shape}");
+ assert!(!plausible_aws_secret(&value), "{shape}: {value}");
+ }
+ }
+}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index ba2fa91..deb658d 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -15,6 +15,15 @@ const KEY_BODY: &str = "Zr8Wq2Xn5Mb7Vc4Lk1Jh6Gf9Dd3Ss0AaUe";
pub fn fake(name: &str) -> String {
match name {
"aws" => ["AK", "IA", &body(16, UPPER)].concat(),
+ "aws-secret" => [
+ &body(18, MIXED),
+ "/",
+ &body(10, LETTERS),
+ "+",
+ &body(10, HEX),
+ ]
+ .concat(),
+ "aws-secret-example" => [&body(30, MIXED), "EXAMPLE", "KEY"].concat(),
"github" => ["gh", "p_", &body(36, MIXED)].concat(),
"gitlab" => ["gl", "pat-", &body(20, MIXED)].concat(),
"github-pat" => ["github", "_pat_", &body(82, MIXED)].concat(),
diff --git a/tests/fixtures/secrets/EXPECTED b/tests/fixtures/secrets/EXPECTED
index 44e2306..65b4ec6 100644
--- a/tests/fixtures/secrets/EXPECTED
+++ b/tests/fixtures/secrets/EXPECTED
@@ -31,4 +31,17 @@ config.py:34 secret.sendgrid-key
config.py:36 secret.pypi-token
config.py:38 secret.shopify-token
config.py:39 secret.digitalocean-token
-config.py:41 secret.twilio-api-key
\ No newline at end of file
+config.py:41 secret.twilio-api-key
+aws/assignments.txt:1 secret.aws-secret-key
+aws/assignments.txt:2 secret.aws-secret-key
+aws/assignments.txt:3 secret.aws-secret-key
+aws/assignments.txt:4 secret.aws-secret-key
+aws/assignments.txt:5 secret.aws-secret-key
+aws/assignments.txt:6 secret.aws-secret-key
+aws/assignments.txt:7 secret.aws-secret-key
+aws/credentials:2 secret.aws-access-key
+aws/credentials:3 secret.aws-secret-key
+config.py:43 secret.aws-secret-key
+config.py:47 secret.aws-secret-key
+config.py:48 secret.aws-secret-key
+config.py:55 secret.aws-secret-key
\ No newline at end of file
diff --git a/tests/fixtures/secrets/aws/assignments.txt b/tests/fixtures/secrets/aws/assignments.txt
new file mode 100644
index 0000000..306521a
--- /dev/null
+++ b/tests/fixtures/secrets/aws/assignments.txt
@@ -0,0 +1,10 @@
+os.environ["AWS_SECRET_ACCESS_KEY"] = "{{fake:aws-secret}}"
+process.env["AWS_SECRET_ACCESS_KEY"] = "{{fake:aws-secret}}"
+const awsSecretAccessKey = `{{fake:aws-secret}}`;
+const awsSecretAccessKey: string = "{{fake:aws-secret}}";
+const AWS_SECRET_ACCESS_KEY: &str = "{{fake:aws-secret}}";
+aws_secret_access_key: str = "{{fake:aws-secret}}"
+IAMAwsSecretKey = "{{fake:aws-secret}}"
+aws_unsecret = "{{fake:aws-secret}}"
+AWS_UNSECRET_NOTE = "{{fake:aws-secret}}"
+if env["AWS_SECRET_ACCESS_KEY"] == "{{fake:aws-secret}}":
diff --git a/tests/fixtures/secrets/aws/credentials b/tests/fixtures/secrets/aws/credentials
new file mode 100644
index 0000000..3df224f
--- /dev/null
+++ b/tests/fixtures/secrets/aws/credentials
@@ -0,0 +1,3 @@
+[default]
+aws_access_key_id = {{fake:aws}}
+aws_secret_access_key = {{fake:aws-secret}}
diff --git a/tests/fixtures/secrets/config.py b/tests/fixtures/secrets/config.py
index 60f76b1..996cfe5 100644
--- a/tests/fixtures/secrets/config.py
+++ b/tests/fixtures/secrets/config.py
@@ -39,4 +39,18 @@ shopify_token = "{{fake:shopify-token}}"
digitalocean = "{{fake:digitalocean-token}}"
digitalocean_short = "dop_v1_0123abcd"
twilio = "{{fake:twilio}}"
-twilio_lookalike = "SKU-12345678 SK0123abcd"
\ No newline at end of file
+twilio_lookalike = "SKU-12345678 SK0123abcd"
+aws_secret_access_key = "{{fake:aws-secret}}"
+aws_secret_access_key = os.environ["AWS_SECRET_ACCESS_KEY"]
+checksum = "{{fake:aws-secret}}"
+aws_secret_access_key = "{{fake:aws-secret-example}}"
+aws = {"endpoint": "https://api.example.com", "awsSecretAccessKey": "{{fake:aws-secret}}"}
+aws_secret_access_key = "{{fake:aws-secret}}" # example prod key
+flaws_secret = "{{fake:aws-secret}}"
+FLAWS_SECRET_SHA = "{{fake:aws-secret}}"
+aws_secret_path = "/prod/east1/payments/stripe/billing/keys"
+aws_secret_access_key = "0000000000000000000000000000000000000000"
+aws_secret_access_key = "TestSecretKeyTestSecretKeyTestSecretKey1"
+aws_secret_path = "/Prod/East1/Payments/Stripe/Billing/Keys"
+aws_secret_a=0000000000000000000000000000000000000000,aws_secret_key={{fake:aws-secret}}
+aws_secret_access_key = "{{fake:aws-secret}}A"
\ No newline at end of file