BETA Shoulder está en beta — Los hallazgos a veces pueden ser incorrectos. Tu feedback da forma a lo que arreglamos a continuación. Compartir comentarios
💻

Command Injection

Review child_process usage
🛡️ 3 reglas detectan esto

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.

Prevalencia
Common
Found in many applications
Impacto
Critical
Full server compromise
Prevención
Avoid shell
Use execFile, not exec
2 Prevención
2 Prevención

Cómo corregir esta vulnerabilidad

Estrategias de prevención para OS Command Injection basadas en 3 reglas de detección de 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 Detección
3 Detección

Encuentra vulnerabilidades en tu código

Usa Shoulder para escanear tu código en busca de patrones Command Injection. 3 reglas.

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

# Or scan entire project
npx @shoulderdev/cli trust .
4 Señales de Alerta
4 Señales de Alerta

Qué buscar en las revisiones de código

Estos patrones indican vulnerabilidades potenciales de Command Injection. Búscalos durante las revisiones de código y auditorías de seguridad.

🔴
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 Auditoría de código
5 Auditoría de código

Patrones de revisión manual

Al revisar código manualmente, busca estos patrones peligrosos.

Señales de alerta a buscar
query = + concatenación de cadenas
execute(f"... or execute("..." +
raw_query, rawQuery, executeRaw
${ or #{ dentro de cadenas SQL
6 Análisis experto
6 Análisis experto

Cómo piensan los expertos en seguridad

El modelo mental que usan los profesionales de seguridad al revisar esta vulnerabilidad.

1

Mapea los puntos de entrada

Parámetros de URL, cuerpos POST, encabezados, cookies, subidas de archivos.

2

Rastrea el flujo de datos

Sigue la entrada a través del código. ¿Se sanea?

3

Identifica los sumideros

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

4

Verifica los límites de confianza

Vigila los datos almacenados que se usan en consultas.

🔍

Escanea tu base de código para Command Injection

Shoulder CLI encuentra patrones vulnerables en toda tu base de código.