---
# System prepended metadata

title: heXDump
tags: [xxd, HITCON CTF 2019 Quals]

---

# heXDump

## Challenge Summary

We are given an oracle, implemented with Ruby, that could control a temporary file. There are three functions:
1. Modify the file
2. Obtain a digest of the file - we can assume that the content is hashed with sha256.
3. Write the flag to the file

The objective is, of course, to read the flag.

## Solution

### Part I: How are the functions implemented?

Let us first take a look on how the file is updated (they call it write):
```ruby
def write
  puts 'Data? (In hex format)'
  data = gets
  return false unless data && !data.empty? && data.size < 0x1000

  IO.popen("xxd -r -ps - #{@file}", 'r+') do |f|
    f.puts data
    f.close_write
  end
  return false unless $CHILD_STATUS.success?

  true
end
```

As hinted from the challenge statement, it uses `xxd` somewhere. From the manpage of the `xxd` command, we spotted a curious property from the description of the `-r` flag:

```
-r | -revert
  reverse  operation:  convert (or patch) hexdump into binary.  If not writing to std‐
  out, xxd writes into its output file without truncating it. Use the  combination  -r
  -p  to  read  plain  hexadecimal dumps without line number information and without a
  particular column layout. Additional Whitespace and  line-breaks  are  allowed  any‐
  where.
```

It converts (or _patches_) the hexdump into binary. How does it work? Let's have an experiment:

```bash
> xxd -r -ps - test
404040
> cat test
@@@
> xxd -r -ps - test
6161
> cat test
aa@
```

That means that the first two bytes of the file are patched with the character `a`! The way to exploit is quite evident now:

1. Writes the flag to the file and reads its hash
2. Patches the first byte of the file and reads the updated hash - until the hash matches the target
3. Patches the first two bytes (we know what is the first byte - thus we need to exhaust the second only)
4. ???
5. Profit!

I have written a script and let it does the whole thing - and got the flag in no time!
`hitcon{xxd?XDD!ed45dc4df7d0b79}`

###### tags: `HITCON CTF 2019 Quals` `xxd`