> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-5/file-repair/manual-byte-patching/trick-0240.md).

# Manual File Byte Patching with dd

***

Fix corrupted file sections by replacing incorrect bytes at specific offsets using `dd`. This is useful when file format specifications or known good data provide the correct byte sequences.

You can pipe the replacement bytes (generated using `printf` with hexadecimal values) directly into `dd`. Specify the target file with `of=<file>`, set block size to 1 byte (`bs=1`), define the starting position for writing with `seek=<offset>`, and limit the bytes written with `count=<bytes>`. The `conv=notrunc` option is crucial to avoid truncating the rest of the file. Without `conv=notrunc`, `dd` would truncate the output file at the end of the input data, potentially destroying the file's contents beyond the patched section. The `notrunc` operand ensures that the output file is not truncated at the end of the input file.

For instance, to fix a PNG magic number starting at offset 0:

```bash
printf '\x89PNG\r\n\x1a\n' | dd of=corrupted.png bs=1 seek=0 count=8 conv=notrunc
```

Alternatively, you can use a source file for the bytes, such as `/dev/zero` to write null bytes or `/dev/urandom` to write random bytes, demonstrating the seek and count parameters:

```bash
dd if=/dev/urandom of=/tmp/testfile bs=1 seek=10 count=5 conv=notrunc
```

This command writes 5 random bytes from `/dev/urandom` to `/tmp/testfile` starting at byte offset 10, without affecting the rest of the file's content. Using `/dev/zero` instead would write null bytes.

Another example demonstrates replacing bytes at a specific offset using `printf` and `dd`:

```bash
printf "\x53\x54\x55\x56" | dd of=file.bin bs=1 seek=10 count=4 conv=notrunc
```

This command writes the four bytes represented by the hexadecimal values `53 54 55 56` to the file `file.bin`, starting at offset 10.

This technique requires precise knowledge of the file format's structure, including the exact offsets and correct hexadecimal bytes for the elements you need to repair (e.g., magic numbers, chunk headers, CRCs, data segments). File magic numbers are the first few bytes of a file that identify its type. For example, a PNG file starts with `\x89PNG\r\n\x1a`. If these initial bytes are corrupted, the file may not be recognized or processed correctly by applications. Correcting the magic number using `dd` is a direct way to potentially fix such issues.
