> For the complete documentation index, see [llms.txt](https://playbook.sidthoviti.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://playbook.sidthoviti.com/devsecops/secure-coding/code-review-examples/command-injection.md).

# Command Injection

**Example 1: Python**

**Vulnerable Code:**

```python
pythonCopy codeos.system("ls " + request.args.get('dir'))
```

**Reason for vulnerability:** User input is directly used in the command, allowing command injection.

**Fixed Code:**

```python
pythonCopy codedir = request.args.get('dir')
if not is_valid_directory(dir):
    abort(400)
os.system("ls " + dir)
```

**Reason for fix:** Validate and sanitize user input before using it in the command.

**Example 2: Java**

**Vulnerable Code:**

```java
javaCopy codeString dir = request.getParameter("dir");
Runtime.getRuntime().exec("ls " + dir);
```

**Reason for vulnerability:** User input is directly used in the command, allowing command injection.

**Fixed Code:**

```java
javaCopy codeString dir = request.getParameter("dir");
if (!isValidDirectory(dir)) {
    throw new IllegalArgumentException("Invalid directory");
}
Runtime.getRuntime().exec("ls " + dir);
```

**Reason for fix:** Validate and sanitize user input before using it in the command.

***

### Python Example

#### Vulnerable Code:

```python
pythonCopyimport os

def run_command(command):
    os.system(command)

def process_user_input(user_input):
    run_command(f"echo {user_input} >> log.txt")
```

#### Reason for Vulnerability:

This code directly incorporates user input into a shell command, allowing injection of arbitrary commands.

#### Fixed Code:

```python
pythonCopyimport subprocess
import shlex

def run_command(command, args):
    subprocess.run([command] + args, check=True)

def process_user_input(user_input):
    run_command("echo", [user_input, ">>", "log.txt"])
```

#### Reason for Fix:

The fixed code uses `subprocess.run` with a list of arguments, which prevents shell injection. It also uses `shlex.quote` for extra safety when constructing commands.

***

### Java Example

#### Vulnerable Code:

```java
javaCopyimport java.io.IOException;

public class PingUtility {
    public static String ping(String host) throws IOException {
        Process process = Runtime.getRuntime().exec("ping " + host);
        // Read and return process output
    }
}
```

#### Reason for Vulnerability:

This code directly incorporates user input into a shell command, allowing injection of arbitrary commands.

#### Fixed Code:

```java
javaCopyimport java.io.IOException;

public class PingUtility {
    public static String ping(String host) throws IOException {
        if (!isValidHostname(host)) {
            throw new IllegalArgumentException("Invalid hostname");
        }
        ProcessBuilder pb = new ProcessBuilder("ping", host);
        Process process = pb.start();
        // Read and return process output
    }

    private static boolean isValidHostname(String host) {
        return host.matches("^[a-zA-Z0-9.-]+$");
    }
}
```

#### Reason for Fix:

The fixed code validates the hostname and uses ProcessBuilder to safely construct the command.

### Ruby Example

#### Vulnerable Code:

```ruby
rubyCopydef execute_command(command)
  `#{command}`
end

puts execute_command(ARGV[0])
```

#### Reason for Vulnerability:

This code directly executes user-provided input as a shell command, allowing arbitrary command execution.

#### Fixed Code:

```ruby
rubyCopyrequire 'open3'

def execute_command(command, *args)
  raise ArgumentError, "Invalid command" unless ['ls', 'cat', 'echo'].include?(command)
  stdout, stderr, status = Open3.capture3(command, *args)
  raise "Command failed: #{stderr}" unless status.success?
  stdout
end

begin
  puts execute_command(ARGV[0], *ARGV[1..-1])
rescue ArgumentError, RuntimeError => e
  puts "Error: #{e.message}"
end
```

#### Reason for Fix:

The fixed code uses a whitelist of allowed commands and Open3.capture3 for safer command execution.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://playbook.sidthoviti.com/devsecops/secure-coding/code-review-examples/command-injection.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
