File size: 9,560 Bytes
1269259 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | // SPF Smart Gateway - Content Inspection
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Inspects content being written/edited/executed for:
// - Credential patterns (API keys, tokens, private keys)
// - Path traversal attempts (../ sequences)
// - Shell injection in written content (backticks, $(), eval)
// - References to paths outside allowed boundaries
//
// FIX: "eval " now uses line-start detection to avoid false positives
// on documentation content containing words like "evaluate", "evaluation".
// Shell eval commands always start a statement — docs mention eval mid-sentence.
use crate::config::{EnforceMode, SpfConfig};
use crate::validate::ValidationResult;
/// Credential patterns to detect
const CREDENTIAL_PATTERNS: &[(&str, &str)] = &[
("sk-", "Possible API secret key"),
("AKIA", "Possible AWS access key"),
("ghp_", "Possible GitHub personal access token"),
("gho_", "Possible GitHub OAuth token"),
("ghs_", "Possible GitHub server token"),
("github_pat_", "Possible GitHub PAT"),
("glpat-", "Possible GitLab PAT"),
("xoxb-", "Possible Slack bot token"),
("xoxp-", "Possible Slack user token"),
("-----BEGIN RSA PRIVATE KEY", "RSA private key detected"),
("-----BEGIN OPENSSH PRIVATE KEY", "SSH private key detected"),
("-----BEGIN EC PRIVATE KEY", "EC private key detected"),
("-----BEGIN PRIVATE KEY", "Private key detected"),
("password=", "Possible hardcoded password"),
("passwd=", "Possible hardcoded password"),
("secret=", "Possible hardcoded secret"),
("api_key=", "Possible hardcoded API key"),
("apikey=", "Possible hardcoded API key"),
("access_token=", "Possible hardcoded access token"),
];
/// Shell injection patterns in written content
const SHELL_INJECTION_PATTERNS: &[(&str, &str)] = &[
("$(", "Command substitution in content"),
("eval ", "Eval statement in content"),
("exec ", "Exec statement in content"),
("`", "Backtick command substitution in content"),
];
/// Inspect content being written or edited
pub fn inspect_content(
content: &str,
file_path: &str,
config: &SpfConfig,
) -> ValidationResult {
let mut result = ValidationResult::ok();
// Skip injection checks for shell scripts and code/config/doc files
// where these patterns are expected or contextually normal.
if file_path.ends_with(".sh") || file_path.ends_with(".bash")
|| file_path.ends_with(".zsh") || file_path.ends_with(".rs")
|| file_path.ends_with(".py") || file_path.ends_with(".js")
|| file_path.ends_with(".ts") || file_path.ends_with(".toml")
|| file_path.ends_with(".json") || file_path.ends_with(".md")
{
// For code files, only check credentials — shell patterns are normal
check_credentials(content, config, &mut result);
check_path_traversal(content, config, &mut result);
check_blocked_path_references(content, config, &mut result);
return result;
}
// Full inspection for non-code files
check_credentials(content, config, &mut result);
check_path_traversal(content, config, &mut result);
check_shell_injection(content, config, &mut result);
check_blocked_path_references(content, config, &mut result);
result
}
/// Check for credential patterns
fn check_credentials(
content: &str,
config: &SpfConfig,
result: &mut ValidationResult,
) {
for (pattern, description) in CREDENTIAL_PATTERNS {
if content.contains(pattern) {
match config.enforce_mode {
EnforceMode::Max => {
result.warn(format!("MAX TIER: CREDENTIAL DETECTED — {}", description));
}
EnforceMode::Soft => {
result.warn(format!("Credential warning: {}", description));
}
}
}
}
}
/// Check for path traversal attempts
fn check_path_traversal(
content: &str,
config: &SpfConfig,
result: &mut ValidationResult,
) {
if content.contains("../") || content.contains("..\\") {
match config.enforce_mode {
EnforceMode::Max => {
result.warn("MAX TIER: PATH TRAVERSAL — content contains ../ sequences".to_string());
}
EnforceMode::Soft => {
result.warn("Path traversal pattern detected in content".to_string());
}
}
}
}
/// Check for shell injection patterns (non-code files only).
///
/// Special handling for "eval ":
/// Shell eval commands always begin a statement (start of line, after ; or &&).
/// Documentation mentioning eval appears mid-sentence — substring match causes
/// false positives on words like "evaluate" in STATUS.txt, notes, etc.
/// All other patterns use simple substring match (unchanged behaviour).
fn check_shell_injection(
content: &str,
config: &SpfConfig,
result: &mut ValidationResult,
) {
for (pattern, description) in SHELL_INJECTION_PATTERNS {
let found = if *pattern == "eval " {
// Require eval at start of a statement (line-start or after ; or &&)
content.lines().any(|line| {
let t = line.trim_start();
t.starts_with("eval ") || t.starts_with("eval\t")
})
} else {
content.contains(pattern)
};
if found {
match config.enforce_mode {
EnforceMode::Max => {
result.warn(format!("MAX TIER: SHELL INJECTION — {}", description));
}
EnforceMode::Soft => {
result.warn(format!("Shell pattern warning: {}", description));
}
}
}
}
}
/// Check for references to blocked paths in content
fn check_blocked_path_references(
content: &str,
config: &SpfConfig,
result: &mut ValidationResult,
) {
for blocked in &config.blocked_paths {
if content.contains(blocked.as_str()) {
result.warn(format!("Content references blocked path: {}", blocked));
}
}
}
// ============================================================================
// TESTS
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use crate::config::SpfConfig;
fn default_config() -> SpfConfig {
SpfConfig::default()
}
#[test]
fn detects_aws_access_key() {
let config = default_config();
let result = inspect_content("my key is AKIAIOSFODNN7EXAMPLE", "data.txt", &config);
assert!(!result.warnings.is_empty(), "Should detect AKIA pattern");
}
#[test]
fn detects_private_key() {
let config = default_config();
let result = inspect_content("-----BEGIN RSA PRIVATE KEY-----\nblah", "key.txt", &config);
assert!(!result.warnings.is_empty(), "Should detect RSA private key");
}
#[test]
fn detects_github_pat() {
let config = default_config();
let result = inspect_content("token: ghp_abc123def456ghi789", "notes.txt", &config);
assert!(!result.warnings.is_empty(), "Should detect GitHub PAT");
}
#[test]
fn detects_path_traversal() {
let config = default_config();
let result = inspect_content("read from ../../../etc/passwd", "data.txt", &config);
assert!(!result.warnings.is_empty(), "Should detect path traversal");
}
#[test]
fn detects_shell_injection_in_non_code() {
let config = default_config();
let result = inspect_content("run $(whoami) now", "data.txt", &config);
assert!(!result.warnings.is_empty(), "Should detect command substitution");
}
#[test]
fn detects_eval_at_line_start() {
let config = default_config();
// eval at line start = real shell injection
let result = inspect_content("eval $(get_secret)", "data.txt", &config);
assert!(!result.warnings.is_empty(), "eval at line start should be flagged");
}
#[test]
fn no_false_positive_evaluate_word() {
let config = default_config();
// "evaluate" mid-sentence in documentation — must NOT flag
let content = "We evaluate the result and check if the system is working correctly.";
let result = inspect_content(content, "STATUS.txt", &config);
let shell_warnings: Vec<_> = result.warnings.iter()
.filter(|w| w.contains("SHELL") || w.contains("Eval"))
.collect();
assert!(shell_warnings.is_empty(), "evaluate mid-sentence should NOT trigger: {:?}", shell_warnings);
}
#[test]
fn skips_shell_patterns_in_code_files() {
let config = default_config();
// Shell patterns are normal in .sh files — should NOT flag shell injection
let result = inspect_content("echo $(date)", "script.sh", &config);
let shell_warnings: Vec<_> = result.warnings.iter()
.filter(|w| w.contains("SHELL") || w.contains("Command substitution"))
.collect();
assert!(shell_warnings.is_empty(), "Should skip shell patterns in .sh files: {:?}", shell_warnings);
}
#[test]
fn clean_content_passes() {
let config = default_config();
let result = inspect_content("Hello, this is normal content.", "readme.txt", &config);
assert!(result.warnings.is_empty(), "Clean content should have no warnings: {:?}", result.warnings);
assert!(result.valid, "Clean content should be valid");
}
}
|