Coverage for /Users/les/Projects/crackerjack/crackerjack/services/secure_subprocess.py: 0%
150 statements
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
« prev ^ index » next coverage.py v7.10.6, created at 2025-09-03 15:39 -0700
1"""
2Secure subprocess execution with environment sanitization and command validation.
4This module provides production-ready security for all subprocess operations in Crackerjack,
5implementing comprehensive validation, sanitization, and logging to prevent injection attacks.
6"""
8import os
9import re
10import subprocess
11import time
12import typing as t
13from pathlib import Path
15from .security_logger import SecurityEventLevel, SecurityEventType, get_security_logger
18class SecurityError(Exception):
19 """Raised when a security violation is detected."""
21 pass
24class CommandValidationError(SecurityError):
25 """Raised when command validation fails."""
27 pass
30class EnvironmentValidationError(SecurityError):
31 """Raised when environment validation fails."""
33 pass
36class SubprocessSecurityConfig:
37 """Configuration for secure subprocess execution."""
39 def __init__(
40 self,
41 max_command_length: int = 10000,
42 max_arg_length: int = 4096,
43 max_env_var_length: int = 32768,
44 max_env_vars: int = 1000,
45 allowed_executables: set[str] | None = None,
46 blocked_executables: set[str] | None = None,
47 max_timeout: float = 3600, # 1 hour max
48 enable_path_validation: bool = True,
49 enable_command_logging: bool = True,
50 ):
51 self.max_command_length = max_command_length
52 self.max_arg_length = max_arg_length
53 self.max_env_var_length = max_env_var_length
54 self.max_env_vars = max_env_vars
55 self.allowed_executables = allowed_executables or set()
56 self.blocked_executables = blocked_executables or {
57 "rm",
58 "rmdir",
59 "del",
60 "format",
61 "fdisk",
62 "mkfs",
63 "dd",
64 "shred",
65 "wipe",
66 "nc",
67 "netcat",
68 "telnet",
69 "ftp",
70 "tftp",
71 "curl",
72 "wget",
73 "ssh",
74 "scp",
75 "rsync",
76 "sudo",
77 "su",
78 "doas",
79 "eval",
80 "exec",
81 "source",
82 ".",
83 "bash",
84 "sh",
85 "zsh",
86 "fish",
87 "csh",
88 }
89 self.max_timeout = max_timeout
90 self.enable_path_validation = enable_path_validation
91 self.enable_command_logging = enable_command_logging
94class SecureSubprocessExecutor:
95 """Secure subprocess executor with comprehensive validation and logging."""
97 def __init__(self, config: SubprocessSecurityConfig | None = None):
98 self.config = config or SubprocessSecurityConfig()
99 self.security_logger = get_security_logger()
101 # Dangerous patterns for command injection detection
102 self.dangerous_patterns = [
103 r"[;&|`$(){}[\]<>*?~]", # Shell metacharacters
104 r"\.\./", # Path traversal
105 r"\$\{.*\}", # Variable expansion
106 r"`.*`", # Command substitution
107 r"\$\(.*\)", # Command substitution
108 r">\s*/", # Redirect to system paths
109 r"<\s*/", # Redirect from system paths
110 ]
112 # Environment variables that should never be passed through
113 self.dangerous_env_vars = {
114 "LD_PRELOAD",
115 "DYLD_INSERT_LIBRARIES",
116 "DYLD_LIBRARY_PATH",
117 "LD_LIBRARY_PATH",
118 "PYTHONPATH",
119 "PATH",
120 "IFS",
121 "PS4",
122 "BASH_ENV",
123 "ENV",
124 "SHELLOPTS",
125 "BASHOPTS",
126 }
128 # Minimal safe environment variables
129 self.safe_env_vars = {
130 "HOME",
131 "USER",
132 "USERNAME",
133 "LOGNAME",
134 "LANG",
135 "LC_ALL",
136 "LC_CTYPE",
137 "TERM",
138 "TMPDIR",
139 "TMP",
140 "TEMP",
141 }
143 def execute_secure(
144 self,
145 command: list[str],
146 cwd: Path | str | None = None,
147 env: dict[str, str] | None = None,
148 timeout: float | None = None,
149 input_data: str | bytes | None = None,
150 capture_output: bool = True,
151 text: bool = True,
152 check: bool = False,
153 **kwargs: t.Any,
154 ) -> subprocess.CompletedProcess[str]:
155 """
156 Execute a subprocess with comprehensive security validation.
158 Args:
159 command: Command and arguments as list
160 cwd: Working directory (validated for path traversal)
161 env: Environment variables (will be sanitized)
162 timeout: Maximum execution time
163 input_data: Input to pass to subprocess
164 capture_output: Whether to capture stdout/stderr
165 text: Whether to use text mode
166 check: Whether to raise on non-zero exit
167 **kwargs: Additional subprocess.run arguments
169 Returns:
170 CompletedProcess result
172 Raises:
173 SecurityError: If security validation fails
174 CommandValidationError: If command validation fails
175 EnvironmentValidationError: If environment validation fails
176 """
177 start_time = time.time()
179 try:
180 # Validate and sanitize all inputs
181 validated_command = self._validate_command(command)
182 validated_cwd = self._validate_cwd(cwd)
183 sanitized_env = self._sanitize_environment(env)
184 validated_timeout = self._validate_timeout(timeout)
186 # Log the execution attempt
187 if self.config.enable_command_logging:
188 self.security_logger.log_subprocess_execution(
189 command=validated_command,
190 cwd=str(validated_cwd) if validated_cwd else None,
191 env_vars_count=len(sanitized_env),
192 timeout=validated_timeout,
193 )
195 # Execute the subprocess
196 result = subprocess.run(
197 validated_command,
198 cwd=validated_cwd,
199 env=sanitized_env,
200 timeout=validated_timeout,
201 input=input_data,
202 capture_output=capture_output,
203 text=text,
204 check=check,
205 **kwargs,
206 )
208 # Log success
209 execution_time = time.time() - start_time
210 if self.config.enable_command_logging:
211 self.security_logger.log_security_event(
212 SecurityEventType.SUBPROCESS_EXECUTION,
213 SecurityEventLevel.LOW,
214 f"Subprocess completed successfully in {execution_time:.2f}s",
215 command_preview=validated_command[:3],
216 execution_time=execution_time,
217 exit_code=result.returncode,
218 )
220 return result
222 except subprocess.TimeoutExpired:
223 execution_time = time.time() - start_time
224 self.security_logger.log_subprocess_timeout(
225 command=command,
226 timeout_seconds=validated_timeout or self.config.max_timeout,
227 actual_duration=execution_time,
228 )
229 raise
231 except subprocess.CalledProcessError as e:
232 self.security_logger.log_subprocess_failure(
233 command=command,
234 exit_code=e.returncode,
235 error_output=str(e.stderr)[:200] if e.stderr else "",
236 )
237 raise
239 except Exception as e:
240 self.security_logger.log_security_event(
241 SecurityEventType.SUBPROCESS_FAILURE,
242 SecurityEventLevel.HIGH,
243 f"Unexpected subprocess error: {str(e)[:200]}",
244 command_preview=command[:3] if command else [],
245 error_type=type(e).__name__,
246 error_message=str(e)[:200],
247 )
248 raise
250 def _validate_command(self, command: list[str]) -> list[str]:
251 """Validate command arguments for security issues."""
252 if not command:
253 raise CommandValidationError("Command cannot be empty")
255 if not isinstance(command, list):
256 raise CommandValidationError("Command must be a list of strings")
258 # Check overall command length
259 total_length = sum(len(arg) for arg in command)
260 if total_length > self.config.max_command_length:
261 raise CommandValidationError(
262 f"Command too long: {total_length} > {self.config.max_command_length}"
263 )
265 validated_command = []
266 issues = []
268 for i, arg in enumerate(command):
269 if not isinstance(arg, str):
270 raise CommandValidationError(
271 f"Command argument {i} must be string, got {type(arg)}"
272 )
274 # Check argument length
275 if len(arg) > self.config.max_arg_length:
276 issues.append(
277 f"Argument {i} too long: {len(arg)} > {self.config.max_arg_length}"
278 )
279 continue
281 # Check for injection patterns
282 for pattern in self.dangerous_patterns:
283 if re.search(pattern, arg):
284 issues.append(
285 f"Dangerous pattern '{pattern}' in argument {i}: {arg[:50]}"
286 )
287 continue
289 validated_command.append(arg)
291 # Check executable allowlist/blocklist
292 if validated_command:
293 executable = Path(validated_command[0]).name
295 if (
296 self.config.allowed_executables
297 and executable not in self.config.allowed_executables
298 ):
299 issues.append(f"Executable '{executable}' not in allowlist")
301 if executable in self.config.blocked_executables:
302 issues.append(f"Executable '{executable}' is blocked")
304 # Log validation results
305 validation_passed = len(issues) == 0
306 if self.config.enable_command_logging:
307 self.security_logger.log_subprocess_command_validation(
308 command=command,
309 validation_result=validation_passed,
310 issues=issues,
311 )
313 if issues:
314 # Block dangerous commands
315 self.security_logger.log_dangerous_command_blocked(
316 command=command,
317 reason="Command validation failed",
318 dangerous_patterns=issues,
319 )
320 raise CommandValidationError(
321 f"Command validation failed: {'; '.join(issues)}"
322 )
324 return validated_command
326 def _validate_cwd(self, cwd: Path | str | None) -> Path | None:
327 """Validate working directory for path traversal."""
328 if cwd is None:
329 return None
331 if not self.config.enable_path_validation:
332 return Path(cwd) if isinstance(cwd, str) else cwd
334 cwd_path = Path(cwd) if isinstance(cwd, str) else cwd
336 try:
337 # Resolve to absolute path and check for traversal
338 resolved_path = cwd_path.resolve()
340 # Check for dangerous path components
341 path_str = str(resolved_path)
342 if ".." in path_str or path_str.startswith(
343 ("/etc", "/usr/bin", "/bin", "/sbin")
344 ):
345 self.security_logger.log_path_traversal_attempt(
346 attempted_path=path_str,
347 base_directory=None,
348 )
349 raise CommandValidationError(f"Dangerous working directory: {path_str}")
351 return resolved_path
353 except (OSError, ValueError) as e:
354 raise CommandValidationError(f"Invalid working directory '{cwd}': {e}")
356 def _sanitize_environment(self, env: dict[str, str] | None) -> dict[str, str]:
357 """Sanitize environment variables."""
358 if env is None:
359 env = os.environ.copy()
361 original_count = len(env)
362 filtered_vars = []
363 sanitized_env = {}
365 # Check total environment size
366 if len(env) > self.config.max_env_vars:
367 self.security_logger.log_security_event(
368 SecurityEventType.INPUT_SIZE_EXCEEDED,
369 SecurityEventLevel.HIGH,
370 f"Too many environment variables: {len(env)} > {self.config.max_env_vars}",
371 actual_count=len(env),
372 max_count=self.config.max_env_vars,
373 )
374 raise EnvironmentValidationError(
375 f"Too many environment variables: {len(env)} > {self.config.max_env_vars}"
376 )
378 for key, value in env.items():
379 # Check key safety
380 if key in self.dangerous_env_vars:
381 filtered_vars.append(key)
382 self.security_logger.log_environment_variable_filtered(
383 variable_name=key,
384 reason="dangerous environment variable",
385 value_preview=str(value)[:50] if value else None,
386 )
387 continue
389 # Check value length
390 if len(str(value)) > self.config.max_env_var_length:
391 filtered_vars.append(key)
392 self.security_logger.log_environment_variable_filtered(
393 variable_name=key,
394 reason=f"value too long: {len(str(value))} > {self.config.max_env_var_length}",
395 value_preview=str(value)[:50],
396 )
397 continue
399 # Check for injection in values
400 value_str = str(value)
401 has_injection = False
402 for pattern in self.dangerous_patterns[:3]: # Check first 3 most dangerous
403 if re.search(pattern, value_str):
404 filtered_vars.append(key)
405 self.security_logger.log_environment_variable_filtered(
406 variable_name=key,
407 reason=f"dangerous pattern '{pattern}' in value",
408 value_preview=value_str[:50],
409 )
410 has_injection = True
411 break
413 if not has_injection:
414 sanitized_env[key] = value_str
416 # Ensure essential environment variables are present
417 for safe_var in self.safe_env_vars:
418 if safe_var not in sanitized_env and safe_var in os.environ:
419 sanitized_env[safe_var] = os.environ[safe_var]
421 # Log sanitization results
422 if self.config.enable_command_logging:
423 self.security_logger.log_subprocess_environment_sanitized(
424 original_count=original_count,
425 sanitized_count=len(sanitized_env),
426 filtered_vars=filtered_vars,
427 )
429 return sanitized_env
431 def _validate_timeout(self, timeout: float | None) -> float | None:
432 """Validate timeout value."""
433 if timeout is None:
434 return None
436 if timeout <= 0:
437 raise CommandValidationError(f"Timeout must be positive: {timeout}")
439 if timeout > self.config.max_timeout:
440 self.security_logger.log_security_event(
441 SecurityEventType.INPUT_SIZE_EXCEEDED,
442 SecurityEventLevel.MEDIUM,
443 f"Timeout too large: {timeout} > {self.config.max_timeout}",
444 requested_timeout=timeout,
445 max_timeout=self.config.max_timeout,
446 )
447 raise CommandValidationError(
448 f"Timeout too large: {timeout} > {self.config.max_timeout}"
449 )
451 return timeout
454# Global secure executor instance
455_global_executor: SecureSubprocessExecutor | None = None
458def get_secure_executor(
459 config: SubprocessSecurityConfig | None = None,
460) -> SecureSubprocessExecutor:
461 """Get the global secure subprocess executor."""
462 global _global_executor
463 if _global_executor is None:
464 _global_executor = SecureSubprocessExecutor(config)
465 return _global_executor
468def execute_secure_subprocess(
469 command: list[str],
470 **kwargs: t.Any,
471) -> subprocess.CompletedProcess[str]:
472 """
473 Convenience function for secure subprocess execution.
475 This is the recommended way to execute subprocesses in Crackerjack.
476 """
477 executor = get_secure_executor()
478 return executor.execute_secure(command, **kwargs)