php.lang.security.tainted-exec.tainted-exec

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Executing non-constant commands. This can lead to command injection. You should use escapeshellarg() when using command.

Run Locally

Run in CI

Defintion

rules:
  - id: tainted-exec
    mode: taint
    pattern-sources:
      - pattern: $_REQUEST
      - pattern: $_GET
      - pattern: $_POST
      - pattern: $_COOKIE
    pattern-sinks:
      - pattern: exec(...)
      - pattern: system(...)
      - pattern: popen(...)
      - pattern: passthru(...)
      - pattern: shell_exec(...)
      - pattern: pcntl_exec(...)
      - pattern: proc_open(...)
    pattern-sanitizers:
      - pattern: escapeshellarg(...)
    message: Executing non-constant commands. This can lead to command injection.
      You should use `escapeshellarg()` when using command.
    metadata:
      cwe:
        - "CWE-94: Improper Control of Generation of Code ('Code Injection')"
      references:
        - https://www.stackhawk.com/blog/php-command-injection/
        - https://brightsec.com/blog/code-injection-php/
        - https://www.acunetix.com/websitesecurity/php-security-2/
      category: security
      technology:
        - php
      owasp:
        - A03:2021 - Injection
      cwe2022-top25: true
      subcategory:
        - vuln
      likelihood: HIGH
      impact: HIGH
      confidence: MEDIUM
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Code Injection
    languages:
      - php
    severity: ERROR

Examples

tainted-exec.php

<?php

$username = $_COOKIE['username'];
//ruleid: tainted-exec
exec("wto -n \"$username\" -g", $ret);


$fullpath = $_POST['fullpath'];
//ok: tainted-exec
$filesize = trim(shell_exec('stat -c %s ' . escapeshellarg($fullpath)));


$jobName = $_REQUEST['jobName'];
$cmd = sprintf("rsyncmd -l \"$xmlPath\" -r %s >/dev/null", $jobName);
//ruleid: tainted-exec
system($cmd);


$errorCode = escapeshellarg($_POST['errorCode']);
$func = escapeshellarg($_POST['func']);
$uuid = str_replace(PHP_EOL, '', file_get_contents("/proc/sys/kernel/random/uuid"));
$logsCmd = sprintf('%s%s%s',
  "wdlog -l INFO -s 'adminUI' -m 'firmware_upload_page' function:string=$func ",
  "status:string='updateFail' errorCode:string=$errorCode ",
  "corid:string='AUI:$uuid' >/dev/null 2>&1"
);
//ok: tainted-exec
exec($logsCmd);


$arg = $_POST['arg'];
$cmd = "logwdweb --post_migration_onboarding -%s %s";
$cmd_logwdweb = "logwdweb --post_migration_onboarding --page %s %s";
$_arg = sprintf("--status %s", $arg);
$cmd = sprintf($cmd_logwdweb, "raidRoaming", $_arg);
//ruleid: tainted-exec
pclose(popen($cmd, 'r'));
?>