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(config): flag S3 public access blocks that are turned off (#97)

Onur Ugur8987b3bb7c02
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3bfe074..a59badd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,8 @@
- 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 `-`).
+- Config: new rule `config.tf-public-access-block` (medium) for `block_public_policy = false` or
+ `restrict_public_buckets = false` in an `aws_s3_bucket_public_access_block` or `aws_s3_account_public_access_block`.
- Secrets: new rule `secret.groq-key` (critical) for Groq API keys (`gsk_` followed by 52 letters or digits).
- Code: new rule `code.open-redirect` (medium) for redirects built straight from request input (`res.redirect(req.query.next)`, `redirect(request.args.get("next"))`); a redirect to a fixed path stays unflagged.
- Code: `code.sql-injection` also catches Go queries built by concatenation in `db.Query`, `db.QueryRow`, `db.Exec`
diff --git a/README.md b/README.md
index 6cac718..c3d6dd4 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 80 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 81 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">
@@ -86,7 +86,7 @@ safe-anything --list-rules
## What it finds
-80 rules, each with a CWE id, an OWASP category and a link to the OWASP page that explains it.
+81 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).
| | |
@@ -175,7 +175,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 80 problems were found, not that the code is safe. [Design notes](docs/adr).
+these 81 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 6ad4da7..fb925fa 100644
--- a/docs/rules.md
+++ b/docs/rules.md
@@ -86,7 +86,7 @@ Every rule safe-anything checks, generated from `safe-anything --list-rules --js
| [`mobile.ios-ats-disabled`](https://mas.owasp.org/MASVS/08-MASVS-NETWORK/) | high | [CWE-319](https://cwe.mitre.org/data/definitions/319.html) | MASVS-NETWORK | App Transport Security is off, so the app may load anything over plain HTTP. |
| [`mobile.insecure-storage`](https://mas.owasp.org/MASVS/05-MASVS-STORAGE/) | medium | [CWE-922](https://cwe.mitre.org/data/definitions/922.html) | MASVS-STORAGE | A token or password is saved in plain storage that other code, backups or XSS can read. |
-## Config (15)
+## Config (16)
| Rule | Severity | CWE | OWASP | What it means |
| --- | --- | --- | --- | --- |
@@ -103,6 +103,7 @@ Every rule safe-anything checks, generated from `safe-anything --list-rules --js
| [`config.k8s-host-access`](https://cheatsheetseries.owasp.org/cheatsheets/Kubernetes_Security_Cheat_Sheet.html) | high | [CWE-250](https://cwe.mitre.org/data/definitions/250.html) | A05:2021 Security Misconfiguration | The pod shares the host's network, process or IPC namespace. |
| [`config.tf-open-ingress`](https://cheatsheetseries.owasp.org/cheatsheets/Infrastructure_as_Code_Security_Cheat_Sheet.html) | medium | [CWE-284](https://cwe.mitre.org/data/definitions/284.html) | A01:2021 Broken Access Control | A network rule is open to the whole internet. |
| [`config.tf-public-bucket`](https://cheatsheetseries.owasp.org/cheatsheets/Infrastructure_as_Code_Security_Cheat_Sheet.html) | high | [CWE-284](https://cwe.mitre.org/data/definitions/284.html) | A01:2021 Broken Access Control | A storage bucket is public. |
+| [`config.tf-public-access-block`](https://cheatsheetseries.owasp.org/cheatsheets/Infrastructure_as_Code_Security_Cheat_Sheet.html) | medium | [CWE-284](https://cwe.mitre.org/data/definitions/284.html) | A01:2021 Broken Access Control | An S3 public access block is turned off, so a bucket policy can make the bucket (or every bucket in the account) public. |
| [`config.nginx-autoindex`](https://cheatsheetseries.owasp.org/cheatsheets/Attack_Surface_Analysis_Cheat_Sheet.html) | low | [CWE-548](https://cwe.mitre.org/data/definitions/548.html) | A05:2021 Security Misconfiguration | Directory listing is on, so every file in the folder can be browsed. |
| [`config.weak-tls-version`](https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html) | medium | [CWE-326](https://cwe.mitre.org/data/definitions/326.html) | A02:2021 Cryptographic Failures | Old TLS or SSL versions are enabled; they have known attacks. |
diff --git a/src/refs.rs b/src/refs.rs
index 85e6e80..b89290f 100644
--- a/src/refs.rs
+++ b/src/refs.rs
@@ -233,11 +233,13 @@ pub fn of(id: &str) -> Refs {
"config.gha-script-injection" => {
r!("CWE-78", "A03:2021 Injection", "CI_CD_Security_Cheat_Sheet")
}
- "config.tf-open-ingress" | "config.tf-public-bucket" => r!(
- "CWE-284",
- "A01:2021 Broken Access Control",
- "Infrastructure_as_Code_Security_Cheat_Sheet"
- ),
+ "config.tf-open-ingress" | "config.tf-public-bucket" | "config.tf-public-access-block" => {
+ r!(
+ "CWE-284",
+ "A01:2021 Broken Access Control",
+ "Infrastructure_as_Code_Security_Cheat_Sheet"
+ )
+ }
"config.nginx-autoindex" => r!(
"CWE-548",
"A05:2021 Security Misconfiguration",
diff --git a/src/rules.rs b/src/rules.rs
index e2a958d..5eb8d53 100644
--- a/src/rules.rs
+++ b/src/rules.rs
@@ -119,6 +119,10 @@ impl<'a> Text<'a> {
self.starts.partition_point(|&s| s <= offset)
}
+ pub fn line_start(&self, n: usize) -> usize {
+ self.starts[n - 1]
+ }
+
pub fn line(&self, n: usize) -> &'a str {
let start = self.starts[n - 1];
let end = self.starts.get(n).map(|e| e - 1).unwrap_or(self.src.len());
@@ -230,7 +234,8 @@ pub fn check(file: &FileInfo, src: &str, include_tests: bool) -> Vec<Finding> {
}
}
}
- out.retain(|f| config::keep(file, &text, f));
+ let mut hcl = config::HclWalk::default();
+ out.retain(|f| config::keep(file, &text, f, &mut hcl));
for f in agent::structured(file, &text)
.into_iter()
.filter(|_| !test_file)
diff --git a/src/rules/config.rs b/src/rules/config.rs
index 03b29d4..1217930 100644
--- a/src/rules/config.rs
+++ b/src/rules/config.rs
@@ -164,6 +164,15 @@ pub static RULES: &[Rule] = &[
"A storage bucket is public.",
"Make it private and serve files through a CDN or signed URLs."
),
+ rule!(
+ "config.tf-public-access-block",
+ Medium,
+ terraform,
+ r#"(?m)\b(?:block_public_policy|restrict_public_buckets)\s*=\s*(?:false|"false")\s*(?:$|#|//|/\*|,|\})"#,
+ None,
+ "An S3 public access block is turned off, so a bucket policy can make the bucket (or every bucket in the account) public.",
+ "Set block_public_policy and restrict_public_buckets to true. Ignore for a bucket that serves a public website on purpose."
+ ),
rule!(
"config.nginx-autoindex",
Low,
@@ -190,8 +199,170 @@ static FROM: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(?i)^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)").unwrap());
static YAML_KEY: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*-?\s*([A-Za-z_][\w-]*)\s*:\s*\S").unwrap());
+// The whole `key = false`, not just the key, so `= true # was block_public_policy = false`
+// is judged by the part in the comment, which the walk then rejects.
+// The rule's own pattern (`key = false` that ends the value), found again on the line in `keep`.
+static PUBLIC_ACCESS_OFF: LazyLock<Regex> = LazyLock::new(|| {
+ let rule = RULES
+ .iter()
+ .find(|r| r.id == "config.tf-public-access-block")
+ .expect("the rule is in RULES");
+ Regex::new(rule.pattern).unwrap()
+});
+
+/// The end of the quoted string that opens at `b[start]`: the index of its closing quote, of the
+/// newline that ends it unclosed, or `b.len()`. A `${ ... }` or `%{ ... }` template inside may
+/// hold braces and quoted strings of its own; a stack (not recursion) keeps deep nesting safe.
+fn hcl_string_end(b: &[u8], start: usize) -> usize {
+ // One entry per open string (None) or template (Some(open braces)).
+ let mut open: Vec<Option<usize>> = vec![None];
+ let mut j = start + 1;
+ while j < b.len() {
+ match open.last_mut() {
+ Some(None) => match b[j] {
+ b'"' => {
+ open.pop();
+ if open.is_empty() {
+ return j;
+ }
+ }
+ b'\n' if open.len() == 1 => return j,
+ b'\\' => j += 1,
+ // `$${` and `%%{` are a literal `${` and `%{`, not a template.
+ b'$' | b'%' if b.get(j + 1) == Some(&b[j]) && b.get(j + 2) == Some(&b'{') => j += 2,
+ b'$' | b'%' if b.get(j + 1) == Some(&b'{') => {
+ open.push(Some(1));
+ j += 1;
+ }
+ _ => {}
+ },
+ Some(Some(depth)) => match b[j] {
+ b'"' => open.push(None),
+ b'{' => *depth += 1,
+ b'}' => {
+ *depth -= 1;
+ if *depth == 0 {
+ open.pop();
+ }
+ }
+ _ => {}
+ },
+ None => unreachable!("the outer string is popped only by returning"),
+ }
+ j += 1;
+ }
+ b.len()
+}
-pub fn keep(file: &FileInfo, text: &Text, f: &Finding) -> bool {
+/// A walk through one HCL file that remembers where it stopped. Asking about
+/// offsets in increasing order (the order findings come in) reads the file
+/// once in total, instead of once per finding.
+#[derive(Default)]
+pub struct HclWalk {
+ i: usize,
+ depth: usize,
+ line_start: usize,
+ header: Option<(usize, usize)>,
+ // Where the last step started when it jumped past the offset asked for (over a comment,
+ // string or heredoc). Any later offset before `i` but after this is inside that same span.
+ over_from: Option<usize>,
+}
+
+impl HclWalk {
+ /// The header of the top-level HCL block whose own body holds byte `at`
+ /// (e.g. `resource "aws_s3_bucket_public_access_block" "site"`). None when
+ /// `at` is outside every block, inside a nested block, or in a comment,
+ /// string or heredoc.
+ fn block_at<'s>(&mut self, src: &'s str, at: usize) -> Option<&'s str> {
+ if at < self.i {
+ if self.over_from.is_some_and(|s| s < at) {
+ return None;
+ }
+ *self = Self::default();
+ }
+ let b = src.as_bytes();
+ let mut last = None;
+ while self.i < at {
+ let i = self.i;
+ last = Some(i);
+ match b[i] {
+ b'\n' => self.line_start = i + 1,
+ b'#' => self.i = src[i..].find('\n').map_or(b.len(), |n| i + n) - 1,
+ b'/' if b.get(i + 1) == Some(&b'/') => {
+ self.i = src[i..].find('\n').map_or(b.len(), |n| i + n) - 1
+ }
+ b'/' if b.get(i + 1) == Some(&b'*') => {
+ self.i = src[i + 2..].find("*/").map_or(b.len(), |n| i + 2 + n + 1);
+ // `/* note */ resource ... {`: the header starts after the comment.
+ if src[self.line_start..i].trim().is_empty() {
+ self.line_start = (self.i + 1).min(b.len());
+ }
+ }
+ b'"' => {
+ let j = hcl_string_end(b, i);
+ // An unclosed string ends at its newline, which the walk still reads.
+ self.i = if b.get(j) == Some(&b'\n') { j - 1 } else { j };
+ }
+ b'<' if src[i..].starts_with("<<") => {
+ let rest = src[i + 2..].trim_start_matches('-');
+ let tag: &str = rest
+ .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
+ .next()
+ .unwrap_or("");
+ if !tag.is_empty() {
+ let body = src[i..].find('\n').map_or(b.len(), |n| i + n + 1);
+ let mut end = b.len();
+ let mut pos = body;
+ for l in src[body..].split_inclusive('\n') {
+ pos += l.len();
+ if l.trim() == tag {
+ end = pos;
+ break;
+ }
+ }
+ self.line_start = end;
+ self.i = end - 1;
+ }
+ }
+ b'{' => {
+ if self.depth == 0 {
+ self.header = Some((self.line_start, i));
+ }
+ self.depth += 1;
+ }
+ b'}' => {
+ self.depth = self.depth.saturating_sub(1);
+ // A next block on the same line starts its header here.
+ if self.depth == 0 {
+ self.line_start = i + 1;
+ }
+ }
+ _ => {}
+ }
+ self.i += 1;
+ }
+ if self.i > at {
+ self.over_from = last;
+ return None;
+ }
+ self.over_from = None;
+ if self.depth != 1 {
+ return None;
+ }
+ self.header.map(|(s, e)| src[s..e].trim())
+ }
+}
+
+fn is_public_access_block(header: &str) -> bool {
+ let mut words = header.split_whitespace().map(|w| w.trim_matches('"'));
+ words.next() == Some("resource")
+ && matches!(
+ words.next(),
+ Some("aws_s3_bucket_public_access_block" | "aws_s3_account_public_access_block")
+ )
+}
+
+pub fn keep(file: &FileInfo, text: &Text, f: &Finding, hcl: &mut HclWalk) -> bool {
match f.rule.as_str() {
"config.docker-unpinned-image" => {
let stages: Vec<String> = STAGE
@@ -204,6 +375,143 @@ pub fn keep(file: &FileInfo, text: &Text, f: &Finding) -> bool {
"config.gha-script-injection" if workflow(file) => YAML_KEY
.captures(text.line(f.line))
.is_none_or(|c| &c[1] == "run" || &c[1] == "script"),
+ "config.tf-public-access-block" => {
+ let line = text.line(f.line);
+ let start = text.line_start(f.line);
+ PUBLIC_ACCESS_OFF.find_iter(line).any(|m| {
+ hcl.block_at(text.src, start + m.start())
+ .is_some_and(is_public_access_block)
+ })
+ }
_ => true,
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Whether the first `key = false` in `src` is reported: it matches and sits in an S3
+ /// public access block.
+ fn in_block(src: &str) -> bool {
+ let Some(m) = PUBLIC_ACCESS_OFF.find(src) else {
+ return false;
+ };
+ HclWalk::default()
+ .block_at(src, m.start())
+ .is_some_and(is_public_access_block)
+ }
+
+ #[test]
+ fn public_access_block_reads_hcl_around_the_key() {
+ let block = |body: &str| {
+ format!("resource \"aws_s3_bucket_public_access_block\" \"site\" {{\n{body}\n}}\n")
+ };
+ let cases: &[(String, bool)] = &[
+ (block(" block_public_policy = false"), true),
+ // Two top-level blocks on one line: each block's header starts after the last `}`.
+ (
+ "resource \"aws_s3_bucket_public_access_block\" \"a\" {} resource \"aws_s3_access_point\" \"b\" {\n block_public_policy = false\n}\n".to_string(),
+ false,
+ ),
+ (
+ "resource \"aws_s3_access_point\" \"b\" {} resource \"aws_s3_bucket_public_access_block\" \"a\" {\n block_public_policy = false\n}\n".to_string(),
+ true,
+ ),
+ // A block comment before the header on the same line.
+ (
+ "/* site */ resource \"aws_s3_bucket_public_access_block\" \"site\" {\n block_public_policy = false\n}\n".to_string(),
+ true,
+ ),
+ (
+ block(" block_public_policy = false # public website"),
+ true,
+ ),
+ (block(" block_public_policy = \"false\","), true),
+ // `false` is part of a longer expression, not the value.
+ (block(" block_public_policy = false == var.public"), false),
+ // `$${` and `%%{` are literal text, not a template that would swallow the block.
+ (
+ format!(
+ "locals {{\n x = \"$${{\"\n y = \"%%{{\"\n}}\n{}",
+ block(" block_public_policy = false")
+ ),
+ true,
+ ),
+ // A heredoc tag with a hyphen ends at its own line.
+ (
+ format!(
+ "locals {{\n d = <<END-POLICY\nhi\nEND-POLICY\n}}\n{}",
+ block(" block_public_policy = false")
+ ),
+ true,
+ ),
+ // The key itself is fine; the `= false` is in a comment.
+ (
+ block(" block_public_policy = true # was block_public_policy = false"),
+ false,
+ ),
+ (block(" # block_public_policy = false"), false),
+ // A template with a quoted brace, before the block and inside it.
+ (
+ format!(
+ "locals {{\n n = \"${{replace(var.name, \"{{\", \"-\")}}\"\n}}\n{}",
+ block(" block_public_policy = false")
+ ),
+ true,
+ ),
+ (
+ block(
+ " bucket = \"${replace(var.name, \"{\", \"-\")}\"\n block_public_policy = false",
+ ),
+ true,
+ ),
+ (
+ block(" bucket = \"%{ if var.x }{%{ endif }\"\n block_public_policy = false"),
+ true,
+ ),
+ // The `= false` inside a string is not a setting.
+ (
+ block(" note = \"block_public_policy = false\"\n block_public_policy = true"),
+ false,
+ ),
+ // Nested blocks and other resource types are not the access block.
+ (
+ block(" tags = {\n block_public_policy = false\n }"),
+ false,
+ ),
+ (
+ "resource \"aws_s3_access_point\" \"ap\" {\n block_public_policy = false\n}\n"
+ .to_string(),
+ false,
+ ),
+ ];
+ for (src, want) in cases {
+ assert_eq!(in_block(src), *want, "{src}");
+ }
+ }
+
+ #[test]
+ fn hcl_string_end_survives_deep_or_unclosed_templates() {
+ let deep = format!("\"{}", "${\"".repeat(100_000));
+ assert_eq!(hcl_string_end(deep.as_bytes(), 0), deep.len());
+ assert_eq!(hcl_string_end(b"\"abc\nx\"", 0), 4);
+ assert_eq!(hcl_string_end(b"\"a\\\"b\" x", 0), 5);
+ assert_eq!(hcl_string_end(b"\"${ \"}\" }\" x", 0), 9);
+ }
+
+ #[test]
+ fn hcl_walk_gives_the_same_answer_resumed_or_fresh() {
+ // Offsets inside one heredoc and one block comment must not restart the walk (each
+ // restart reads the file from the top again) and must still give the fresh answer.
+ let src = "resource \"aws_s3_bucket_public_access_block\" \"a\" {\n block_public_policy = false\n policy = <<EOF\n block_public_policy = false\n restrict_public_buckets = false\nEOF\n /* block_public_policy = false\n restrict_public_buckets = false */\n restrict_public_buckets = false\n}\nresource \"aws_s3_access_point\" \"b\" {\n restrict_public_buckets = false\n}\n";
+ let offsets: Vec<usize> = PUBLIC_ACCESS_OFF
+ .find_iter(src)
+ .map(|m| m.start())
+ .collect();
+ let mut walk = HclWalk::default();
+ for &at in offsets.iter().chain(offsets.iter().rev()) {
+ assert_eq!(walk.block_at(src, at), HclWalk::default().block_at(src, at));
+ }
+ }
+}
diff --git a/tests/fixtures/config/EXPECTED b/tests/fixtures/config/EXPECTED
index 8ea56a9..2c7d54f 100644
--- a/tests/fixtures/config/EXPECTED
+++ b/tests/fixtures/config/EXPECTED
@@ -12,6 +12,9 @@ Dockerfile:8 config.docker-root-user
docker-compose.yml:3 config.privileged-container
infra/main.tf:3 config.tf-open-ingress
infra/main.tf:6 config.tf-public-bucket
+infra/main.tf:11 config.tf-public-access-block
+infra/main.tf:13 config.tf-public-access-block
+infra/main.tf:17 config.tf-public-access-block
k8s/deploy.yaml:2 config.k8s-host-access
k8s/deploy.yaml:5 config.privileged-container
k8s/deploy.yaml:6 config.privileged-container
diff --git a/tests/fixtures/config/infra/main.tf b/tests/fixtures/config/infra/main.tf
index 3b18026..9b65387 100644
--- a/tests/fixtures/config/infra/main.tf
+++ b/tests/fixtures/config/infra/main.tf
@@ -5,3 +5,28 @@ resource "aws_security_group_rule" "ssh" {
resource "aws_s3_bucket_acl" "b" {
acl = "public-read"
}
+resource "aws_s3_bucket_public_access_block" "site" {
+ bucket = aws_s3_bucket.site.id
+ block_public_acls = false
+ block_public_policy = false
+ ignore_public_acls = false
+ restrict_public_buckets = false
+}
+resource "aws_s3_account_public_access_block" "account" {
+ block_public_policy = true
+ restrict_public_buckets = "false"
+}
+resource "aws_s3_bucket_public_access_block" "private" {
+ bucket = aws_s3_bucket.private.id
+ block_public_policy = true
+ restrict_public_buckets = true
+ # block_public_policy = false
+}
+resource "aws_s3_access_point" "reports" {
+ bucket = aws_s3_bucket.reports.id
+ name = "reports"
+ public_access_block_configuration {
+ block_public_policy = false
+ restrict_public_buckets = false
+ }
+}