BETA O Shoulder está em beta — Os resultados às vezes podem estar incorretos. Seu feedback molda o que corrigimos a seguir. Compartilhar feedback
💻

Command Injection

Review child_process usage
🛡️ 3 regras detectam isto

Improper Neutralization of Special Elements used in an OS Command

User input is passed unsanitized to system shell commands, allowing attackers to execute arbitrary commands on the server.

Prevalência
Common
Found in many applications
Impacto
Critical
Full server compromise
Prevenção
Avoid shell
Use execFile, not exec
2 Prevenção
2 Prevenção

Como corrigir esta vulnerabilidade

Estratégias de prevenção para OS Command Injection baseadas em 3 regras de detecção do Shoulder.

Command Injection via os/exec CRITICAL

Use exec.Command with explicit arguments, never shell invocation

+14 -6 go
  package main
  
  import (
      "net/http"
      "os/exec"
- )
- 
- func handler(w http.ResponseWriter, r *http.Request) {
-     cmd := r.URL.Query().Get("cmd")
-     // Vulnerable: shell invocation with user input
-     output, _ := exec.Command("sh", "-c", cmd).Output()
+     "regexp"
+ )
+ 
+ var safePattern = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
+ 
+ func handler(w http.ResponseWriter, r *http.Request) {
+     filename := r.URL.Query().Get("file")
+     // Validate input
+     if !safePattern.MatchString(filename) {
+         http.Error(w, "Invalid filename", http.StatusBadRequest)
+         return
+     }
+     // Safe: explicit command with validated argument
+     output, _ := exec.Command("cat", filename).Output()
      w.Write(output)
  }
  
Command Injection via child_process CRITICAL

Use execFile/spawn with array arguments instead of exec with string commands

+5 -5 javascript
- const { exec } = require('child_process');
- 
- app.get('/convert', (req, res) => {
-   const filename = req.query.file;
-   exec(`convert ${filename} output.png`, (err, stdout) => {
+ const { execFile } = require('child_process');
+ 
+ app.get('/convert', (req, res) => {
+   const filename = req.query.file;
+   execFile('convert', [filename, 'output.png'], (err, stdout) => {
      res.send('Converted');
    });
  });
  
OS Command Injection CRITICAL

Use subprocess.run with list arguments and shell=False

+1 -1 python
  import subprocess
  from flask import request
  
  @app.route('/convert')
  def convert():
      filename = request.args.get('file')
-     subprocess.run(f'convert {filename} output.png', shell=True)
+     subprocess.run(['convert', filename, 'output.png'], check=True)
      return 'Done'
  
3 Detecção
3 Detecção

Encontre vulnerabilidades no seu código

Use o Shoulder para escanear seu código em busca de padrões Command Injection. 3 regras.

terminal
# Scan with Shoulder CLI
npx @shoulderdev/cli trust --cwe=78

# Or scan entire project
npx @shoulderdev/cli trust .
4 Sinais de Alerta
4 Sinais de Alerta

O que observar nas revisões de código

Estes padrões indicam vulnerabilidades potenciais de Command Injection. Procure-os durante revisões de código e auditorias de segurança.

🔴
user input flowing to os/exec command execution, enabling OS command injection go-command-injection
🔴
user input flowing to shell command execution functions javascript-command-injection
🔴
untrusted user input flowing into operating system command execution functions without proper saniti python-command-injection
5 Auditoria de código
5 Auditoria de código

Padrões de revisão manual

Ao revisar código manualmente, procure por estes padrões perigosos.

Sinais de alerta para procurar
query = + concatenação de strings
execute(f"... or execute("..." +
raw_query, rawQuery, executeRaw
${ or #{ dentro de strings SQL
6 Análise especializada
6 Análise especializada

Como especialistas em segurança pensam

O modelo mental que profissionais de segurança usam ao revisar esta vulnerabilidade.

1

Mapeie os pontos de entrada

Parâmetros de URL, corpos POST, cabeçalhos, cookies, uploads de arquivo.

2

Rastreie o fluxo de dados

Siga a entrada através do código. Ela é sanitizada?

3

Identifique os sumidouros

Where queries are executed: execute(), query()

4

Verifique as fronteiras de confiança

Observe dados armazenados usados em consultas.

🔍

Escaneie seu código para Command Injection

O Shoulder CLI encontra padrões vulneráveis em todo o seu código.