Find the holes before someone else does. A fast, 100% Rust vulnerability scanner: XSS, SQL injection, leaked secrets, dependency CVEs and AI agent setups.
Rust ai-agentsclaude-codeclaude-code-pluginclicodexcursordevsecopsmcposvowasprustsastsecret-scanningsecretssecuritysecurity-scannersql-injectionvulnerabilityvulnerability-scannerxss
feat: code, secret, agent, mobile and config rules
Kam9c569173e827
diff --git a/src/rules/agent.rs b/src/rules/agent.rsnew file mode 100644index 0000000..dde3c84--- /dev/null+++ b/src/rules/agent.rs@@ -0,0 +1,388 @@+use serde_json::Value;++use super::{FileInfo, Meta, Rule, Text, finding};+use crate::{Family, Finding, Severity};++pub fn is_mcp_config(f: &FileInfo) -> bool {+ f.name == ".mcp.json"+ || f.name == "mcp.json"+ || f.name == "claude_desktop_config.json"+ || f.name == "opencode.json"+ || f.name == "opencode.jsonc"+ || (f.name.starts_with("settings")+ && f.ext == "json"+ && (f.under(".gemini/") || f.under(".claude/")))+}++fn claude_settings(f: &FileInfo) -> bool {+ f.under(".claude/") && f.name.starts_with("settings") && f.ext == "json"+}++pub fn is_agent_file(f: &FileInfo) -> bool {+ is_mcp_config(f)+ || matches!(+ f.name.as_str(),+ "skill.md"+ | "claude.md"+ | "agents.md"+ | "gemini.md"+ | ".cursorrules"+ | ".windsurfrules"+ | "copilot-instructions.md"+ )+ || (f.under(".codex/") && f.ext == "toml")+ || f.under(".claude/commands/")+ || f.under(".claude/agents/")+ || f.under(".claude/skills/")+ || f.under(".claude/hooks/")+ || f.under(".cursor/rules/")+ || f.under(".gemini/commands/")+}++macro_rules! rule {+ ($id:literal, $sev:ident, $files:ident, $pat:literal, $unless:expr, $msg:literal, $fix:literal) => {+ Rule {+ id: $id,+ family: Family::Agent,+ severity: Severity::$sev,+ files: $files,+ pattern: $pat,+ unless: $unless,+ message: $msg,+ fix: $fix,+ }+ };+}++pub static RULES: &[Rule] = &[+ rule!(+ "agent.bypass-permissions",+ High,+ is_agent_file,+ r#""defaultMode"\s*:\s*"bypassPermissions"|--dangerously-skip-permissions|--dangerously-bypass-approvals-and-sandbox|sandbox_mode\s*=\s*"danger-full-access"|--yolo\b"#,+ None,+ "The agent is set to run every action without asking, so one bad instruction can do anything on this machine.",+ "Use the default or an accept-edits mode and allow specific commands instead of skipping all approvals."+ ),+ rule!(+ "agent.unrestricted-shell",+ High,+ claude_settings,+ r#""Bash(?:\(\*\)|\(:\*\))?""#,+ None,+ "Every shell command is pre-approved, so the agent can run anything without asking.",+ "Allow specific commands, for example \"Bash(npm test:*)\"."+ ),+ rule!(+ "agent.remote-script",+ High,+ is_agent_file,+ r"\b(?:curl|wget)\b[^|\n]*?(?:https?://|\$\{?\w)[^|\n]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh|python3?|node)\b",+ None,+ "A script is downloaded and run straight from the internet; whoever controls that URL controls this machine.",+ "Download, review and pin the script (or a checksum), or install the tool from a package manager."+ ),+ rule!(+ "agent.prompt-injection",+ Medium,+ is_agent_file,+ r"(?i)\b(?:ignore|disregard|forget)\s+(?:all\s+|any\s+)?(?:the\s+)?(?:previous|prior|above|earlier)\s+(?:instructions|rules|directions|prompts?)|\b(?:do\s+not|don't|never)\s+(?:tell|inform|notify|alert)\s+the\s+user|\bwithout\s+(?:telling|asking|informing|notifying)\s+the\s+user|\bexfiltrat",+ Some(+ r#"(?i)["“'‘(]\s*(?:ignore|disregard|forget)|\b(?:never|don't|do not|must not|should not|shouldn't|not)\b[^.]{0,80}\bwithout\s+(?:asking|telling|informing|notifying)|\b(?:must not|never|do not|don't)\s+(?:contain|follow|obey|act on|comply)|\b(?:malware|injection|attack|malicious|treat\b[^.]*\bas data)"#+ ),+ "Instruction text tells the agent to override its rules or hide actions from the user (prompt injection).",+ "Remove the text, and do not install skills or rules from sources you have not read."+ ),+ rule!(+ "agent.sensitive-file-access",+ High,+ is_agent_file,+ r"~/\.ssh\b|\bid_(?:rsa|ed25519|ecdsa)\b|\.aws/credentials|\.netrc\b|\.git-credentials|/etc/shadow|\bLogin Data\b|security\s+find-(?:generic|internet)-password",+ None,+ "Agent instructions read credential files such as SSH keys or cloud credentials.",+ "Remove the step; an agent never needs your private keys or credential stores."+ ),+ rule!(+ "agent.hidden-unicode",+ High,+ is_agent_file,+ r"[\x{E0000}-\x{E007F}\x{200B}\x{200C}\x{200E}\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}]",+ None,+ "Invisible Unicode characters are in agent instructions; they can hide text the agent reads but you don't see.",+ "Delete the invisible characters and review what they spelled out."+ ),+];++pub static STRUCTURED: &[(&str, Severity, &str)] = &[+ (+ "agent.mcp-unpinned",+ Severity::Medium,+ "An MCP server is started from a package or image with no pinned version.",+ ),+ (+ "agent.mcp-plaintext-secret",+ Severity::High,+ "An MCP server's token or key is written in plain text in the config.",+ ),+ (+ "agent.mcp-insecure-url",+ Severity::High,+ "A remote MCP server is reached over plain HTTP.",+ ),+];++pub fn structured(file: &FileInfo, text: &Text) -> Vec<Finding> {+ if !is_mcp_config(file) {+ return Vec::new();+ }+ let Ok(json) = serde_json::from_str::<Value>(&strip_jsonc(text.src)) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ for key in ["mcpServers", "servers", "mcp", "context_servers"] {+ let Some(servers) = json.get(key).and_then(Value::as_object) else {+ continue;+ };+ for (name, server) in servers {+ let start = text.src.find(&format!("\"{name}\"")).unwrap_or(0);+ check_server(file, text, start, server, &mut out);+ }+ }+ out+}++fn check_server(+ file: &FileInfo,+ text: &Text,+ start: usize,+ server: &Value,+ out: &mut Vec<Finding>,+) {+ let mut argv: Vec<String> = Vec::new();+ match server.get("command") {+ Some(Value::String(c)) => argv.push(c.clone()),+ Some(Value::Array(a)) => argv.extend(a.iter().filter_map(|v| v.as_str().map(String::from))),+ _ => {}+ }+ if let Some(Value::Array(a)) = server.get("args") {+ argv.extend(a.iter().filter_map(|v| v.as_str().map(String::from)));+ }+ if let Some(spec) = unpinned(&argv) {+ let line = line_after(text, start, &format!("\"{spec}\""));+ out.push(finding(+ file,+ text,+ line,+ Meta {+ id: "agent.mcp-unpinned",+ family: Family::Agent,+ severity: Severity::Medium,+ message: &format!("The MCP server runs `{spec}` without a pinned version, so every start installs whatever was published last."),+ fix: "Pin an exact version ([email protected], pkg==1.2.3, or an image digest) and update on purpose.",+ secret: None,+ },+ ));+ }+ for env_key in ["env", "environment"] {+ let Some(env) = server.get(env_key).and_then(Value::as_object) else {+ continue;+ };+ for (k, v) in env {+ let Some(v) = v.as_str() else { continue };+ let secretish = {+ let k = k.to_ascii_lowercase();+ [+ "token",+ "key",+ "secret",+ "password",+ "pat",+ "auth",+ "credential",+ ]+ .iter()+ .any(|s| k.contains(s))+ };+ if secretish+ && v.len() >= 8+ && !v.starts_with('$')+ && !v.starts_with('<')+ && !v.contains("{env:")+ {+ let line = line_after(text, start, &format!("\"{k}\""));+ out.push(finding(+ file,+ text,+ line,+ Meta {+ id: "agent.mcp-plaintext-secret",+ family: Family::Agent,+ severity: Severity::High,+ message: &format!("The MCP server's {k} is written in plain text in the config."),+ fix: "Reference an environment variable (\"${VAR}\") and keep the value out of files that get shared or committed.",+ secret: Some(v),+ },+ ));+ }+ }+ }+ if let Some(url) = server+ .get("url")+ .or_else(|| server.get("serverUrl"))+ .and_then(Value::as_str)+ {+ if let Some(rest) = url.strip_prefix("http://") {+ let host = rest.split(['/', ':']).next().unwrap_or("");+ if !matches!(host, "localhost" | "127.0.0.1" | "[") && !host.starts_with("[::1") {+ let line = line_after(text, start, url);+ out.push(finding(+ file,+ text,+ line,+ Meta {+ id: "agent.mcp-insecure-url",+ family: Family::Agent,+ severity: Severity::High,+ message: "A remote MCP server is reached over plain HTTP, so its tools and your data can be read or changed on the way.",+ fix: "Use https:// for every MCP server that is not on this machine.",+ secret: None,+ },+ ));+ }+ }+ }+}++fn unpinned(argv: &[String]) -> Option<String> {+ let cmd = argv.first()?;+ let base = cmd+ .rsplit(['/', '\\'])+ .next()+ .unwrap_or(cmd)+ .trim_end_matches(".cmd")+ .trim_end_matches(".exe");+ let rest = &argv[1..];+ let positional = |skip: &[&str]| {+ rest.iter()+ .find(|a| !a.starts_with('-') && !skip.contains(&a.as_str()))+ .cloned()+ };+ match base {+ "npx" | "bunx" | "pnpx" => {+ let pkg = positional(&[])?;+ (!npm_pinned(&pkg)).then_some(pkg)+ }+ "pnpm" | "yarn" | "bun"+ if rest.first().map(String::as_str) == Some("dlx")+ || rest.first().map(String::as_str) == Some("x") =>+ {+ let pkg = rest[1..].iter().find(|a| !a.starts_with('-')).cloned()?;+ (!npm_pinned(&pkg)).then_some(pkg)+ }+ "uvx" | "pipx" => {+ let pkg = match rest.iter().position(|a| a == "--from") {+ Some(i) => rest.get(i + 1).cloned()?,+ None => positional(&["run"])?,+ };+ (!(pkg.contains("==")+ || pkg.contains('@')+ || pkg.starts_with('.')+ || pkg.starts_with('/')))+ .then_some(pkg)+ }+ "docker" | "podman" => {+ let i = rest.iter().position(|a| a == "run")?;+ let mut it = rest[i + 1..].iter();+ let image = loop {+ let a = it.next()?;+ if a.starts_with('-') {+ if matches!(+ a.as_str(),+ "-e" | "-v"+ | "-p"+ | "--env"+ | "--volume"+ | "--name"+ | "--network"+ | "-w"+ | "--mount"+ | "--env-file"+ ) {+ it.next();+ }+ continue;+ }+ break a.clone();+ };+ let last = image.rsplit('/').next().unwrap_or(&image);+ let pinned =+ image.contains("@sha256:") || (last.contains(':') && !last.ends_with(":latest"));+ (!pinned).then_some(image)+ }+ _ => None,+ }+}++fn npm_pinned(pkg: &str) -> bool {+ if pkg.starts_with('.') || pkg.starts_with('/') {+ return true;+ }+ match pkg[1..].rfind('@') {+ Some(i) => {+ let v = &pkg[i + 2..];+ !v.is_empty() && v != "latest" && v.chars().next().is_some_and(|c| c.is_ascii_digit())+ }+ None => false,+ }+}++fn line_after(text: &Text, start: usize, needle: &str) -> usize {+ let at = text.src[start..]+ .find(needle)+ .map(|i| start + i)+ .unwrap_or(start);+ text.line_of(at)+}++fn strip_jsonc(src: &str) -> String {+ let mut out = String::with_capacity(src.len());+ let mut chars = src.chars().peekable();+ let mut in_str = false;+ while let Some(c) = chars.next() {+ if in_str {+ out.push(c);+ if c == '\\' {+ if let Some(n) = chars.next() {+ out.push(n);+ }+ } else if c == '"' {+ in_str = false;+ }+ } else if c == '"' {+ in_str = true;+ out.push(c);+ } else if c == '/' && chars.peek() == Some(&'/') {+ for n in chars.by_ref() {+ if n == '\n' {+ out.push('\n');+ break;+ }+ }+ } else if c == '/' && chars.peek() == Some(&'*') {+ chars.next();+ let mut prev = ' ';+ for n in chars.by_ref() {+ if n == '\n' {+ out.push('\n');+ }+ if prev == '*' && n == '/' {+ break;+ }+ prev = n;+ }+ } else {+ out.push(c);+ }+ }+ out+}diff --git a/src/rules/code.rs b/src/rules/code.rsnew file mode 100644index 0000000..3963537--- /dev/null+++ b/src/rules/code.rs@@ -0,0 +1,493 @@+use super::{FileInfo, Rule};+use crate::{Family, Severity};++fn js(f: &FileInfo) -> bool {+ f.ext_in(&[+ "js", "jsx", "ts", "tsx", "mjs", "cjs", "vue", "svelte", "html", "htm", "astro",+ ])+}+fn py(f: &FileInfo) -> bool {+ f.ext == "py"+}+fn go(f: &FileInfo) -> bool {+ f.ext == "go"+}+fn jvm(f: &FileInfo) -> bool {+ f.ext_in(&["java", "kt", "scala", "groovy"])+}+fn php(f: &FileInfo) -> bool {+ f.ext_in(&["php", "phtml"])+}+fn rb(f: &FileInfo) -> bool {+ f.ext_in(&["rb", "erb", "haml"])+}+fn cs(f: &FileInfo) -> bool {+ f.ext_in(&["cs", "cshtml", "razor"])+}+fn sql(f: &FileInfo) -> bool {+ f.ext == "sql"+}+fn vue_svelte(f: &FileInfo) -> bool {+ f.ext_in(&["vue", "svelte", "html", "htm"])+}+fn django_settings(f: &FileInfo) -> bool {+ f.name == "settings.py"+}+fn code(f: &FileInfo) -> bool {+ js(f) || py(f) || go(f) || jvm(f) || php(f) || rb(f) || cs(f)+}+fn js_py(f: &FileInfo) -> bool {+ js(f) || py(f)+}++macro_rules! kw {+ () => {+ r"(?i:select\s.+?\sfrom\b|insert\s+into\b|update\s+\w+\s+set\b|delete\s+from\b)"+ };+}++macro_rules! rule {+ ($id:literal, $sev:ident, $files:ident, $pat:expr, $unless:expr, $msg:expr, $fix:expr) => {+ Rule {+ id: $id,+ family: Family::Code,+ severity: Severity::$sev,+ files: $files,+ pattern: $pat,+ unless: $unless,+ message: $msg,+ fix: $fix,+ }+ };+}++const SQLI_MSG: &str = "A SQL query is built from variables by string formatting, so input can change the query (SQL injection).";+const SQLI_FIX: &str = "Use parameterized queries (placeholders like ?, $1 or %s passed separately) or the ORM's query builder.";+const CMD_MSG: &str =+ "A shell command is built from variables, so input can run other commands (command injection).";+const CMD_FIX: &str = "Call the program directly with an argument list (no shell), and validate the input against an allow list.";+const DESER_MSG: &str =+ "Untrusted data is deserialized with a format that can run code or build arbitrary objects.";+const DESER_FIX: &str = "Use a data-only format such as JSON, or a safe loader, and never deserialize input from users or the network.";++pub static RULES: &[Rule] = &[+ rule!(+ "code.xss-inner-html",+ Medium,+ js,+ r"\.(?:inner|outer)HTML\s*\+?=[^=]",+ Some(r#"(?:inner|outer)HTML\s*\+?=\s*(?:''|""|``|'[^'$+]*'\s*;?\s*$|"[^"$+]*"\s*;?\s*$)"#),+ "HTML is written from a variable; if it holds user input, scripts run in the page (XSS).",+ "Use textContent for text, or sanitize the HTML with a library such as DOMPurify first."+ ),+ rule!(+ "code.xss-document-write",+ Medium,+ js,+ r"\bdocument\.write(?:ln)?\s*\(",+ None,+ "document.write puts raw HTML into the page; with user input this is XSS.",+ "Build elements with the DOM API and set textContent instead."+ ),+ rule!(+ "code.xss-dangerously-set-inner-html",+ Medium,+ js,+ r"dangerouslySetInnerHTML\s*=",+ Some(r"(?i)purify|sanitize"),+ "dangerouslySetInnerHTML renders raw HTML; with user content this is XSS.",+ "Render the text as children, or sanitize the HTML (DOMPurify) right where it is set."+ ),+ rule!(+ "code.xss-v-html",+ Medium,+ vue_svelte,+ r#"\bv-html\s*=|\{@html\s"#,+ Some(r"(?i)purify|sanitize"),+ "Raw HTML is rendered from a variable; with user content this is XSS.",+ "Use text interpolation, or sanitize the HTML before rendering it."+ ),+ rule!(+ "code.xss-reflected",+ Medium,+ php,+ r"\b(?:echo|print)\s*\(?\s*\$_(?:GET|POST|REQUEST|COOKIE)\b",+ None,+ "Request input is printed into the page without escaping (reflected XSS).",+ "Escape output with htmlspecialchars($value, ENT_QUOTES, 'UTF-8')."+ ),+ rule!(+ "code.xss-raw-html",+ Medium,+ rb,+ r"\braw\s*\(?\s*@|\.html_safe\b",+ None,+ "A value is marked as safe HTML, so Rails will not escape it (XSS if it holds user input).",+ "Let Rails escape it, or sanitize it with the sanitize helper."+ ),+ rule!(+ "code.eval",+ High,+ code,+ r"(?m)(?:^|[^\w.$\n])eval\s*\(|\bnew\s+Function\s*\(",+ Some(r#"new\s+Function\s*\(\s*(?:(?:'[^']*'|"[^"]*")\s*,?\s*)+\)"#),+ "Code is evaluated from a string at run time; if any part comes from input, an attacker can run code.",+ "Remove eval. Parse data with JSON.parse / json.loads, or map allowed inputs to functions."+ ),+ rule!(+ "code.command-injection",+ High,+ js,+ r#"(?m)(?:^|[^.\w\n]|\b(?:child_process|childProcess|cp)\.)(?:exec|execSync)\s*\(\s*(?:`[^`]*\$\{|['"][^'"]*['"]\s*\+)"#,+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.command-injection",+ High,+ py,+ r#"\bshell\s*=\s*True|\bos\.(?:system|popen)\s*\(\s*(?:f["']|[A-Za-z_]|["'][^"']*["']\s*[+%])"#,+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.command-injection",+ High,+ go,+ r#"exec\.Command(?:Context)?\((?:\s*\w+\s*,)?\s*"(?:sh|bash|/bin/sh|/bin/bash|cmd|cmd\.exe)"\s*,\s*"(?:-c|/c|/C)""#,+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.command-injection",+ High,+ jvm,+ r#"Runtime\.getRuntime\(\)\.exec\(\s*(?:"[^"]*"\s*\+|[a-z_]\w*\s*\))"#,+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.command-injection",+ Critical,+ php,+ r"\b(?:system|exec|shell_exec|passthru|popen|proc_open)\s*\([^)]*\$_(?:GET|POST|REQUEST|COOKIE)\b",+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.command-injection",+ High,+ php,+ r#"\b(?:system|exec|shell_exec|passthru|popen|proc_open)\s*\(\s*(?:['"][^'"]*['"]\s*\.\s*\$|"[^"]*\$[A-Za-z_{])"#,+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.command-injection",+ High,+ rb,+ r#"\b(?:system|exec|spawn)\s*\(?\s*"[^"]*#\{|`[^`]*#\{|%x\([^)]*#\{"#,+ None,+ CMD_MSG,+ CMD_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ js,+ concat!(+ r#"`\s*"#,+ kw!(),+ r#"[^`]*\$\{|["']\s*"#,+ kw!(),+ r#"[^"']*["']\s*\+\s*[A-Za-z_$]"#+ ),+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ py,+ concat!(+ r#"\bf"\s*"#,+ kw!(),+ r#"[^"]*\{|\bf'\s*"#,+ kw!(),+ r#"[^']*\{|"\s*"#,+ kw!(),+ r#"[^"]*"\s*(?:%\s*[\w(]|\+\s*[A-Za-z_]|\.format\()|'\s*"#,+ kw!(),+ r#"[^']*'\s*(?:%\s*[\w(]|\+\s*[A-Za-z_]|\.format\()"#+ ),+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ go,+ r#"fmt\.Sprintf\(\s*"(?i:select|insert|update|delete)[^"]*%[sdvq]"#,+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ jvm,+ concat!(r#""\s*"#, kw!(), r#"[^"]*"\s*\+\s*[A-Za-z_]"#),+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ php,+ concat!(+ r#"["']\s*"#,+ kw!(),+ r#"[^"']*["']\s*\.\s*\$|"\s*"#,+ kw!(),+ r#"[^"]*\$[A-Za-z_{]"#+ ),+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ rb,+ concat!(+ r#"\.(?:where|find_by_sql|order|group|having|joins|select|pluck|exists\?)\(\s*"[^"]*#\{|"\s*"#,+ kw!(),+ r#"[^"]*#\{"#+ ),+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.sql-injection",+ High,+ cs,+ concat!(+ r#""\s*"#,+ kw!(),+ r#"[^"]*"\s*\+\s*[A-Za-z_]|\$@?"\s*"#,+ kw!(),+ r#"[^"]*\{"#+ ),+ None,+ SQLI_MSG,+ SQLI_FIX+ ),+ rule!(+ "code.path-traversal",+ High,+ js,+ r"\b(?:sendFile|readFile|readFileSync|createReadStream|download|unlink|unlinkSync)\s*\(\s*req\.(?:query|params|body)",+ Some(r"\broot\s*:"),+ "A file path comes straight from the request, so ../ can reach any file on the server (path traversal).",+ "Resolve the path against a fixed base directory and reject results outside it, or map ids to known files."+ ),+ rule!(+ "code.path-traversal",+ High,+ py,+ r"\b(?:open|send_file|send_from_directory)\s*\(\s*request\.(?:args|form|values|GET|POST|files|json)",+ None,+ "A file path comes straight from the request, so ../ can reach any file on the server (path traversal).",+ "Resolve the path against a fixed base directory and reject results outside it, or map ids to known files."+ ),+ rule!(+ "code.ssrf",+ High,+ js,+ r"\b(?:fetch|axios(?:\.(?:get|post|put|request))?|got|needle|http\.get|https\.get|request)\s*\(\s*req\.(?:query|params|body)",+ None,+ "The server fetches a URL taken from the request, so users can reach internal services (SSRF).",+ "Allow only known hosts, block private and link-local addresses, and never pass the raw URL through."+ ),+ rule!(+ "code.ssrf",+ High,+ py,+ r"\b(?:requests\.(?:get|post|put|head|request)|urlopen|httpx\.(?:get|post))\s*\(\s*request\.(?:args|form|values|GET|POST|json)",+ None,+ "The server fetches a URL taken from the request, so users can reach internal services (SSRF).",+ "Allow only known hosts, block private and link-local addresses, and never pass the raw URL through."+ ),+ rule!(+ "code.tls-verify-off",+ Medium,+ code,+ r#"rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0|\bverify\s*=\s*False\b|InsecureSkipVerify\s*:\s*true|CURLOPT_SSL_VERIFYPEER\s*,\s*(?:false|0)\b|ServerCertificateValidationCallback\s*=[^;]*=>\s*true"#,+ None,+ "TLS certificate checks are turned off, so anyone on the network can read or change the traffic.",+ "Keep verification on; for a private CA, pass its certificate (ca / verify=path) instead of disabling checks."+ ),+ rule!(+ "code.weak-hash",+ Low,+ code,+ r#"createHash\(\s*['"](?:md5|sha1)['"]|hashlib\.(?:md5|sha1)\(|\b(?:md5|sha1)\.New\(\)|MessageDigest\.getInstance\(\s*"(?:MD5|SHA-?1)"|\b(?:md5|sha1)\s*\(\s*\$\w*(?:pass|pwd)"#,+ None,+ "MD5 and SHA-1 are broken for security use (collisions; too fast for passwords).",+ "Use SHA-256 or better for integrity, and bcrypt, scrypt or Argon2 for passwords. Ignore if this is a non-security checksum."+ ),+ rule!(+ "code.weak-cipher",+ Medium,+ code,+ r#"Cipher\.getInstance\(\s*"(?:DES|RC4|DESede|[^"]*/ECB/)|\bDES\.new\(|\bARC4\.new\(|\bMODE_ECB\b|createCipheriv\(\s*['"](?:des|rc4|aes-\d+-ecb)"#,+ None,+ "A weak cipher or ECB mode is used; ECB leaks patterns and DES/RC4 are broken.",+ "Use AES-GCM or ChaCha20-Poly1305 with a random nonce."+ ),+ rule!(+ "code.insecure-cookie",+ Low,+ js_py,+ r"\b(?:httpOnly|httponly|secure)\s*[:=]\s*(?:false|False)\b",+ None,+ "A cookie is set without HttpOnly or Secure, so scripts or plain HTTP can read it.",+ "Set httpOnly: true and secure: true (and sameSite) on session cookies."+ ),+ rule!(+ "code.jwt-none",+ High,+ js_py,+ r#"algorithms\s*[:=]\s*\[\s*['"]none['"]|['"]verify_signature['"]\s*:\s*False|jwt\.decode\([^)]*verify\s*=\s*False"#,+ None,+ "JWT signatures are not checked, so anyone can forge a token.",+ "Verify tokens with a fixed list of real algorithms (e.g. RS256 or HS256) and the right key."+ ),+ rule!(+ "code.cors-wildcard",+ Low,+ code,+ r#"Access-Control-Allow-Origin['"]?\s*[,:]\s*['"]\*['"]"#,+ None,+ "CORS allows every origin. Fine for public data; risky for anything behind a login.",+ "List the origins that may call the API instead of *."+ ),+ rule!(+ "code.insecure-random",+ Medium,+ js_py,+ r"(?i)(?:token|secret|password|nonce|salt|session|otp|api_?key)\w*\s*[:=][^\n]*(?:Math\.random\(\)|random\.(?:random|randint|choice)\()",+ None,+ "A secret value is made with a non-cryptographic random generator, which can be predicted.",+ "Use crypto.randomUUID() / crypto.getRandomValues() in JS, or the secrets module in Python."+ ),+ rule!(+ "code.debug-enabled",+ Medium,+ py,+ r"\.run\([^)]*\bdebug\s*=\s*True",+ None,+ "The app runs in debug mode; the debugger can run code and leaks internals.",+ "Turn debug off outside local development (read it from the environment)."+ ),+ rule!(+ "code.debug-enabled",+ Medium,+ django_settings,+ r"(?m)^\s*DEBUG\s*=\s*True\b",+ None,+ "Django DEBUG is on; error pages leak settings and code.",+ "Set DEBUG from the environment and keep it False in production."+ ),+ rule!(+ "code.template-injection",+ High,+ py,+ r"\brender_template_string\s*\(\s*request\.|\bTemplate\s*\(\s*request\.",+ None,+ "A template is built from request input, so users can run code in the template engine (SSTI).",+ "Render fixed template files and pass user input only as variables."+ ),+ rule!(+ "code.unsafe-deserialization",+ High,+ py,+ r"\bpickle\.loads?\s*\(|\byaml\.load\s*\(|\bmarshal\.loads?\s*\(",+ Some(r"Loader\s*=\s*(?:yaml\.)?C?SafeLoader"),+ DESER_MSG,+ DESER_FIX+ ),+ rule!(+ "code.unsafe-deserialization",+ High,+ jvm,+ r"\bnew\s+ObjectInputStream\s*\(|\bXMLDecoder\s*\(",+ None,+ DESER_MSG,+ DESER_FIX+ ),+ rule!(+ "code.unsafe-deserialization",+ Critical,+ php,+ r"\bunserialize\s*\(\s*\$_(?:GET|POST|REQUEST|COOKIE)\b",+ None,+ DESER_MSG,+ DESER_FIX+ ),+ rule!(+ "code.unsafe-deserialization",+ High,+ rb,+ r"\bMarshal\.load\s*\(|\bYAML\.load\s*\(",+ Some(r"permitted_classes|safe_load"),+ DESER_MSG,+ DESER_FIX+ ),+ rule!(+ "code.unsafe-deserialization",+ High,+ cs,+ r"\bBinaryFormatter\b|\bNetDataContractSerializer\b|TypeNameHandling\.(?:All|Auto|Objects)",+ None,+ DESER_MSG,+ DESER_FIX+ ),+ rule!(+ "code.file-inclusion",+ Critical,+ php,+ r"\b(?:include|require)(?:_once)?\s*\(?\s*\$_(?:GET|POST|REQUEST|COOKIE)\b",+ None,+ "A file to include comes from the request, so attackers can load other files or remote code.",+ "Map allowed page names to fixed files instead of including request input."+ ),+ rule!(+ "code.sql-grant-all",+ Medium,+ sql,+ r"(?i)\bGRANT\s+ALL(?:\s+PRIVILEGES)?\s+ON\s+\*\.\*",+ None,+ "A database user gets every privilege on every database.",+ "Grant only the privileges the app needs on its own database."+ ),+ rule!(+ "code.sql-plaintext-password",+ Medium,+ sql,+ r"(?i)\bIDENTIFIED\s+BY\s+'[^']+'|\bWITH\s+PASSWORD\s+'[^']+'|\bCREATE\s+(?:USER|ROLE)\b[^;]*\bPASSWORD\s+'[^']+'",+ None,+ "A database password is written in a SQL file.",+ "Create users with passwords passed in at deploy time, not stored in migrations."+ ),+];diff --git a/src/rules/config.rs b/src/rules/config.rsnew file mode 100644index 0000000..03b29d4--- /dev/null+++ b/src/rules/config.rs@@ -0,0 +1,209 @@+use std::sync::LazyLock;++use regex::Regex;++use super::{FileInfo, Rule, Text};+use crate::Finding;+use crate::{Family, Severity};++fn dockerfile(f: &FileInfo) -> bool {+ f.name == "dockerfile"+ || f.name.starts_with("dockerfile.")+ || f.name.ends_with(".dockerfile")+ || f.name == "containerfile"+}+fn shell(f: &FileInfo) -> bool {+ f.ext_in(&["sh", "bash", "zsh", "ps1"])+ || f.name == "makefile"+ || f.name == "justfile"+ || dockerfile(f)+}+fn workflow(f: &FileInfo) -> bool {+ f.under(".github/workflows/") && f.ext_in(&["yml", "yaml"])+}+fn yaml(f: &FileInfo) -> bool {+ f.ext_in(&["yml", "yaml"])+}+fn terraform(f: &FileInfo) -> bool {+ f.ext_in(&["tf", "hcl"])+}+fn server_conf(f: &FileInfo) -> bool {+ f.ext == "conf" || f.name == "nginx.conf" || f.name == "httpd.conf" || f.name == ".htaccess"+}++macro_rules! rule {+ ($id:literal, $sev:ident, $files:ident, $pat:literal, $unless:expr, $msg:literal, $fix:literal) => {+ Rule {+ id: $id,+ family: Family::Config,+ severity: Severity::$sev,+ files: $files,+ pattern: $pat,+ unless: $unless,+ message: $msg,+ fix: $fix,+ }+ };+}++pub static RULES: &[Rule] = &[+ rule!(+ "config.remote-script",+ Medium,+ shell,+ r"\b(?:curl|wget|iwr|Invoke-WebRequest)\b[^|\n]*?(?:https?://|\$\{?\w)[^|\n]*\|\s*(?:sudo\s+)?(?:sh|bash|zsh|python3?|iex)\b",+ None,+ "A script is downloaded and piped straight into a shell, with no pinning or checksum.",+ "Download to a file, verify a pinned checksum or signature, then run it; or use a package manager."+ ),+ rule!(+ "config.docker-unpinned-image",+ Low,+ dockerfile,+ r"(?mi)^FROM\s+(?:--platform=\S+\s+)?[^\s:@$]+(?::latest)?(?:\s+AS\s+\S+)?\s*$",+ Some(r"(?i)^FROM\s+scratch\b"),+ "The base image has no version tag (or uses latest), so builds change without notice.",+ "Pin a version tag, ideally with a digest (image:1.2@sha256:...)."+ ),+ rule!(+ "config.docker-secret-env",+ High,+ dockerfile,+ r"(?mi)^(?:ENV|ARG)\s+\w*(?:PASSWORD|SECRET|TOKEN|API_?KEY|PRIVATE_KEY)\w*\s*[= ]\s*\S+",+ None,+ "A secret is baked into the image; anyone who pulls it can read it from the layers.",+ "Pass secrets at run time, or use BuildKit secrets (RUN --mount=type=secret)."+ ),+ rule!(+ "config.docker-add-url",+ Low,+ dockerfile,+ r"(?mi)^ADD\s+https?://",+ None,+ "ADD downloads a remote file at build time without checking it.",+ "Download with curl and verify a checksum, or COPY a vendored file."+ ),+ rule!(+ "config.docker-root-user",+ Medium,+ dockerfile,+ r"(?mi)^USER\s+(?:root|0)\s*$",+ None,+ "The container runs as root, so a break-out starts with full privileges.",+ "Create an unprivileged user and switch to it with USER."+ ),+ rule!(+ "config.gha-pull-request-target",+ Medium,+ workflow,+ r"(?m)^\s*pull_request_target\s*:|on:\s*\[[^\]\n]*pull_request_target",+ None,+ "pull_request_target runs with repository secrets on code from forks; checking out the PR head here is a known takeover path.",+ "Use pull_request, or never check out or run the PR's code in this workflow."+ ),+ rule!(+ "config.gha-write-all",+ Medium,+ workflow,+ r"permissions\s*:\s*write-all",+ None,+ "The workflow token can write to everything in the repository.",+ "Set permissions: contents: read, and grant writes per job only where needed."+ ),+ rule!(+ "config.gha-unpinned-action",+ Medium,+ workflow,+ r"uses:\s*[\w.\-]+/[\w./\-]+@(?:main|master|dev|develop|HEAD|latest)\b",+ None,+ "A third-party action runs from a moving branch, so any push to it runs in your CI with your secrets.",+ "Pin the action to a full commit SHA."+ ),+ rule!(+ "config.gha-script-injection",+ High,+ workflow,+ r"\$\{\{\s*github\.(?:event\.(?:issue|pull_request|comment|review|review_comment|discussion|head_commit|commits|pages)[\w.\[\]*]*\.(?:title|body|message|name|label|ref|email|default_branch)|head_ref)\s*\}\}",+ None,+ "Text an outsider controls (a PR title, issue body, branch name) is pasted into the workflow, so it can run commands.",+ "Pass it through an env: variable and use \"$VAR\" in the script."+ ),+ rule!(+ "config.privileged-container",+ High,+ yaml,+ r"(?m)^\s*(?:privileged|allowPrivilegeEscalation)\s*:\s*true\b",+ None,+ "A container runs privileged (or may gain privileges), which gives it near-root access to the host.",+ "Remove privileged and set allowPrivilegeEscalation: false; add only the capabilities you need."+ ),+ rule!(+ "config.k8s-host-access",+ High,+ yaml,+ r"(?m)^\s*host(?:Network|PID|IPC)\s*:\s*true\b",+ None,+ "The pod shares the host's network, process or IPC namespace.",+ "Remove hostNetwork/hostPID/hostIPC unless the workload truly needs it."+ ),+ rule!(+ "config.tf-open-ingress",+ Medium,+ terraform,+ r#"\bcidr_blocks\s*=\s*\[\s*"0\.0\.0\.0/0"|\bipv6_cidr_blocks\s*=\s*\[\s*"::/0""#,+ None,+ "A network rule is open to the whole internet.",+ "Limit the CIDR to known addresses, especially for SSH, RDP and databases. Ignore for public web ports or egress."+ ),+ rule!(+ "config.tf-public-bucket",+ High,+ terraform,+ r#"\bacl\s*=\s*"public-read(?:-write)?""#,+ None,+ "A storage bucket is public.",+ "Make it private and serve files through a CDN or signed URLs."+ ),+ rule!(+ "config.nginx-autoindex",+ Low,+ server_conf,+ r"(?m)^\s*autoindex\s+on\s*;",+ None,+ "Directory listing is on, so every file in the folder can be browsed.",+ "Set autoindex off."+ ),+ rule!(+ "config.weak-tls-version",+ Medium,+ server_conf,+ r"(?i)(?:ssl_protocols|SSLProtocol)[^;\n]*\b(?:SSLv[23]|TLSv1|TLSv1\.1)(?:\s|;|$)",+ None,+ "Old TLS or SSL versions are enabled; they have known attacks.",+ "Allow only TLSv1.2 and TLSv1.3."+ ),+];++static STAGE: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"(?mi)^FROM\s+\S+\s+AS\s+(\S+)").unwrap());+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());++pub fn keep(file: &FileInfo, text: &Text, f: &Finding) -> bool {+ match f.rule.as_str() {+ "config.docker-unpinned-image" => {+ let stages: Vec<String> = STAGE+ .captures_iter(text.src)+ .map(|c| c[1].to_ascii_lowercase())+ .collect();+ FROM.captures(text.line(f.line))+ .is_none_or(|c| !stages.contains(&c[1].to_ascii_lowercase()))+ }+ "config.gha-script-injection" if workflow(file) => YAML_KEY+ .captures(text.line(f.line))+ .is_none_or(|c| &c[1] == "run" || &c[1] == "script"),+ _ => true,+ }+}diff --git a/src/rules/mobile.rs b/src/rules/mobile.rsnew file mode 100644index 0000000..4228094--- /dev/null+++ b/src/rules/mobile.rs@@ -0,0 +1,117 @@+use super::{FileInfo, Rule};+use crate::{Family, Severity};++fn manifest(f: &FileInfo) -> bool {+ f.name == "androidmanifest.xml"+}+fn net_config(f: &FileInfo) -> bool {+ f.ext == "xml" && (f.name.contains("network_security") || f.name == "androidmanifest.xml")+}+fn android_code(f: &FileInfo) -> bool {+ f.ext_in(&["java", "kt"])+}+fn plist(f: &FileInfo) -> bool {+ f.ext == "plist"+}+fn app_code(f: &FileInfo) -> bool {+ f.ext_in(&["swift", "m", "dart", "js", "jsx", "ts", "tsx", "kt", "java"])+}++macro_rules! rule {+ ($id:literal, $sev:ident, $files:ident, $pat:literal, $unless:expr, $msg:literal, $fix:literal) => {+ Rule {+ id: $id,+ family: Family::Mobile,+ severity: Severity::$sev,+ files: $files,+ pattern: $pat,+ unless: $unless,+ message: $msg,+ fix: $fix,+ }+ };+}++pub static RULES: &[Rule] = &[+ rule!(+ "mobile.android-debuggable",+ High,+ manifest,+ r#"android:debuggable\s*=\s*"true""#,+ None,+ "The app is debuggable; anyone with the APK can attach a debugger and read its memory.",+ "Remove android:debuggable; the build system sets it for debug builds only."+ ),+ rule!(+ "mobile.android-allow-backup",+ Low,+ manifest,+ r#"android:allowBackup\s*=\s*"true""#,+ None,+ "App data can be copied off the device with adb backup.",+ "Set android:allowBackup=\"false\" or exclude sensitive files with backup rules."+ ),+ rule!(+ "mobile.android-cleartext",+ Medium,+ net_config,+ r#"android:usesCleartextTraffic\s*=\s*"true"|cleartextTrafficPermitted\s*=\s*"true""#,+ None,+ "Plain HTTP traffic is allowed, so data can be read or changed on the network.",+ "Use HTTPS everywhere; allow cleartext only for specific debug domains."+ ),+ rule!(+ "mobile.android-exported-provider",+ High,+ manifest,+ r#"<provider\b[^>]*android:exported\s*=\s*"true"[^>]*>"#,+ Some(r"android:(?:read|write)?[Pp]ermission"),+ "A content provider is exported with no permission, so any app on the device can read its data.",+ "Set android:exported=\"false\", or protect it with android:permission."+ ),+ rule!(+ "mobile.webview-js-bridge",+ Medium,+ android_code,+ r"\baddJavascriptInterface\s*\(",+ None,+ "Native methods are exposed to JavaScript in a WebView; any page it loads can call them.",+ "Load only trusted local content in that WebView, or remove the bridge."+ ),+ rule!(+ "mobile.webview-file-access",+ High,+ android_code,+ r"setAllow(?:Universal|File)AccessFromFileURLs\s*\(\s*true",+ None,+ "A WebView lets file:// pages read other files and origins.",+ "Leave these settings false (the default)."+ ),+ rule!(+ "mobile.world-readable",+ High,+ android_code,+ r"\bMODE_WORLD_(?:READABLE|WRITEABLE)\b",+ None,+ "A file or preferences store is readable or writable by every app on the device.",+ "Use MODE_PRIVATE, and a FileProvider to share specific files."+ ),+ rule!(+ "mobile.ios-ats-disabled",+ High,+ plist,+ r"<key>NSAllowsArbitraryLoads</key>\s*<true\s*/>",+ None,+ "App Transport Security is off, so the app may load anything over plain HTTP.",+ "Remove NSAllowsArbitraryLoads and add narrow exceptions per domain if needed."+ ),+ rule!(+ "mobile.insecure-storage",+ Medium,+ app_code,+ r#"UserDefaults[^\n]*\.set\([^\n]*forKey:\s*"[^"]*(?i:token|password|secret|jwt|session|pin)|(?i:prefs|preferences)\.set(?:String)?\(\s*['"][^'"]*(?i:token|password|secret|jwt|pin)|(?:AsyncStorage|localStorage|sessionStorage)\.setItem\(\s*['"][^'"]*(?i:token|password|secret|jwt|session)"#,+ None,+ "A token or password is saved in plain storage that other code, backups or XSS can read.",+ "Use the Keychain (iOS), EncryptedSharedPreferences/Keystore (Android), flutter_secure_storage, or an httpOnly cookie on the web."+ ),+];diff --git a/src/rules/secrets.rs b/src/rules/secrets.rsnew file mode 100644index 0000000..1c5a979--- /dev/null+++ b/src/rules/secrets.rs@@ -0,0 +1,115 @@+use super::{FileInfo, Rule};+use crate::{Family, Severity};++fn any_text(_: &FileInfo) -> bool {+ true+}++fn env_file(f: &FileInfo) -> bool {+ (f.name == ".env" || f.name.starts_with(".env."))+ && !["example", "sample", "template", "dist", "defaults"]+ .iter()+ .any(|s| f.name.ends_with(s))+}++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 {+ ($id:literal, $sev:ident, $pat:literal, $msg:literal) => {+ Rule {+ id: $id,+ family: Family::Secret,+ severity: Severity::$sev,+ files: any_text,+ pattern: $pat,+ unless: None,+ message: $msg,+ fix: ROTATE,+ }+ };+}++pub static RULES: &[Rule] = &[+ secret!(+ "secret.aws-access-key",+ Critical,+ r"\b(AKIA|ASIA)[0-9A-Z]{16}\b",+ "An AWS access key id is written in the file."+ ),+ secret!(+ "secret.github-token",+ Critical,+ r"\b(gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})",+ "A GitHub token is written in the file."+ ),+ secret!(+ "secret.slack-token",+ High,+ r"\bxox[baprs]-[A-Za-z0-9-]{10,}",+ "A Slack token is written in the file."+ ),+ secret!(+ "secret.stripe-live-key",+ Critical,+ r"\b[sr]k_live_[A-Za-z0-9]{24,}",+ "A live Stripe secret key is written in the file."+ ),+ secret!(+ "secret.anthropic-key",+ Critical,+ r"\bsk-ant-[A-Za-z0-9_\-]{32,}",+ "An Anthropic API key is written in the file."+ ),+ secret!(+ "secret.openai-key",+ Critical,+ r"\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_\-]{32,}|\bsk-[A-Za-z0-9]{48}\b",+ "An OpenAI API key is written in the file."+ ),+ secret!(+ "secret.google-api-key",+ High,+ r"\bAIza[0-9A-Za-z_\-]{35}",+ "A Google API key is written in the file."+ ),+ secret!(+ "secret.private-key",+ Critical,+ r"-----BEGIN ((RSA|EC|DSA|OPENSSH|PGP|ENCRYPTED) )?PRIVATE KEY( BLOCK)?-----\r?\n[A-Za-z0-9+/=]{20,}",+ "A private key is stored in the repository."+ ),+ Rule {+ id: "secret.hardcoded-password",+ family: Family::Secret,+ severity: Severity::High,+ files: any_text,+ pattern: r#"(?i)\b(password|passwd|pwd|secret|api_?key|access_?token|auth_?token|client_?secret)\b["']?\s*[:=]\s*["']([^"'\s]{8,})["']"#,+ unless: Some(+ r#"(?i)[:=]\s*["'][^"']*(?:\.\.\.|…)|[:=]\s*["'](\$|changeme|password|secret|example|x{3,}|your[-_]|<|\$\{|\{\{|%\(|dummy|test|placeholder|redacted|\*{3,}|none|null)"#,+ ),+ message: "A password or secret is written in the code.",+ fix: ROTATE,+ },+ Rule {+ id: "secret.url-credentials",+ family: Family::Secret,+ severity: Severity::High,+ files: any_text,+ pattern: r#"\b[a-z][a-z0-9+.\-]*://[^\s:/@"'`]+:[^\s@/"'`$]{4,}@[^\s"'`]+"#,+ unless: Some(+ r"(?i)localhost|127\.0\.0\.1|0\.0\.0\.0|example\.(com|org)|:password@|:pass@|\$\{|\buser(?:name)?:(?:token|pass(?:word)?|secret|pat)@|:\*+@",+ ),+ message: "A connection string carries a username and password.",+ fix: ROTATE,+ },+ Rule {+ id: "secret.env-file",+ family: Family::Secret,+ severity: Severity::Medium,+ files: env_file,+ pattern: r"\A(?:.*\n)*?[A-Za-z_][A-Za-z0-9_]*=\S",+ unless: None,+ message: "A .env file with values is in the repository; these usually hold real secrets.",+ fix: "Remove the file from git (keep a .env.example without values) and add .env to .gitignore.",+ },+];