Skip to main content

ggen_core/security/
command.rs

1//! Safe command execution to prevent command injection attacks
2//!
3//! **SECURITY ISSUE 3: Command Injection Prevention**
4//!
5//! This module provides safe wrappers around `std::process::Command` to prevent
6//! command injection attacks by avoiding shell execution and validating inputs.
7
8use crate::utils::error::{Error, Result};
9use std::path::Path;
10use std::process::{Command, Output};
11
12/// Error type for command execution failures
13#[derive(Debug, thiserror::Error)]
14pub enum CommandError {
15    #[error("Invalid command: {0}")]
16    InvalidCommand(String),
17
18    #[error("Command not allowed: {0}")]
19    NotAllowed(String),
20
21    #[error("Command execution failed: {0}")]
22    ExecutionFailed(String),
23
24    #[error("Invalid argument: {0}")]
25    InvalidArgument(String),
26
27    #[error("Command output invalid UTF-8")]
28    InvalidUtf8,
29}
30
31impl From<CommandError> for Error {
32    fn from(err: CommandError) -> Self {
33        Error::new(&err.to_string())
34    }
35}
36
37/// Safe command builder that prevents injection attacks
38///
39/// Instead of executing commands through a shell (vulnerable to injection),
40/// this executes programs directly with validated arguments.
41///
42/// # Security Features
43///
44/// - No shell execution (prevents `; rm -rf /` attacks)
45/// - Argument validation (prevents metacharacter injection)
46/// - Whitelist of allowed commands
47/// - Path validation for file operations
48///
49/// # Examples
50///
51/// ```rust
52/// use crate::security::command::SafeCommand;
53///
54/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
55/// // Safe: Direct program execution
56/// let output = SafeCommand::new("git")?
57///     .arg("init")?
58///     .execute()?;
59///
60/// // Unsafe equivalent that we prevent:
61/// // Command::new("sh").arg("-c").arg(user_input) // VULNERABLE!
62/// # Ok(())
63/// # }
64/// ```
65#[derive(Clone)]
66pub struct SafeCommand {
67    program: String,
68    args: Vec<String>,
69    current_dir: Option<String>,
70}
71
72impl SafeCommand {
73    /// Allowed commands whitelist
74    const ALLOWED_COMMANDS: &'static [&'static str] = &[
75        "git", "cargo", "npm", "node", "rustc", "rustup", "ls", "echo",
76    ];
77
78    /// Dangerous shell metacharacters to reject
79    const DANGEROUS_CHARS: &'static [char] = &[
80        ';', '|', '&', '$', '`', '\n', '\r', '<', '>', '(', ')', '{', '}',
81    ];
82
83    /// Create a new safe command
84    ///
85    /// # Security
86    ///
87    /// - Validates command is in whitelist
88    /// - Prevents shell execution
89    /// - Rejects commands with dangerous characters
90    pub fn new(program: &str) -> Result<Self> {
91        // Validate program name
92        if program.is_empty() {
93            return Err(CommandError::InvalidCommand("Empty command".to_string()).into());
94        }
95
96        // Check for dangerous characters
97        if program.chars().any(|c| Self::DANGEROUS_CHARS.contains(&c)) {
98            return Err(CommandError::InvalidCommand(format!(
99                "Command contains dangerous characters: {}",
100                program
101            ))
102            .into());
103        }
104
105        // Check whitelist
106        if !Self::ALLOWED_COMMANDS.contains(&program) {
107            return Err(CommandError::NotAllowed(format!(
108                "Command '{}' is not in allowed list",
109                program
110            ))
111            .into());
112        }
113
114        Ok(Self {
115            program: program.to_string(),
116            args: Vec::new(),
117            current_dir: None,
118        })
119    }
120
121    /// Add an argument to the command
122    ///
123    /// # Security
124    ///
125    /// - Validates argument doesn't contain shell metacharacters
126    /// - Prevents injection via argument expansion
127    pub fn arg(mut self, arg: &str) -> Result<Self> {
128        // Validate argument
129        if arg.chars().any(|c| Self::DANGEROUS_CHARS.contains(&c)) {
130            return Err(CommandError::InvalidArgument(format!(
131                "Argument contains dangerous characters: {}",
132                arg
133            ))
134            .into());
135        }
136
137        self.args.push(arg.to_string());
138        Ok(self)
139    }
140
141    /// Add multiple arguments
142    pub fn args<I, S>(mut self, args: I) -> Result<Self>
143    where
144        I: IntoIterator<Item = S>,
145        S: AsRef<str>,
146    {
147        for arg in args {
148            self = self.arg(arg.as_ref())?;
149        }
150        Ok(self)
151    }
152
153    /// Set the working directory
154    ///
155    /// # Security
156    ///
157    /// - Validates path exists and is a directory
158    /// - Prevents path traversal attacks
159    pub fn current_dir(mut self, dir: &Path) -> Result<Self> {
160        // Validate directory exists
161        if !dir.exists() {
162            return Err(Error::new(&format!(
163                "Directory does not exist: {}",
164                dir.display()
165            )));
166        }
167
168        if !dir.is_dir() {
169            return Err(Error::new(&format!(
170                "Path is not a directory: {}",
171                dir.display()
172            )));
173        }
174
175        // Store as string for later use
176        self.current_dir = Some(dir.to_string_lossy().to_string());
177        Ok(self)
178    }
179
180    /// Execute the command safely
181    ///
182    /// # Security
183    ///
184    /// - Uses direct program execution (no shell)
185    /// - All arguments are properly escaped
186    /// - Output is validated as UTF-8
187    pub fn execute(self) -> Result<Output> {
188        let mut cmd = Command::new(&self.program);
189
190        // Add arguments
191        for arg in &self.args {
192            cmd.arg(arg);
193        }
194
195        // Set working directory if specified
196        if let Some(dir) = &self.current_dir {
197            cmd.current_dir(dir);
198        }
199
200        // Execute command
201        let output = cmd
202            .output()
203            .map_err(|e| CommandError::ExecutionFailed(format!("{}: {}", self.program, e)))?;
204
205        Ok(output)
206    }
207
208    /// Execute and return stdout as String
209    ///
210    /// # Security
211    ///
212    /// - Validates output is valid UTF-8
213    /// - Returns error on non-zero exit code
214    pub fn execute_stdout(self) -> Result<String> {
215        let program = self.program.clone();
216        let output = self.execute()?;
217
218        if !output.status.success() {
219            let stderr = String::from_utf8_lossy(&output.stderr);
220            return Err(CommandError::ExecutionFailed(format!("{}: {}", program, stderr)).into());
221        }
222
223        String::from_utf8(output.stdout).map_err(|_| CommandError::InvalidUtf8.into())
224    }
225}
226
227/// Command executor with additional safety features
228pub struct CommandExecutor;
229
230impl CommandExecutor {
231    /// Execute a git command safely
232    pub fn git(args: &[&str]) -> Result<Output> {
233        let mut cmd = SafeCommand::new("git")?;
234        for arg in args {
235            cmd = cmd.arg(arg)?;
236        }
237        cmd.execute()
238    }
239
240    /// Execute a cargo command safely
241    pub fn cargo(args: &[&str]) -> Result<Output> {
242        let mut cmd = SafeCommand::new("cargo")?;
243        for arg in args {
244            cmd = cmd.arg(arg)?;
245        }
246        cmd.execute()
247    }
248
249    /// Execute an npm command safely
250    pub fn npm(args: &[&str]) -> Result<Output> {
251        let mut cmd = SafeCommand::new("npm")?;
252        for arg in args {
253            cmd = cmd.arg(arg)?;
254        }
255        cmd.execute()
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn test_safe_command_new_validates_whitelist() {
265        // Allowed command
266        assert!(SafeCommand::new("git").is_ok());
267        assert!(SafeCommand::new("cargo").is_ok());
268
269        // Disallowed command
270        assert!(SafeCommand::new("rm").is_err());
271        assert!(SafeCommand::new("sh").is_err());
272    }
273
274    #[test]
275    fn test_safe_command_rejects_dangerous_chars() {
276        // Dangerous characters in command
277        assert!(SafeCommand::new("git; rm -rf /").is_err());
278        assert!(SafeCommand::new("git | cat").is_err());
279        assert!(SafeCommand::new("git && ls").is_err());
280
281        // Dangerous characters in arguments
282        let cmd1 = SafeCommand::new("git").unwrap();
283        assert!(cmd1.arg("init; rm -rf /").is_err());
284
285        let cmd2 = SafeCommand::new("git").unwrap();
286        assert!(cmd2.arg("init | cat").is_err());
287    }
288
289    #[test]
290    fn test_safe_command_arg_validation() {
291        let cmd = SafeCommand::new("git").unwrap();
292
293        // Safe arguments
294        assert!(cmd.clone().arg("init").is_ok());
295        assert!(cmd.clone().arg("status").is_ok());
296
297        // Dangerous arguments
298        assert!(cmd.clone().arg("init; ls").is_err());
299        assert!(cmd.clone().arg("$(whoami)").is_err());
300        assert!(cmd.clone().arg("`whoami`").is_err());
301    }
302
303    #[test]
304    fn test_command_injection_prevention() {
305        // Attempt command injection via arguments
306        let result = SafeCommand::new("git")
307            .unwrap()
308            .arg("init")
309            .unwrap()
310            .arg("; rm -rf /");
311
312        assert!(result.is_err());
313
314        // Attempt command injection via command name
315        let result = SafeCommand::new("git; whoami");
316        assert!(result.is_err());
317    }
318
319    #[test]
320    fn test_executor_git() {
321        // This will fail if git is not installed, but tests the API
322        let result = CommandExecutor::git(&["--version"]);
323        // Just ensure it returns a Result
324        let _ = result;
325    }
326}