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
fix(agent): report tokens in the headers of a remote MCP server (#78)
Onur Ugur7b1bfe99380d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 01a2bca..21110eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,11 @@## Unreleased+- Agent: `agent.mcp-plaintext-secret` also checks the `headers` and `http_headers` of remote MCP servers+ in JSON configs. `Authorization` and `Proxy-Authorization` always count. In `env` and headers alike, a+ value is judged after its auth scheme and with its variables taken out: `Bearer ${API_TOKEN}` and+ `user:${PASSWORD}` are skipped, `admin:<password>@${DB_HOST}` and `${TOKEN:-sk_live_...}` are+ reported.- Agent: `agent.unrestricted-shell` now reads `permissions.allow` in `.claude/settings*.json` instead of matching `"Bash"` anywhere in the file, so entries in `deny`, `ask`, or hook matchers are no longer flagged.- Secrets: `secret.env-not-ignored` is reported at the `.env` file when the project has no `.gitignore`at all. Example files like `.env.example` alone no longer trigger it.diff --git a/docs/agent-setups.md b/docs/agent-setups.mdindex 05f33da..5f53e54 100644--- a/docs/agent-setups.md+++ b/docs/agent-setups.md@@ -22,7 +22,7 @@ decide what they may do are code, and safe-anything checks them like code.| `agent.bypass-permissions` | `"defaultMode": "bypassPermissions"`, `--dangerously-skip-permissions`, `sandbox_mode = "danger-full-access"` | one bad instruction can do anything on the machine || `agent.unrestricted-shell` | `"allow": ["Bash"]` | every shell command is pre-approved || `agent.mcp-unpinned` | `"command": "npx", "args": ["-y", "some-mcp-server"]` | every start runs whatever was published last; a hijacked package runs with your access |-| `agent.mcp-plaintext-secret` | `"env": { "GITHUB_TOKEN": "ghp_..." }` | the token travels with the file |+| `agent.mcp-plaintext-secret` | `"env": { "GITHUB_TOKEN": "ghp_..." }`, `"headers": { "Authorization": "Bearer sk-..." }` | the token travels with the file; `"Bearer ${API_TOKEN}"` keeps it out || `agent.mcp-insecure-url` | `"url": "http://mcp.example.net/sse"` | tool calls and results cross the network in clear text || `agent.remote-script` | a hook or skill that runs `curl ... \| sh` | whoever controls the URL controls the machine || `agent.prompt-injection` | "ignore all previous instructions", "do not tell the user" | text that turns the agent against its user |diff --git a/src/rules/agent.rs b/src/rules/agent.rsindex dda8b58..c9f3b46 100644--- a/src/rules/agent.rs+++ b/src/rules/agent.rs@@ -1,3 +1,5 @@+use std::collections::HashMap;+use serde_json::Value;use super::{FileInfo, Meta, Rule, Text, finding};@@ -139,8 +141,17 @@ pub fn structured(file: &FileInfo, text: &Text) -> Vec<Finding> {let Some(servers) = json.get(key).and_then(Value::as_object) else {continue;};+ let positions = root_object(text.src)+ .and_then(|root| object_keys(text.src, root).get(key).copied())+ .and_then(|at| value_object(text.src, at))+ .map(|at| object_keys(text.src, at))+ .unwrap_or_default();for (name, server) in servers {- let start = text.src.find(&format!("\"{name}\"")).unwrap_or(0);+ let start = positions+ .get(name.as_str())+ .copied()+ .or_else(|| text.src.find(&format!("\"{name}\"")))+ .unwrap_or(0);check_server(file, text, start, server, &mut out);}}@@ -234,19 +245,45 @@ fn check_server(},));}- for env_key in ["env", "environment"] {- let Some(env) = server.get(env_key).and_then(Value::as_object) else {+ // Local servers get credentials in `env`; remote ones in `headers` (`http_headers` is Codex's+ // name for it).+ for (field, header) in [+ ("env", false),+ ("environment", false),+ ("headers", true),+ ("http_headers", true),+ ] {+ let Some(values) = server.get(field).and_then(Value::as_object) else {continue;};- for (k, v) in env {+ // Find each key inside its own object, so the same name in `args`, in `env` or as a value+ // does not take its line.+ let field_keys = value_object(text.src, start)+ .and_then(|at| object_keys(text.src, at).get(field).copied())+ .and_then(|at| value_object(text.src, at))+ .map(|at| object_keys(text.src, at))+ .unwrap_or_default();+ for (k, v) in values {let Some(v) = v.as_str() else { continue };- if secret_like_key(k)- && v.len() >= 8- && !v.starts_with('$')- && !v.starts_with('<')- && !v.contains("{env:")- {- let line = line_after(text, start, &format!("\"{k}\""));+ // `Authorization` and `Proxy-Authorization` are credential words in `secret_like_key`.+ if secret_like_key(k) && !references_variable(v) {+ let line = field_keys.get(k.as_str()).map_or_else(+ || line_after(text, start, &format!("\"{k}\"")),+ |&at| text.line_of(at),+ );+ let (message, fix) = if header {+ (+ format!(+ "The MCP server's {k} header is written in plain text in the config."+ ),+ "Reference an environment variable (\"${VAR}\", or \"Bearer ${VAR}\" for Authorization) and keep the value out of files that get shared or committed.",+ )+ } else {+ (+ format!("The MCP server's {k} is written in plain text in the config."),+ "Reference an environment variable (\"${VAR}\") and keep the value out of files that get shared or committed.",+ )+ };out.push(finding(file,text,@@ -255,8 +292,8 @@ fn check_server(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.",+ message: &message,+ fix,secret: Some(v),},));@@ -289,6 +326,88 @@ fn check_server(}}+/// Whether a value points at a credential kept elsewhere instead of holding one. After the auth+/// scheme (`Bearer`, `Basic`, ...): it starts with `$` or `<`, or what is left once every+/// `${VAR}` and `{env:VAR}` is taken out is shorter than 8 characters. So `Bearer ${TOKEN}`,+/// `user:${PASSWORD}` and `<your token>` are skipped, and `admin:hunter2hunter2@${DB_HOST}` and+/// `${TOKEN:-sk_live_default}` (a real default) are not.+fn references_variable(value: &str) -> bool {+ const SCHEMES: &[&str] = &[+ "bearer", "basic", "token", "bot", "digest", "apikey", "oauth",+ ];+ let bare = value+ .split_once(char::is_whitespace)+ .filter(|(scheme, _)| SCHEMES.iter().any(|s| scheme.eq_ignore_ascii_case(s)))+ .map_or(value, |(_, rest)| rest.trim_start());+ // A value that starts with a variable is taken from the environment (`$TOKEN`,+ // `${HOME}/key.json`), unless its default is a value of its own (`${TOKEN:-sk_live_...}`).+ let has_default = bare+ .strip_prefix("${")+ .and_then(|r| r.split_once('}'))+ .and_then(|(inner, _)| inner.split_once(":-"))+ .is_some_and(|(_, default)| !references_variable(default));+ if bare.starts_with('<') || value.starts_with('<') || (bare.starts_with('$') && !has_default) {+ return true;+ }+ without_variables(bare).len() < 8+}++/// The value with each `${VAR}`, `${env:VAR}`, `${input:VAR}` and `{env:VAR}` taken out. A+/// `${VAR:-default}` leaves its default, which may be a real value.+fn without_variables(value: &str) -> String {+ let mut out = String::with_capacity(value.len());+ let mut rest = value;+ while let Some(i) = rest.find(['$', '{']) {+ out.push_str(&rest[..i]);+ let after = &rest[i..];+ let inner = after+ .strip_prefix("${")+ .or_else(|| after.strip_prefix("{env:"))+ .and_then(|r| r.find('}').map(|end| (&r[..end], &r[end + 1..])));+ match inner {+ Some((inner, tail)) => {+ let (name, default) = inner.split_once(":-").unwrap_or((inner, ""));+ if is_variable_name(name) {+ out.push_str(default);+ } else {+ out.push_str(&after[..after.len() - tail.len()]);+ }+ rest = tail;+ }+ // No `}` follows, so no later `${` closes either: keep the rest as it is. This also+ // keeps the scan linear on a value full of unclosed `${`.+ None if after.starts_with("${") || after.starts_with("{env:") => {+ rest = after;+ break;+ }+ None => {+ out.push_str(&after[..1]);+ rest = &after[1..];+ }+ }+ }+ out.push_str(rest);+ out+}++/// `API_TOKEN`, or `env:API_TOKEN` / `input:api-token` (VS Code ids may hold `-` and `.`). A plain+/// name is a shell name, so `${TOKEN-realvalue}` is not taken for one.+fn is_variable_name(name: &str) -> bool {+ let (name, extra): (&str, &[char]) = match name+ .strip_prefix("env:")+ .or_else(|| name.strip_prefix("input:"))+ {+ Some(id) => (id, &['_', '-', '.']),+ None => (name, &['_']),+ };+ name.chars()+ .next()+ .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')+ && name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || extra.contains(&c))+}+/// Whether an env key names a credential. Each part of the key (split at every character that/// is not a letter or digit) is searched for the credential words, as before, except where the/// word only shows up as part of an ordinary one: a part that starts with `monkey`, `keyboard`@@ -459,6 +578,88 @@ fn npm_pinned(pkg: &str) -> bool {}}+/// The offset of each key of the object whose `{` is at `open` (the first one if a key repeats),+/// skipping nested values, strings and comments. One pass, so looking up every server or every+/// key of a large object stays linear.+fn object_keys(src: &str, open: usize) -> HashMap<&str, usize> {+ let b = src.as_bytes();+ let mut keys = HashMap::new();+ let mut i = open + 1;+ let mut depth = 1usize;+ while i < b.len() {+ match b[i] {+ b'"' => {+ let Some(end) = string_end(b, i) else { break };+ if depth == 1 && b[skip_blank(b, end + 1)..].first() == Some(&b':') {+ keys.entry(&src[i + 1..end]).or_insert(i);+ }+ i = end;+ }+ b'/' if b.get(i + 1) == Some(&b'/') => {+ i = src[i..].find('\n').map_or(b.len(), |n| i + n);+ }+ b'/' if b.get(i + 1) == Some(&b'*') => {+ i = src[i + 2..].find("*/").map_or(b.len(), |n| i + 3 + n);+ }+ b'{' | b'[' => depth += 1,+ b'}' | b']' => {+ depth -= 1;+ if depth == 0 {+ break;+ }+ }+ _ => {}+ }+ i += 1;+ }+ keys+}++/// The offset of the `{` that opens the file's top-level object, after any blank space and+/// comments.+fn root_object(src: &str) -> Option<usize> {+ let b = src.as_bytes();+ let mut i = 0;+ loop {+ i = skip_blank(b, i);+ if b[i..].starts_with(b"//") {+ i = src[i..].find('\n').map_or(b.len(), |n| i + n);+ } else if b[i..].starts_with(b"/*") {+ i = src[i + 2..].find("*/").map_or(b.len(), |n| i + 4 + n);+ } else {+ return (b.get(i) == Some(&b'{')).then_some(i);+ }+ }+}++/// The offset of the `{` that starts the value of the key at `key_at`, if it is an object.+fn value_object(src: &str, key_at: usize) -> Option<usize> {+ let b = src.as_bytes();+ let colon = skip_blank(b, string_end(b, key_at)? + 1);+ (b.get(colon) == Some(&b':')).then_some(())?;+ let open = skip_blank(b, colon + 1);+ (b.get(open) == Some(&b'{')).then_some(open)+}++fn string_end(b: &[u8], open: usize) -> Option<usize> {+ let mut i = open + 1;+ while i < b.len() {+ match b[i] {+ b'\\' => i += 2,+ b'"' => return Some(i),+ _ => i += 1,+ }+ }+ None+}++fn skip_blank(b: &[u8], mut i: usize) -> usize {+ while i < b.len() && b[i].is_ascii_whitespace() {+ i += 1;+ }+ i+}+fn line_after(text: &Text, start: usize, needle: &str) -> usize {let at = text.src[start..].find(needle)diff --git a/tests/fixtures/agent/.mcp.json b/tests/fixtures/agent/.mcp.jsonindex 59f77c3..cbd8634 100644--- a/tests/fixtures/agent/.mcp.json+++ b/tests/fixtures/agent/.mcp.json@@ -52,6 +52,39 @@"daemonKey": "EXAMPLE_NOT_A_REAL_KEY_VALUE","GITHUBPATVALUE": "EXAMPLE_NOT_A_REAL_PAT_VALUE"}+ },+ "remote-token": {+ "type": "http",+ "url": "https://mcp.acme-tools.io/mcp",+ "args": ["--dump", "headers"],+ "env": { "X-API-Key": "${API_KEY}", "DB_PASSWORD": "correct horse battery staple" },+ "headers": {+ "Authorization": "Bearer EXAMPLEnotarealtoken0123456789abcdef",+ "X-API-Key": "EXAMPLEnotarealkey0123456789abcdef",+ "X-Request-Source": "acme-desktop-client"+ }+ },+ "remote-codex": {+ "url": "https://mcp.acme-tools.io/mcp",+ "http_headers": { "proxy-authorization": "Basic EXAMPLEnotarealbasic0123456789" }+ },+ "remote-env": {+ "type": "sse",+ "url": "https://mcp.acme-tools.io/sse",+ "env": {+ "DB_URL_PASSWORD": "admin:EXAMPLEnotreal@${DB_HOST}",+ "ACME_TOKEN": "${ACME_TOKEN:-EXAMPLEnotarealdefault}",+ "GOOGLE_APPLICATION_CREDENTIALS": "${HOME}/keys/service-account.json",+ "INFLUX_KEY_FILE": "${INFLUX_KEY_FILE:-$HOME/.influx/api-key}"+ },+ "headers": {+ "Authorization": "Bearer ${API_TOKEN}",+ "X-API-Key": "${env:API_KEY}",+ "X-Auth-Token": "{env:AUTH_TOKEN}",+ "Proxy-Authorization": "Basic <base64 user:password>",+ "X-Api-Token": "ApiKey ${ACME_KEY}",+ "X-Acme-Key": "<your acme key here>"+ }}}}diff --git a/tests/fixtures/agent/EXPECTED b/tests/fixtures/agent/EXPECTEDindex 505a328..5eb106e 100644--- a/tests/fixtures/agent/EXPECTED+++ b/tests/fixtures/agent/EXPECTED@@ -23,6 +23,12 @@.mcp.json:51 agent.mcp-plaintext-secret.mcp.json:52 agent.mcp-plaintext-secret.mcp.json:53 agent.mcp-plaintext-secret+.mcp.json:60 agent.mcp-plaintext-secret+.mcp.json:62 agent.mcp-plaintext-secret+.mcp.json:63 agent.mcp-plaintext-secret+.mcp.json:69 agent.mcp-plaintext-secret+.mcp.json:75 agent.mcp-plaintext-secret+.mcp.json:76 agent.mcp-plaintext-secret.mcp.json:5 agent.mcp-unpinned.mcp.json:7 agent.mcp-plaintext-secret.mcp.json:7 secret.github-token