From 9e9b38c3b14625a7e853c68bcb30c1f9d33f165e Mon Sep 17 00:00:00 2001 From: Markus Koch Date: Mon, 15 Jun 2020 19:57:43 +0200 Subject: [PATCH] bash: Add patch_binary.sh --- README.MD | 3 +++ bash/patch_binary.sh | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 bash/patch_binary.sh diff --git a/README.MD b/README.MD index 5ec5a22..2b34df6 100644 --- a/README.MD +++ b/README.MD @@ -4,3 +4,6 @@ Small code snippets that might prove useful again in the future. ## C * report/: Easy to use report statement with log levels * sdprintf.c: sprintf to a dynamic buffer + +## Bash +* patch_binary.sh: Function to patch executables with asm payloads diff --git a/bash/patch_binary.sh b/bash/patch_binary.sh new file mode 100644 index 0000000..bf361fc --- /dev/null +++ b/bash/patch_binary.sh @@ -0,0 +1,41 @@ +# patch_binary(target file, asm payload, destination dynamic symbol, offset) +# The dynamic symbol may also be a hex address. +# offset must be in decimal representation. +function patch_binary() { + file="$1" + payload="$2" + sym="$3" + offset="$4" + payload_file="`mktemp`" + + echo "# Patching file $file @ $sym" + echo " Generating payload..." + echo "$payload" | rasm2 -a x86 -b64 -B -f - > "$payload_file" + + if [[ $sym = 0x* ]]; then + addr="`echo \"$sym\" | sed \"s/^0x//\"`" + else + echo " Preparing patch of dynamic location $sym + $offset" + addr=`nm -D "$file" 2>/dev/null | grep "$sym" | head -n1 | sed 's/ .*//'` + if [ "$addr" == "" ]; then + echo " Symbol not found. Skipping." + return 1; + fi + echo " Found symbol at $addr" + fi + load=`readelf -l "$file" | grep LOAD | head -n1 | sed 's/.* 0x//'` + load=`echo $((16#$load))` + addr=`echo $((16#$addr))` + addr=`echo $(($addr + $offset))` # This is also the address shown by r2 + paddr=`echo $(($addr - $load))` # The offset is added when copying to RAM; we need to subtract that + printf " Patching dynamic address 0x%x\n" "$addr" + printf " Load offset is 0x%x\n" "$load" + printf " Patching $file at physical offset 0x%x...\n" "$paddr" + dd if="$payload_file" of="$file" obs=1 seek="$paddr" conv=notrunc 2>&1 | sed 's/^/ /' + + rm "$payload_file" + echo " Done." + return 0 +} + +patch_binary $@