Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/tools/builtin/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,13 @@ impl Tool for ReadFileTool {

let path = validate_path(path_str, self.base_dir.as_deref())?;

if super::path_utils::is_sensitive_path(&path) {
return Err(ToolError::NotAuthorized(format!(
"Access denied: '{}' is a sensitive path. Use the appropriate secrets management tool instead.",
path_str
)));
}

// Check file size
let metadata = fs::metadata(&path)
.await
Expand Down Expand Up @@ -256,6 +263,13 @@ impl Tool for WriteFileTool {

let path = validate_path(path_str, self.base_dir.as_deref())?;

if super::path_utils::is_sensitive_path(&path) {
return Err(ToolError::NotAuthorized(format!(
"Access denied: '{}' is a sensitive path",
path_str
)));
}

// Create parent directories
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await.map_err(|e| {
Expand Down Expand Up @@ -364,6 +378,13 @@ impl Tool for ListDirTool {

let path = validate_path(path_str, self.base_dir.as_deref())?;

if super::path_utils::is_sensitive_path(&path) {
return Err(ToolError::NotAuthorized(format!(
"Access denied: '{}' is a sensitive directory",
path_str
)));
}

let mut entries = Vec::new();
list_dir_inner(&path, &path, recursive, max_depth, 0, &mut entries).await?;

Expand Down Expand Up @@ -447,6 +468,10 @@ async fn list_dir_inner(
entries.push(display);

if recursive && is_dir && current_depth < max_depth {
// Skip sensitive directories during recursive traversal
if super::path_utils::is_sensitive_path(&entry_path) {
continue;
}
// Skip common non-essential directories
let name = entry.file_name();
let name_str = name.to_string_lossy();
Expand Down Expand Up @@ -561,6 +586,13 @@ impl Tool for ApplyPatchTool {

let path = validate_path(path_str, self.base_dir.as_deref())?;

if super::path_utils::is_sensitive_path(&path) {
return Err(ToolError::NotAuthorized(format!(
"Access denied: '{}' is a sensitive path",
path_str
)));
}

// Read current content
let content = fs::read_to_string(&path)
.await
Expand Down
198 changes: 198 additions & 0 deletions src/tools/builtin/path_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,121 @@
//! attacks and ensure paths stay within allowed sandboxes.

use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use crate::tools::tool::ToolError;

/// Paths that contain credentials, secrets, or private keys.
/// Used by both file tools (exact path check) and shell tool (substring scan).
/// Keep sorted by category for readability.
static SENSITIVE_PATH_PATTERNS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
vec![
// SSH
"/.ssh/",
"/id_rsa",
"/id_ed25519",
"/id_ecdsa",
"/id_dsa",
"/authorized_keys",
"/known_hosts",
// GPG
"/.gnupg/",
// AWS
"/.aws/credentials",
"/.aws/config",
// Kubernetes
"/.kube/config",
// Cloud providers
"/.azure/",
"/.gcloud/",
"/.config/gcloud/",
// Terraform
"/.terraform.d/credentials.tfrc.json",
// GitHub CLI
"/.config/gh/hosts.yml",
// Docker
"/.docker/config.json",
// Vault
"/.vault-token",
// Shell history
"/.bash_history",
"/.zsh_history",
"/.histfile",
// Env files (may contain secrets)
"/.env",
// Git credentials
"/.git-credentials",
"/.netrc",
"/.pgpass",
// IronClaw's own secrets
"/.ironclaw/secrets/",
// System
"/etc/shadow",
"/etc/gshadow",
]
});

/// File extensions that are always sensitive regardless of location.
static SENSITIVE_EXTENSIONS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
vec![".pem", ".key", ".p12", ".pfx", ".jks", ".keystore"]
});

/// Suffixes that indicate a file is safe despite matching a sensitive pattern
/// (e.g., `.env.example`, `.env.sample`).
static SAFE_SUFFIXES: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
vec![".example", ".sample", ".template", ".dist", ".bak.example"]
});

/// Check if a resolved file path points to a sensitive location.
/// Used by file tools (read, write, list_dir, apply_patch).
pub fn is_sensitive_path(path: &Path) -> bool {
let path_str = match path.canonicalize() {
Ok(p) => p.to_string_lossy().to_string(),
Err(_) => path.to_string_lossy().to_string(),
Comment on lines +73 to +75

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Canonicalize parent path when target file does not yet exist

When canonicalization fails, is_sensitive_path falls back to the unresolved input path, which allows symlink aliases to hide sensitive destinations for new-file writes. For example, if /tmp/link is a symlink to ~/.ssh, writing /tmp/link/new_config is treated as non-sensitive (no /.ssh/ in the alias string) even though write_file will create the file inside ~/.ssh, leaving a bypass for protected directories.

Useful? React with 👍 / 👎.

};

// Safe suffixes override sensitive patterns
let lower = path_str.to_lowercase();
if SAFE_SUFFIXES.iter().any(|s| lower.ends_with(s)) {
return false;
}

// Check sensitive path patterns
if SENSITIVE_PATH_PATTERNS.iter().any(|p| path_str.contains(p)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Normalize separators before checking sensitive path patterns

is_sensitive_path does a raw contains match against slash-delimited patterns (e.g., /.ssh/, /.aws/credentials) without normalizing path separators. On Windows, Path::to_string_lossy() yields backslash paths, so sensitive targets like C:\Users\...\.ssh\id_rsa do not match and the file-level protection is bypassed; because the same pattern set is reused for shell scanning, backslash-based shell paths are similarly missed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HIGH (H3): Pattern check is case-sensitive but lower is already computed two lines above. On macOS (case-insensitive filesystem), if canonicalize() fails (file doesn't exist — relevant for WriteFileTool), the fallback uses the original input case. So write_file("/app/.SSH/id_rsa", ...) bypasses the check because "/.SSH/" doesn't match pattern "/.ssh/".

Fix: Change path_str.contains(p) to lower.contains(p) — the lower variable is already computed on line 79.

return true;
}

// Check sensitive file extensions
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
let dot_ext = format!(".{}", ext.to_lowercase());
if SENSITIVE_EXTENSIONS.iter().any(|e| *e == dot_ext) {
return true;
}
}

false
}

/// Scan a shell command string for references to sensitive paths.
/// Returns the first matched pattern, or None if the command is clean.
/// Used by the shell tool to block `cat ~/.ssh/id_rsa` etc.
pub fn command_references_sensitive_path(command: &str) -> Option<&'static str> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HIGH (H1): This function does pure substring matching with no safe-suffix exemption, unlike is_sensitive_path() which checks SAFE_SUFFIXES first. This means cat /app/.env.example is allowed by ReadFileTool but blocked by shell tool. Also blocks source /app/.envrc (direnv code, not secrets).

Fix: Apply SAFE_SUFFIXES exemption here too, or extract file-path tokens from the command and delegate to is_sensitive_path().

let normalized = command.to_lowercase();

for pattern in SENSITIVE_PATH_PATTERNS.iter() {
// For path patterns, check case-insensitively
if normalized.contains(&pattern.to_lowercase()) {
return Some(pattern);
}
Comment on lines +123 to +127

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The current implementation uses simple substring containment to detect sensitive paths, which leads to false positives (e.g., matching 'id_rsa' inside other words). Per repository security guidelines, please replace simple substring checks with token-based or word-boundary checks to improve precision and reduce false positives.

References
  1. When detecting commands or keywords in a string, use token-based or word-boundary checks instead of simple substring containment to avoid false positives.

}

// Check for sensitive extensions in file arguments
SENSITIVE_EXTENSIONS
.iter()
.find(|ext| normalized.contains(*ext))
.copied()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply safe-suffix exemptions in shell sensitive-path scan

command_references_sensitive_path checks sensitive patterns/extensions directly but never applies the SAFE_SUFFIXES allowlist that is_sensitive_path uses. This causes shell commands against template files (for example .env.example or .pem.template) to be blocked while file tools allow them, creating inconsistent behavior and breaking workflows the safe-suffix policy was added to preserve.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HIGH (H2): Extension matching via contains() on the full lowercased command string causes false positives. Examples: cat config.keys, cat .keychain, grep pattern file.keynote, cat /tmp/my.keyboard.cfg all match .key. Similarly cat /tmp/template.pemx matches .pem.

Fix: Split the command into whitespace-delimited tokens and check file extensions on each token individually, or use a regex like \.key(?:\s|$).

}

/// Normalize a path by resolving `.` and `..` components lexically (no filesystem access).
///
/// This is critical for security: `std::fs::canonicalize` only works on paths that exist,
Expand Down Expand Up @@ -236,4 +348,90 @@ mod tests {
let result = validate_path("a/b/../c.txt", Some(dir.path()));
assert!(result.is_ok());
}

// ── sensitive path tests ──

#[test]
fn test_is_sensitive_path_blocks_ssh() {
assert!(is_sensitive_path(Path::new("/home/user/.ssh/id_rsa")));
assert!(is_sensitive_path(Path::new("/home/user/.ssh/authorized_keys")));
assert!(is_sensitive_path(Path::new("/root/.ssh/config")));
}

#[test]
fn test_is_sensitive_path_blocks_cloud_credentials() {
assert!(is_sensitive_path(Path::new("/home/user/.aws/credentials")));
assert!(is_sensitive_path(Path::new("/home/user/.kube/config")));
assert!(is_sensitive_path(Path::new("/home/user/.azure/some_token")));
assert!(is_sensitive_path(Path::new(
"/home/user/.config/gh/hosts.yml"
)));
}

#[test]
fn test_is_sensitive_path_blocks_system_secrets() {
assert!(is_sensitive_path(Path::new("/etc/shadow")));
assert!(is_sensitive_path(Path::new("/etc/gshadow")));
}

#[test]
fn test_is_sensitive_path_blocks_key_files_by_extension() {
assert!(is_sensitive_path(Path::new("/tmp/server.pem")));
assert!(is_sensitive_path(Path::new("/app/certs/private.key")));
assert!(is_sensitive_path(Path::new("/home/user/keystore.p12")));
}

#[test]
fn test_is_sensitive_path_allows_safe_suffixes() {
assert!(!is_sensitive_path(Path::new("/app/.env.example")));
assert!(!is_sensitive_path(Path::new("/app/.env.sample")));
assert!(!is_sensitive_path(Path::new("/app/.env.template")));
}

#[test]
fn test_is_sensitive_path_allows_normal_files() {
assert!(!is_sensitive_path(Path::new("/app/src/main.rs")));
assert!(!is_sensitive_path(Path::new("/home/user/README.md")));
assert!(!is_sensitive_path(Path::new("/tmp/output.json")));
}

#[test]
fn test_is_sensitive_path_blocks_env_files() {
assert!(is_sensitive_path(Path::new("/app/.env")));
assert!(is_sensitive_path(Path::new("/app/.env.local")));
assert!(is_sensitive_path(Path::new("/app/.env.production")));
}

// ── command scanning tests ──

#[test]
fn test_command_references_sensitive_path_catches_cat_ssh() {
assert!(command_references_sensitive_path("cat ~/.ssh/id_rsa").is_some());
assert!(command_references_sensitive_path("head -n 5 /home/user/.ssh/authorized_keys").is_some());
}

#[test]
fn test_command_references_sensitive_path_catches_aws() {
assert!(command_references_sensitive_path("cat ~/.aws/credentials").is_some());
assert!(command_references_sensitive_path("grep key ~/.aws/config").is_some());
}

#[test]
fn test_command_references_sensitive_path_catches_etc_shadow() {
assert!(command_references_sensitive_path("cat /etc/shadow").is_some());
}

#[test]
fn test_command_references_sensitive_path_catches_key_extensions() {
assert!(command_references_sensitive_path("cp server.pem /tmp/").is_some());
assert!(command_references_sensitive_path("cat private.key").is_some());
}

#[test]
fn test_command_references_sensitive_path_allows_safe_commands() {
assert!(command_references_sensitive_path("ls -la").is_none());
assert!(command_references_sensitive_path("cargo build").is_none());
assert!(command_references_sensitive_path("git status").is_none());
assert!(command_references_sensitive_path("cat README.md").is_none());
}
}
13 changes: 8 additions & 5 deletions src/tools/builtin/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ static BLOCKED_COMMANDS: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
});

/// Patterns that indicate potentially dangerous commands.
/// Note: sensitive file paths (/.ssh/, /etc/shadow, etc.) are now handled by
/// `command_references_sensitive_path` in path_utils.rs for consistency with
/// file tool protections. This list covers command-level dangers only.
static DANGEROUS_PATTERNS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
vec![
"sudo ",
Expand All @@ -93,11 +96,6 @@ static DANGEROUS_PATTERNS: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
"eval ",
"$(curl",
"$(wget",
"/etc/passwd",
"/etc/shadow",
"~/.ssh",
".bash_history",
"id_rsa",
]
});

Expand Down Expand Up @@ -622,6 +620,11 @@ impl ShellTool {
}
}

// Block commands that reference sensitive file paths (shared with file tools)
if super::path_utils::command_references_sensitive_path(cmd).is_some() {
return Some("Command references sensitive file path");
}

None
}

Expand Down
Loading