Write byte at address (hexedit/modify binary from the command line)

前端 未结 8 826
轻奢々
轻奢々 2020-12-02 12:25

Is there any straightforward way to modify a binary from the commandline? Let\'s say I know that my binary contains 1234abcd and i want to change it to 12FFabcd or FFFFabcd

相关标签:
8条回答
  • 2020-12-02 12:35

    Some alternatives:

    • HexAlter (open source compiled tool)
    • ucon64 --nbak --poke=OFF:V FILE (meant for ROM dumps, should work with any binary file, but no inplace editing)
    • printf '\x31' | dd of=FILE bs=1 seek=OFFSET count=1 conv=notrunc (wrapped in a shellscript like this that also allows reading)
    0 讨论(0)
  • 2020-12-02 12:42

    Writing the same byte at two different positions in the same file with a one liner.

    printf '\x00'| tee >(dd of=filename bs=1 count=1 seek=692 conv=notrunc status=none) \
        >(dd of=filename bs=1 count=1 seek=624 conv=notrunc status=none)
    

    status=none very useful when you don't want any statistics out of dd.

    0 讨论(0)
  • 2020-12-02 12:45

    xxd tool, which comes with vim (and thus is quite likely to be available) allows to hex dump a binary file and construct a new binary file from a modified hex dump.

    0 讨论(0)
  • 2020-12-02 12:47
    printf '\x31\xc0\xc3' | dd of=test_blob bs=1 seek=100 count=3 conv=notrunc 
    

    dd arguments:

    • of | file to patch
    • bs | 1 byte at a time please
    • seek | go to position 100 (decimal)
    • conv=notrunc | don't truncate the output after the edit (which dd does by default)

    One Josh looking out for another ;)

    0 讨论(0)
  • 2020-12-02 12:47

    The printf+dd based solutions do not seem to work for writing out zeros. Here is a generic solution in python3 (included in all modern distros) which should work for all byte values...

    #!/usr/bin/env python3
    #file: set-byte
    
    import sys
    
    fileName = sys.argv[1]
    offset = int(sys.argv[2], 0)
    byte = int(sys.argv[3], 0)
    
    with open(fileName, "r+b") as fh:
        fh.seek(offset)
        fh.write(bytes([byte]))
    

    Usage...

    set-byte eeprom_bad.bin 0x7D00 0
    set-byte eeprom_bad.bin 1000 0xff
    

    Note: This code can handle input numbers both in hex (prefixed by 0x) and dec (no prefix).

    0 讨论(0)
  • 2020-12-02 12:54

    If you don't need it to be scriptable, you could try the "hexedit" utility. It is available in many Linux distributions (if not installed by default, it can usually be found in the distro's package repository).

    If your distro doesn't have it, you can build and install it from source.

    0 讨论(0)
提交回复
热议问题