Patching a binary with dd
Let's try it. Here's a trivial C program:
#include <stdio.h>
int main(int argc, char **argv) {
puts("/usr/tmp");
}
We'll build that into test
:
$ cc -o test test.c
If we run it, it prints "/usr/tmp".
Let's find out where "/usr/tmp
" is in the binary:
$ strings -t d test | grep /usr/tmp
1460 /usr/tmp
-t d
prints the offset in decimal into the file of each string it finds.
Now let's make a temporary file with just "/tmp\0
" in it:
$ printf "/tmp\x00" > tmp
So now we have the binary, we know where the string we want to change is, and we have a file with the replacement string in it.
Now we can use dd
:
$ dd if=tmp of=test obs=1 seek=1460 conv=notrunc
This reads data from tmp
(our "/tmp\0
" file), writing it into our binary, using an output block size of 1 byte, skipping to the offset we found earlier before it writes anything, and explicitly not truncating the file when it's done.
We can run the patched executable:
$ ./test
/tmp
The string literal the program prints out has been changed, so it now contains "/tmp\0tmp\0
", but the string functions stop as soon as they see the first null byte. This patching only allows making the string shorter or the same length, and not longer, but it's adequate for these purposes.
So not only can we patch things using dd
, we've just done it.
It depends on what you mean by "patch the binary".
I change binaries using dd
sometimes. Of course there is no such feature in dd
, but it can open files, and read and write things at specific offsets, so if you know what to write where, voila there is your patch.
For example I had this binary that contained some PNG data. Use binwalk
to find the offset, dd
to extract it (usually binwalk also extracts things but my copy was buggy), edit it with gimp
, make sure the edited file is same size or smaller than the original one (changing offsets is not something you can do easily), and then use dd
to put the changed image back in place.
$ binwalk thebinary
[…]
4194643 0x400153 PNG image, 800 x 160, 8-bit/color RGB, non-interlaced
[…]
$ dd if=nickel bs=1 skip=4194641 count=2 conv=swab | od -i
21869 # file size in this case - depends on the binary format
$ dd if=thebinary bs=1 skip=4194643 count=21869 of=theimage.png
$ gimp theimage.png
$ pngcrush myimage.png myimage.crush.png
# make sure myimage.crush.png is smaller than the original
$ dd if=myimage.crush.png of=thebinary bs=1 seek=4194643 conv=notrunc
Sometimes I also wish to replace strings in binaries (such as path or variable names). While this could also be done using dd
, it is simpler to do so using sed
. You just have to make sure the string you replace with has the same length as the original string so you don't end up changing offsets.
sed -e s@/the/old/save/path@/the/new/save/path@ -i thebinary
or to pick up @MichaelHomer's example with a 0-byte added in:
sed -e 's@/usr/tmp@/tmp\x00tmp@' -i test
Of course you have to verify whether it actually works afterwards.