Skip to main content

Module safe_command

Module safe_command 

Source
Expand description

Safe command execution with validation to prevent command injection attacks

This module provides the SafeCommand type that wraps shell commands with validation to prevent common command injection vulnerabilities. All commands are validated on construction to ensure they:

  • Are in the whitelist of allowed commands
  • Do not contain shell metacharacters in arguments (;|&><$`\n)
  • Do not exceed maximum command length of 4096 characters
  • Use validated paths for path arguments

§Security Model

This module uses a multi-layered defense approach:

  1. Command Whitelist: Only explicitly allowed commands can be executed
  2. Argument Sanitization: Shell metacharacters are blocked in arguments
  3. Type-State Pattern: Commands must be validated before execution
  4. Path Integration: Path arguments use SafePath validation
  5. Length Limits: Maximum 4096 characters to prevent buffer overflow

§Examples

use ggen_utils::safe_command::{SafeCommand, CommandName, CommandArg};

// Valid command
let cmd = SafeCommand::new("cargo")
    .unwrap()
    .arg("build")
    .unwrap()
    .arg("--release")
    .unwrap()
    .validate()
    .unwrap();

// Invalid command (not in whitelist)
assert!(SafeCommand::new("rm").is_err());

// Invalid argument (shell metacharacter)
let result = SafeCommand::new("cargo")
    .unwrap()
    .arg("build; rm -rf /")
    .unwrap_or_else(|e| panic!("Should fail: {}", e));

Structs§

CommandArg
A validated command argument with sanitization
CommandName
A validated command name from the whitelist
SafeCommand
A safe command builder with type-state pattern
Unvalidated
Type-state marker for unvalidated commands
Validated
Type-state marker for validated commands